Keep s3-maze Harbor-native (#1)
Browse files- Keep s3-maze Harbor-native (cc870f3ccae38151830f9f3bde1d52fbdf6dc31e)
- Link the maintained team recipe and archived run setup (78f8d79a7db31762e4afbac396ebf94f991f8ff3)
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- README.md+25-150
- budget.py+1-1
- check.py+6-114
- eval/metrics.pyDeleted-404
- generate.py+1-1
- legion/registries.confDeleted-13
- legion/spec.template.yamlDeleted-73
- legion/sweep/README.mdDeleted-87
- legion/sweep/health-log.shDeleted-27
- legion/sweep/plot.pyDeleted-293
- legion/sweep/serve-vllm.sbatchDeleted-33
- legion/sweep/setaside.pyDeleted-96
- legion/sweep/sweep.pyDeleted-570
- legion/team.mdDeleted-1
- legion/team.pyDeleted-101
- tasks/maze-t01/environment/docker-compose.yaml+2-2
- tasks/maze-t01/environment/maze/service.py+1-1
- tasks/maze-t01/environment/maze/success.py+1-2
- tasks/maze-t02/environment/docker-compose.yaml+2-2
- tasks/maze-t02/environment/maze/service.py+1-1
- tasks/maze-t02/environment/maze/success.py+1-2
- tasks/maze-t03/environment/docker-compose.yaml+2-2
- tasks/maze-t03/environment/maze/service.py+1-1
- tasks/maze-t03/environment/maze/success.py+1-2
- tasks/maze-t04/environment/docker-compose.yaml+2-2
- tasks/maze-t04/environment/maze/service.py+1-1
- tasks/maze-t04/environment/maze/success.py+1-2
- tasks/maze-t05/environment/docker-compose.yaml+2-2
- tasks/maze-t05/environment/maze/service.py+1-1
- tasks/maze-t05/environment/maze/success.py+1-2
- tasks/maze-t06/environment/docker-compose.yaml+2-2
- tasks/maze-t06/environment/maze/service.py+1-1
- tasks/maze-t06/environment/maze/success.py+1-2
- tasks/maze-t07/environment/docker-compose.yaml+2-2
- tasks/maze-t07/environment/maze/service.py+1-1
- tasks/maze-t07/environment/maze/success.py+1-2
- tasks/maze-t08/environment/docker-compose.yaml+2-2
- tasks/maze-t08/environment/maze/service.py+1-1
- tasks/maze-t08/environment/maze/success.py+1-2
- tasks/maze-t09/environment/docker-compose.yaml+2-2
- tasks/maze-t09/environment/maze/service.py+1-1
- tasks/maze-t09/environment/maze/success.py+1-2
- tasks/maze-t10/environment/docker-compose.yaml+2-2
- tasks/maze-t10/environment/maze/service.py+1-1
- tasks/maze-t10/environment/maze/success.py+1-2
- tasks/maze-t11/environment/docker-compose.yaml+2-2
- tasks/maze-t11/environment/maze/service.py+1-1
- tasks/maze-t11/environment/maze/success.py+1-2
- tasks/maze-t12/environment/docker-compose.yaml+2-2
- tasks/maze-t12/environment/maze/service.py+1-1
17 unmodified lines181920212223242526272829303135 unmodified lines6768697071727374757677787980818231 unmodified lines11411511611711811912012112212312412512612712812913055 unmodified lines1861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752761 unmodified line27827928028128228328428528628728828929029129229 unmodified lines3223233243253263273283293303313323333343353364 unmodified lines34134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939017 unmodified lines**communicates when it pays off**: any agent can find the exit alone, but the maze is too largefor one agent's move budget, so sharing what each one has explored lets a team search it intime. It adapts the parallel-exploration task of[s³: Simple Scaling of Swarms via Cooperative Multi-agent RL](https://arxiv.org/abs/2611.08615)([scalingswarms.com](https://scalingswarms.com)) to [Legion](https://github.com/huggingface/legion)swarms, whose agents talk over a shared message board. It isn't a replication of the paper: theagents are Pi with Legion's board, and the board is what we measure. Its companion,[s3-aggregation](https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation), needscommunication instead.**This dataset is private for now.**## The task35 unmodified linesenvironment/docker-compose.yaml main (the agent) and maze, on an internal network only main reachesenvironment/agent/ main's image: its Dockerfile and the `maze` command, nothing elseenvironment/maze/ the service's image: tree.json (private), engine.py, service.py,success.py (Legion's success check), export.py (the collect hook)tests/ the grader's own image: test.sh, grade.py, expected.jsonsolution/solve.sh an oracle that walks the shortest path with `maze move`template/ the files every task shares (generate.py copies them)legion/spec.template.yaml what every team's Legion run shares: model, board rules, loop, limitsteam.py writes one team's spec (the HF cluster, or local docker)registries.conf podman pulls Docker Hub images through mirror.gcr.iosweep/ the scaling sweep (every tree at N = 1..16, one model per grid): its READMEeval/metrics.py one row per team from Legion run directoriesgenerate.py writes tasks/ from its seed (115)budget.py the move-budget table below, from the service's own enginecheck.py the checks that need no model31 unmodified linesPython runs isolated (`python3 -I -S`). It keeps copies of `moves.jsonl` and `final.json` in`/logs/verifier/` for the metrics.**Stop on success.** Legion's `stop_on_success` with the service's `success_check`(`python3 -I -S /app/success.py`, run in the maze service, never in the agent's container)ends the run when the first agent gets out: the check is read-only and prints`{"success": <the exit was reached>, "evidence": {"exit_reached", "moves", "reached_at"}}`from the service's state. Legion polls it every 30 s per agent, then interrupts the turns,releases the workers and grades each agent's Trial.## The move budgetSimulated with the service's own engine (`template/environment/maze/engine.py`: every movegoes through the same `Walk` the service holds), without Legion or containers:`python budget.py` over the 32 trees, for N agents and a per-agent budget:- **(a)** one agent, depth-first: the first door it hasn't been through, in the listed order,55 unmodified lines(c) is what sharing explored branches can buy. The budget is in every task's tree, grader,instruction and `task.toml` (`move_budget`).## Run it with Legion on the HF clusterThe maze needs a second container per agent, so it runs where Legion runs Trials in docker orpodman. On the HF cluster: `compute: slurm`, one worker on **hopper-cpu** running the wholeteam in rootless podman with `podman-compose` (hopper-cpu has podman 4.9.3; the B200 nodes'podman 3.4.4 can't create Legion's per-agent networks), and a local board on that worker, neweach run. Legion's [`experiments/s3-maze/spec.yaml`](https://github.com/huggingface/legion/tree/main/experiments/s3-maze)runs one team (`TREE`, default `maze-t01`, and `N`, default 4) at the revision it pins; Legion's`docs/tasks.md` ("s3-maze") has the commands. For any other team, `legion/team.py` writes thespec from `legion/spec.template.yaml`, run from Legion's checkout:```shDS=/fsx/$USER/s3-maze # this dataset on the shared disk (the workers read registries.conf)hf download HuggingFaceSwarms/s3-maze --repo-type dataset --revision <sha> --local-dir $DSuv run python $DS/legion/team.py --tree 7 --agents 4 --out runs/src/maze-t07-n04uv run legion init $PWD/runs/maze-t07-n04 --from runs/src/maze-t07-n04 --profile cluster.env --secrets secrets.envexport LEGION_RUN_DIR=$PWD/runs/maze-t07-n04uv run legion launch $LEGION_RUN_DIR/experimentuv run legion status maze-t07-n04 # STOPPED ON SUCCESS once an agent gets outuv run legion stop maze-t07-n04 --release # ends the controller (and a run nobody won)uv run python $DS/eval/metrics.py $LEGION_RUN_DIR```**Needs:** a cluster profile with `SLURM_PARTITION=hopper-cpu`, `SLURM_MAX_MEM_PER_CPU_MB=2000`,`VENV` (Legion's venv on the shared disk) and `CONTAINERS_REGISTRIES_CONF=$DS/legion/registries.conf`(Docker Hub's pull limit hits the cluster's shared address hard); and a mode-600 secrets filewith `HF_TOKEN` (reads this private dataset and the run's bucket), `HF_INFERENCE_TOKEN` (afine-grained token with only "Make calls to Inference Providers", which goes into the agents'containers: never the same token), `NAMESPACE` and `BUCKET` (a private bucket for the run'sstate). The worker gets a CPU per agent and two more, at 1900 MB per CPU. hopper-cpuautoscales: a scale-up from 0 can take about 15 minutes.With stop on success, the run ends when the first agent reaches the exit: Legion grades everyTrial as it releases the worker, and the worker copies the grading (with the move logs) and theboard export to `<run dir>/results/` (Legion's `LEGION_RESULTS_DIR`), where `metrics.py` readsthem. A run that nobody wins ends its loop after 45 minutes or 6 rounds, and doesn't end byitself on Slurm: `legion stop --release` drains the worker, which is when its Trials are graded.### The board rulesThe same for every eval run, since they shape how agents talk (`legion/spec.template.yaml`):one channel, `#general`, and no more (`max_channels: 1`); an agent is woken by a mention or areply in its thread; a post is at most 1000 characters, at least 5 s after the agent's previousone, and at most 40 per agent. Podman enforces them in each agent's rule proxy.### The protocol hint`team.py --hint` adds `legion/team.md` as the team's `team_file`, which Legion appends to eachagent's instructions: "Before you go through a door, read the board and post which door you aretaking; pick one no teammate has claimed; post when a branch is a dead end." Without it, theteam gets the neutral instructions.## Metrics`uv run python eval/metrics.py RUN_DIR [RUN_DIR ...] [--out rows.jsonl]` writes one JSON lineper run directory (one team), as s3-aggregation's does, with the maze's fields added from themove logs the grader keeps:| field | || --- | --- || `task`, `agents`, `revision`, `stop_reason`, `duration_s` | the team and how its run ended || `success` | any agent's reward is 1 (`null`: no rewards found) || `rewards` | each agent's reward: its latest Trial's verifier result || `tokens`, `cost_usd` | the team's tokens (input, output, cache, reasoning) and cost || `posts`, `other_posts` | the team's board posts in the run; posts by anyone else || `per_agent` | each agent's reward, tokens, posts and turns || `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) || `centralization` | the paper's (Appendix M): the sum over agents of (k* - k_j) / (N - 1)^2, k_j the in-degree; `null` for N = 1 || `reciprocity` | the fraction of edges whose reverse exists; `null` without edges || `moves`, `refused_moves` | each agent's accepted and refused moves (over all its Trials) || `rooms`, `rooms_union` | the rooms each agent visited (the start included), and the team's together || `room_overlap` | the paper's (Appendix M): (V - U) / V, V = sum_i (\|R_i\| - 1), U = \|union of the R_i\| - 1: 0 when no two agents visit the same room, near 1 when all walk the same path; `null` when no agent moved || `exit_reached_by` | the agents whose walk reached the exit || `first_exit` | the first agent to reach the exit, how long after the team's Trials started, with how many moves of its own, and the team's moves by then; `null` when no agent got out || `missing` | what the run directory lacks (an agent's reward or move log, a move log's unreadable line, the board export), and where its spec and its Trials disagree |A reward and a move log count only from a Trial whose `result.json` holds Harbor's verifierresult: the agent's container can write into its `verifier/` folder while it works, and onlythe verifier's run replaces what is there. A Slurm run has no local bundle, so there the tokenscome from Harbor's Trial results (no reasoning split), and `stop_reason`, `cost_usd` and theturns are `null`. Its task and roster come from `experiment/spec.yaml` as the run resolved it:`${VAR}`s from `cluster.env` then `run.env`, else their defaults. Every agent the spec plannedis in the row, so one whose results are missing is flagged rather than dropped; so are Trialsof an agent the spec didn't plan, or of another task than it selects (e.g. a run directorywhose `run.env` is gone, read with the defaults).## Checks1 unmodified lineTrials (`uv` installs Harbor 0.25.0):```shuv run check.py --env podman # all of them (on the HF cluster: a hopper-cpu node, below)uv run check.py --env none # without the Trials```On the HF cluster, from Legion's checkout, with rootless podman set up as a worker has it:`srun -p hopper-cpu -c 8 --mem=15G bash -c 'source scripts/slurm/podman-node.sh &&CONTAINERS_REGISTRIES_CONF=$DS/legion/registries.conf .venv/bin/python $DS/check.py --env podman;podman_node_cleanup'`.1. **Generator:** `generate.py` reproduces `tasks/` byte for byte, and another seed gives othertrees, which record that seed in their `task.toml` and regenerate from it. Each tree has 391 rooms with distinct 4-digit labels, is a tree (390 two-way doors,all reachable), has 27 dead ends all 30 moves from the start, one of them the exit; the29 unmodified lines`maze` command and names no room, nor do the instruction, `task.toml` or the compose file;the exit is named only in the service's `tree.json`, `tests/expected.json` and`solution/solve.sh`; no folder beside `tasks/` holds a tree.5. **Metrics** (`eval/metrics.py`) on Slurm run directories made of the service's real exportsand the grader's real grades, with Legion's example spec (`${TREE:-maze-t01}`,`${N:-4}`): with no env files the row's task is `maze-t01` and its team four agents;`run.env` (over `cluster.env`) sets another tree and team size; a team with one agent'sresults gone keeps that agent and flags its reward and move log as missing; and the rowflags Trials of another task than the spec selects (a `run.env` gone) and of an agent thespec didn't plan.6. **Trials** (`--env podman` or `docker`, on `maze-t01`, with agents that need no model):- a walker runs Legion's success check in the maze service (false), walks the shortest pathwith `maze move`, runs it again (true), and scores 1, with the move log and the export inits verifier's folder;- Harbor's oracle agent (`solution/solve.sh`) scores 1;4 unmodified lines`/logs/artifacts` and `/logs/verifier`, a `reward.txt` of 1, a `json.py` and a`sitecustomize`, makes three moves short of the exit, and scores 0.Last run on a hopper-cpu node (podman 4.9.3), before the Legion rename: all checks passed.## Dummy runOne team, `maze-t01` with N = 4, from the pre-rename `experiments/s3-maze/spec.yaml` (dataset revision`0f1fe651`, whose `tasks/` are this revision's) on the HF cluster on 2026-11-17:`Qwen/Qwen3.8-27B` on the HF router (deepinfra), one hopper-cpu worker of 6 CPUs running thefour Trials in rootless podman, and a local board.- **The team found the exit.** agent-003 reached it after 154 moves, 10 min 22 s after theTrials started. Legion's success check saw it 27 s later, held the run, interrupted the otheragents and released the worker; every Trial was graded within a minute and the worker ended,at 11:50 UTC. Only agent-003 scored 1.- **They split the tree on the board** without being told to: agents posted the corridors theywalked, claimed branches at junctions, reported each dead end and re-planned around a silentteammate; agent-003 took the last unclaimed branch at the start room, and found the exit there.- **The budget binds.** agent-002 wrote a search script that walked into one dead end and thenbounced between it and its neighbour until its 200th move, and posted once.- **The metrics row** (`eval/metrics.py` on the run directory): `success` true; rewards 0, 0, 1,0; posts 7, 1, 12, 10; moves 101, 200, 154, 158 (one refused); rooms 52, 31, 93, 89, 211together; room overlap 0.195; no @-mentions or DMs, so no edges (centralization 0,reciprocity `null`); 413k input, 6.86M cached and 70k output tokens, about $1.20 on deepinfra;nothing missing.## Known limits- **HF Sandboxes can't run it:** each agent's Trial is two containers (the agent's and its mazeservice), and HF Sandboxes run one container per Trial. It needs multi-container supportthere, as AgentEscapeBench does. Until then it runs on docker or podman (the HF cluster).- **Private for now**, so whatever resolves and downloads the task (Legion's worker, and`legion init`/`launch`) needs a Hub token that can read it. The agents' containers never do.- **A new Trial starts a new maze.** If an agent's Trial fails and Legion starts another (or aworker is relaunched), that agent gets a fresh copy of the maze at the start, with a freshbudget, while its Pi session remembers the old walk. `metrics.py` counts moves over all of anagent's Trials, and its reward is its latest Trial's.- **The first exit ends the run, not the episode at once:** Legion checks every 30 s, so theother agents may move for up to about 30 s more before their turns are interrupted.- **The grader trusts the maze service.** The agent reaches it only through `maze look` and`maze move` (an internal network, two routes, bodies up to 4 KiB); an agent that could reachthe service any other way could forge its record. The service runs without capabilities, witha pids and memory limit, so flooding it only hurts the agent's own maze.- **The move log's `agent`** is the Trial's compose project (`<swarm>-<agent>-tN`), which namesthe Legion agent; `metrics.py` attributes moves by the Trial's folder instead.- **Not the paper's setup:** a per-agent move budget instead of a token allowance (looking andrefused moves are free), a message board instead of `message`/`read_messages` tools withnotifications, Legion's loop prompting again at each turn's end, the moves left in everyobservation, and N = 1 is a solo control.17 unmodified lines18192021222324252635 unmodified lines6263646566676869707131 unmodified lines10310410510610710810911011111211311411511611755 unmodified lines1731741751761771781791801811821831841851861871881891901911921931 unmodified line19519619719819920020120220320429 unmodified lines2342352362372382392402414 unmodified lines24624724824925025125225325425525625725825926026126226326426517 unmodified lines**communicates when it pays off**: any agent can find the exit alone, but the maze is too largefor one agent's move budget, so sharing what each one has explored lets a team search it intime. It adapts the parallel-exploration task of[s³: Simple Scaling of Swarms via Cooperative Multi-agent RL](https://arxiv.org/abs/2611.08615).The companion [s3-aggregation](https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation)requires communication to obtain the teammates' private numbers.## The task35 unmodified linesenvironment/docker-compose.yaml main (the agent) and maze, on an internal network only main reachesenvironment/agent/ main's image: its Dockerfile and the `maze` command, nothing elseenvironment/maze/ the service's image: tree.json (private), engine.py, service.py,success.py (exit status), export.py (the collect hook)tests/ the grader's own image: test.sh, grade.py, expected.jsonsolution/solve.sh an oracle that walks the shortest path with `maze move`template/ the files every task shares (generate.py copies them)generate.py writes tasks/ from its seed (115)budget.py the move-budget table below, from the service's own enginecheck.py the checks that need no model31 unmodified linesPython runs isolated (`python3 -I -S`). It keeps copies of `moves.jsonl` and `final.json` in`/logs/verifier/` for the metrics.**Exit status.** Run `python3 -I -S /app/success.py` in the maze service to read the exit state.It prints JSON with a `success` boolean and, when available, evidence with `exit_reached`,`moves` and `reached_at`. A team runner can use this signal to end the search before gradingthe Trials.## The move budgetSimulated with the service's own engine (`template/environment/maze/engine.py`: every movegoes through the same `Walk` the service holds), without containers:`python budget.py` over the 32 trees, for N agents and a per-agent budget:- **(a)** one agent, depth-first: the first door it hasn't been through, in the listed order,55 unmodified lines(c) is what sharing explored branches can buy. The budget is in every task's tree, grader,instruction and `task.toml` (`move_budget`).## Run a Harbor taskThe maze uses two containers per Trial, so use Docker or Podman. Validate the search andgrader with Harbor's oracle:```shuv run --with harbor==0.25.0 harbor run --path tasks/maze-t01 --agent oracle --env docker```For a cooperative run, give each participant its own Trial of the same task and supply ashared message board. The team succeeds if any participant earns 1.The maintained team recipe connects the exit status and a shared board. [Legion experiment](https://github.com/huggingface/legion/tree/main/experiments/s3-maze)The prior sweep and metrics are archived with the original run setup. [Dataset revision `3421ea2`](https://huggingface.co/datasets/HuggingFaceSwarms/s3-maze/tree/3421ea2d46e8963e59cf3690da6ea47739eefb2f)## Checks1 unmodified lineTrials (`uv` installs Harbor 0.25.0):```shuv run check.py --env podman # include the Trialsuv run check.py --env none # without the Trials```1. **Generator:** `generate.py` reproduces `tasks/` byte for byte, and another seed gives othertrees, which record that seed in their `task.toml` and regenerate from it. Each tree has 391 rooms with distinct 4-digit labels, is a tree (390 two-way doors,all reachable), has 27 dead ends all 30 moves from the start, one of them the exit; the29 unmodified lines`maze` command and names no room, nor do the instruction, `task.toml` or the compose file;the exit is named only in the service's `tree.json`, `tests/expected.json` and`solution/solve.sh`; no folder beside `tasks/` holds a tree.5. **Trials** (`--env podman` or `docker`, on `maze-t01`, with agents that need no model):- a walker runs the exit status check in the maze service (false), walks the shortest pathwith `maze move`, runs it again (true), and scores 1, with the move log and the export inits verifier's folder;- Harbor's oracle agent (`solution/solve.sh`) scores 1;4 unmodified lines`/logs/artifacts` and `/logs/verifier`, a `reward.txt` of 1, a `json.py` and a`sitecustomize`, makes three moves short of the exit, and scores 0.## Known limits- **HF Sandboxes can't run it:** each agent's Trial is two containers (the agent's and its mazeservice), and HF Sandboxes run one container per Trial. It needs multi-container supportthere, as AgentEscapeBench does. Until then it runs on docker or podman (the HF cluster).- **A new Trial starts a new maze.** It starts with a fresh position and move budget.- **The grader trusts the maze service.** The agent reaches it only through `maze look` and`maze move` (an internal network, two routes, bodies up to 4 KiB); an agent that could reachthe service any other way could forge its record. The service runs without capabilities, witha pids and memory limit, so flooding it only hurts the agent's own maze.- **The move log's `agent`** identifies the Trial's compose project.- **Not the paper's setup:** a per-agent move budget instead of a token allowance (looking andrefused moves are free), a message board instead of `message`/`read_messages` tools withnotifications, the moves left in everyobservation, and N = 1 is a solo control.
2 unmodified lines34567892 unmodified linesSimulates searches on the 32 trees in tasks/ with the maze service's own engine(template/environment/maze/engine.py: every move goes through engine.Walk, which refuses whatthe service refuses), without Legion or containers, and prints the success rate of each strategyby team size N and per-agent move budget, as the Markdown table in README.md:- (a) one agent, depth-first: it takes the first door it hasn't been through, in the order the2 unmodified lines34567892 unmodified linesSimulates searches on the 32 trees in tasks/ with the maze service's own engine(template/environment/maze/engine.py: every move goes through engine.Walk, which refuses whatthe service refuses), without containers, and prints the success rate of each strategyby team size N and per-agent move budget, as the Markdown table in README.md:- (a) one agent, depth-first: it takes the first door it hasn't been through, in the order the
12345620 unmodified lines2728293031323314 unmodified lines4849505152535455565758596061626328 unmodified lines9293949596979899100580 unmodified lines681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788240 unmodified lines102910301031103210331034103510361037103810391040104110421043# /// script# requires-python = ">=3.12"# dependencies = ["harbor==0.25.0", "pyyaml"]# ///"""s3-maze's checks that need no model (huggingface/legion#115, section 5):20 unmodified linesno answer names a room other than the current one and its doors (or what the agent askedfor); the exit is named only once the agent stands in it. The move log has one record permove request, refused ones included, each with agent, from, to and time, and its acceptedmoves are the walk. success.py (legion's success_check) says false until the exit is reachedand true after, and false for a missing or linked state file; export.py writes the service'srecord for the grader; a restarted service resumes the walk. The `maze` command prints theservice's JSON and exits 0, 1 for a refused move, 2 for a usage error.14 unmodified linesDockerfile and the `maze` command, and names no room; nor do the instruction, task.toml orthe compose file; the exit is named only in environment/maze/tree.json, tests/expected.jsonand solution/solve.sh; and no folder beside tasks/ holds a tree.5. Metrics (eval/metrics.py) on Slurm run directories made of real exports and grades, withthe example spec's `${TREE:-maze-t01}` and `${N:-4}`: with no env files the row's task ismaze-t01 and its team four agents; `run.env` (over `cluster.env`) sets another tree and teamsize, also with comments after quoted and unquoted values (read as legion reads them); a teamwith one agent's results gone keeps that agent and flags its reward and movelog as missing; and the row flags Trials of another task than the spec selects (a `run.env`gone) and of an agent the spec didn't plan, and a winning move log whose last line was cutoff.6. Trials (`--env`), on maze-t01, with agents that need no model:- a walker checks legion's success_check in the maze service (false), walks the shortest pathwith `maze move`, checks it again (true), and scores 1; the verifier's folder then holdsthe move log and the export;- Harbor's oracle agent (solution/solve.sh) scores 1;28 unmodified linessys.dont_write_bytecode = True # nothing new in tasks/ or template/sys.path.insert(0, str(HERE))sys.path.insert(0, str(HERE / "template" / "environment" / "maze"))sys.path.insert(0, str(HERE / "eval"))import generate as g # noqa: E402import metrics # noqa: E402from engine import Maze, Walk # noqa: E402LABEL = re.compile(rf"R\d{{{g.DIGITS}}}")580 unmodified linescheck(holders == {"environment/maze/tree.json", "tests/expected.json","solution/solve.sh"}, f"{task.name}: the exit is named in {holders}")beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {"tasks", "template", "legion", "eval", ".cache", "__pycache__", ".git"}check(not beside, f"folders beside tasks/: {sorted(beside)}")check(not LABEL.search("".join(p.read_text(errors="ignore")for p in (HERE / "template").rglob("*") if p.is_file())),"template/ names a room")# ------------------------------------------------------------------ metrics# The example spec's lines that metrics.py reads (Legion's experiments/s3-maze/spec.yaml)RUN_SPEC = """name: ${RUN_NAME:-s3-maze}naming: consecutive-idtask:repo: https://huggingface.co/datasets/HuggingFaceSwarms/s3-mazeselector: ${TREE:-maze-t01}revision: REVISIONagents:count: ${N:-4}"""def run_dir(root: Path, work: Path, tree: str, walks: dict[str, bool],env_files: dict[str, str]) -> Path:"""A Slurm run's directory, as `legion init` and the workers leave it: the spec, the envfiles and, per agent in `walks`, one Trial of `tree` (the exit reached or not) graded by thetask's own grader on the maze service's own export."""task = HERE / "tasks" / treelayout = tree_of(task)(root / "experiment").mkdir(parents=True)(root / "experiment" / "spec.yaml").write_text(RUN_SPEC)for name, text in env_files.items():(root / name).write_text(text)for k, (agent, wins) in enumerate(walks.items()):rooms = g.shortest_path(layout) if wins else dead_end_walk(layout, 20)source = evidence(task, work, f"{root.name}-{agent}", rooms)trial = root / "results" / "s3-maze" / agent / "trials" / f"s3-maze-{agent}-t1"env = {**os.environ, "EVIDENCE_DIR": str(source), "VERIFIER_DIR": str(trial / "verifier")}subprocess.run(["bash", str(task / "tests" / "test.sh")], env=env, capture_output=True,timeout=60, check=True)reward = float((trial / "verifier" / "reward.txt").read_text())(trial / "result.json").write_text(json.dumps({"task_name": f"HuggingFaceSwarms/{tree}", "trial_name": trial.name,"started_at": f"2026-11-17T11:38:1{k}+00:00","finished_at": "2026-11-17T11:50:04+00:00","agent_result": {"n_input_tokens": 1000, "n_cache_tokens": 800, "n_output_tokens": 50},"verifier_result": {"rewards": {"reward": reward}}}))return rootdef check_metrics(work: Path) -> int:team4 = {f"agent-{k:03d}": k == 3 for k in range(1, 5)}cases = { # name: (tree, walks, env files, task, agents, missing besides the board export)"defaults": ("maze-t01", team4, {}, "maze-t01", 4, []),"run.env": ("maze-t02", {"agent-001": True, "agent-002": False},{"cluster.env": "N=3\nTREE=maze-t05\n","run.env": "#TREE=maze-t01\nTREE=maze-t02\nN=2\nRUN_NAME=s3-maze-b\n"},"maze-t02", 2, []),# comments after values, read as legion's read_env_file does: a quoted value ends at# its quote, an unquoted one at ` #`"comments in env files": ("maze-t02", {"agent-001": True, "agent-002": False},{"cluster.env": "export N=3 # three\nTREE=maze-t05 # five\n","run.env": "TREE=\"maze-t02\" # group\nN=2 # pair\n""RUN_NAME='s3-maze-c' # name\n"},"maze-t02", 2, []),"an agent's results gone": ("maze-t01", {a: w for a, w in team4.items()if a != "agent-004"}, {}, "maze-t01", 4,["reward: agent-004", "move log: agent-004"]),"run.env gone": ("maze-t02", {"agent-001": True, "agent-002": False}, {}, "maze-t01", 4,["task: the spec selects 'maze-t01', the Trials ran maze-t02","reward: agent-003", "reward: agent-004", "move log: agent-003","move log: agent-004"]),"an unplanned agent": ("maze-t01", {"agent-001": True, "agent-002": False,"agent-003": False}, {"run.env": "N=2\n"},"maze-t01", 2,["agents: Trials of agents the spec didn't plan: agent-003"]),}for case, (tree, walks, env_files, task, agents, missing) in cases.items():name = "run-" + re.sub(r"\W+", "-", case)r = metrics.row(run_dir(work / name, work, tree, walks, env_files))expected_rewards = {a: float(w) for a, w in walks.items() if a in r["rewards"]}check(r["task"] == task and r["agents"] == agents and len(r["rewards"]) == agents,f"metrics, {case}: task {r['task']!r}, {r['agents']} agents, not {task!r}, {agents}")check(sorted(r["missing"]) == sorted(missing + ["board export"]),f"metrics, {case}: missing {r['missing']}")check({a: v for a, v in r["rewards"].items() if v is not None} == expected_rewardsand r["success"] is any(expected_rewards.values()),f"metrics, {case}: rewards {r['rewards']}")moved = {a: 30 if w else 20 for a, w in walks.items() if a in r["rewards"]}check({a: n for a, n in r["moves"].items() if a in moved} == moved,f"metrics, {case}: moves {r['moves']}")# a winning move log whose last line was cut off (a Trial stopped mid-write): its moves and# its exit are unknown, so the row flags it as missing rather than counting 29 movesroot = run_dir(work / "run-a-cut-off-move-log", work, "maze-t01",{"agent-001": True, "agent-002": False}, {"run.env": "N=2\n"})log = root / "results/s3-maze/agent-001/trials/s3-maze-agent-001-t1/verifier/moves.jsonl"log.write_text(log.read_text().rstrip("\n")[:-20])r = metrics.row(root)check(any(m.startswith("move log: agent-001 (line 30 of 30 unreadable)") for m in r["missing"]),f"metrics, a cut-off move log: missing {r['missing']}")return len(cases) + 1# ------------------------------------------------------------------ Trials# Runs in the agent's container as `python3 -c PROBE_PY <base64 config>`; its config travels240 unmodified linesbefore = len(failures)check_files()print(f"4. no-cheat (files): {len(failures) - before} failures")before = len(failures)cases = check_metrics(work)print(f"5. metrics: {len(failures) - before} failures; {cases} run directories")if args.env != "none":before = len(failures)jobs = args.jobs_dir or work / "jobs"jobs.mkdir(parents=True, exist_ok=True)report = asyncio.run(check_trials(args.env, jobs, work))print(f"6. Trials on {args.env} ({PROBE_TASK}): {len(failures) - before} failures; "f"{json.dumps(report)}")for failure in failures:print("FAIL:", failure)12345620 unmodified lines2728293031323314 unmodified lines484950515253545528 unmodified lines84858687888990580 unmodified lines671672673674675676677678679680681682683240 unmodified lines924925926927928929930931932933934935# /// script# requires-python = ">=3.12"# dependencies = ["harbor==0.25.0"]# ///"""s3-maze's checks that need no model (huggingface/legion#115, section 5):20 unmodified linesno answer names a room other than the current one and its doors (or what the agent askedfor); the exit is named only once the agent stands in it. The move log has one record permove request, refused ones included, each with agent, from, to and time, and its acceptedmoves are the walk. success.py says false until the exit is reachedand true after, and false for a missing or linked state file; export.py writes the service'srecord for the grader; a restarted service resumes the walk. The `maze` command prints theservice's JSON and exits 0, 1 for a refused move, 2 for a usage error.14 unmodified linesDockerfile and the `maze` command, and names no room; nor do the instruction, task.toml orthe compose file; the exit is named only in environment/maze/tree.json, tests/expected.jsonand solution/solve.sh; and no folder beside tasks/ holds a tree.5. Trials (`--env`), on maze-t01, with agents that need no model:- a walker checks success.py in the maze service (false), walks the shortest pathwith `maze move`, checks it again (true), and scores 1; the verifier's folder then holdsthe move log and the export;- Harbor's oracle agent (solution/solve.sh) scores 1;28 unmodified linessys.dont_write_bytecode = True # nothing new in tasks/ or template/sys.path.insert(0, str(HERE))sys.path.insert(0, str(HERE / "template" / "environment" / "maze"))import generate as g # noqa: E402from engine import Maze, Walk # noqa: E402LABEL = re.compile(rf"R\d{{{g.DIGITS}}}")580 unmodified linescheck(holders == {"environment/maze/tree.json", "tests/expected.json","solution/solve.sh"}, f"{task.name}: the exit is named in {holders}")beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {"tasks", "template", ".cache", "__pycache__", ".git"}check(not beside, f"folders beside tasks/: {sorted(beside)}")check(not LABEL.search("".join(p.read_text(errors="ignore")for p in (HERE / "template").rglob("*") if p.is_file())),"template/ names a room")# ------------------------------------------------------------------ Trials# Runs in the agent's container as `python3 -c PROBE_PY <base64 config>`; its config travels240 unmodified linesbefore = len(failures)check_files()print(f"4. no-cheat (files): {len(failures) - before} failures")if args.env != "none":before = len(failures)jobs = args.jobs_dir or work / "jobs"jobs.mkdir(parents=True, exist_ok=True)report = asyncio.run(check_trials(args.env, jobs, work))print(f"5. Trials on {args.env} ({PROBE_TASK}): {len(failures) - before} failures; "f"{json.dumps(report)}")for failure in failures:print("FAIL:", failure)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404"""One row per team from s³ runs (huggingface/legion#115): `uv run eval/metrics.pyRUN_DIR [RUN_DIR ...] [--out rows.jsonl]`.
s3-aggregation's eval/metrics.py, with s3-maze's move-log metrics added (`maze_moves` inEXTRAS). A run directory is one team: a local run's bundle (`.legion/<swarm>-<time>/`,docs/local.md), or a Slurm run's directory (`legion init`'s RUN_DIR, docs/slurm.md), where theworkers copy what a run is graded on into `results/`. Under either, each agent's Trials(`<agent>/trials/<swarm>-<agent>-tN/`: Harbor's `result.json` and `verifier/`) and the boardexport (`resources/message_board/{board.jsonl,channels.json}`) are found anywhere. Each row (oneJSON line; README.md has every field):- the task and team size, how the run ended, and `success`: any agent's reward is 1;- per agent: its reward (its latest Trial with a verifier result), tokens and board posts;- the message graph: an edge from a sender to each teammate it mentions (`@agent-002`; a group mention such as `@all` names every member) or messages directly (a DM or a private channel of the two), with in-degree centralization and reciprocity as in the s³ paper's Appendix M. A post that mentions no one adds no edge;- for the maze: each agent's moves, the rooms it visited and the team's room overlap, from the move logs the grader keeps in each Trial's `verifier/`;- `missing`: what the run directory lacks (an agent's reward or move log, the board export) or where its spec and its Trials disagree, so a row never passes for complete when it is not.
A reward and a move log count only from a Trial whose `result.json` holds Harbor's verifierresult: the agent's container can write into `verifier/` while it works, and only theverifier's run replaces what is there.
A local run's `run.json` gives the spec, the agents, their tokens (summed over models), thecost and how the run ended. A Slurm run has no such bundle: the task and the roster come fromits `experiment/spec.yaml` as the run resolved it (its `${VAR}`s from `cluster.env` and`run.env`, else their defaults), each agent's tokens from its Trials' results (no reasoningsplit), and the run's span from its Trials. Every agent the spec planned has a row entry, soone without results shows in `missing`; so do Trials of an unplanned agent or of another taskthan the spec selects (e.g. a run directory whose `run.env` is gone, read with the defaults).The board may hold earlier runs' messages (a reused Space): only those posted within the run'sspan count."""
import argparseimport fnmatchimport jsonimport reimport sysfrom collections import Counterfrom collections.abc import Callablefrom datetime import datetimefrom pathlib import Path
import yaml
TOKEN_FIELDS = ("input", "output", "cache_read", "cache_write", "reasoning")
def load_json(path: Path): return json.loads(path.read_text(encoding="utf-8"))
def epoch(value) -> float: return float(value) if isinstance(value, int | float) else datetime.fromisoformat( value).timestamp()
def bundle(run_dir: Path) -> dict | None: """A local run's run.json; None for a Slurm run (its controller's run.json, in the bucket, holds neither the spec nor the agents).""" path = run_dir / "run.json" doc = load_json(path) if path.is_file() else {} return doc if "spec" in doc and "agents" in doc else None
def all_trials(run_dir: Path) -> dict[str, list[Path]]: """Each agent's Trial directories, oldest first: `<agent>/trials/<swarm>-<agent>-t<N>/` (a local run's agents/_harbor/, a Slurm run's results/<swarm>/), one per Trial name.""" found: dict[str, dict[str, tuple[int, Path]]] = {} for trial in run_dir.rglob("trials/*"): agent = trial.parent.parent.name m = re.fullmatch(rf"(?:.+-)?{re.escape(agent)}-t(\d+)", trial.name) if m and trial.is_dir(): found.setdefault(agent, {}).setdefault(trial.name, (int(m[1]), trial)) return {a: [p for _, p in sorted(t.values())] for a, t in sorted(found.items())}
def results(trials: list[Path]) -> list[dict]: return [load_json(t / "result.json") for t in trials if (t / "result.json").is_file()]
def verified(trial: Path) -> dict | None: """Harbor's verifier rewards for a Trial, or None when its verifier didn't run.""" result = trial / "result.json" if not result.is_file() or result.is_symlink(): return None return (load_json(result).get("verifier_result") or {}).get("rewards") or None
def reward(trials: list[Path]) -> float | None: """The reward of the agent's latest Trial that has one.""" for trial in reversed(trials): rewards = verified(trial) if rewards and "reward" in rewards: return float(rewards["reward"]) return None
def bundle_tokens(agent: dict) -> dict[str, int]: usage = dict.fromkeys(TOKEN_FIELDS, 0) for by_model in (agent.get("tokens") or {}).values(): for key in TOKEN_FIELDS: usage[key] += int(by_model.get(key) or 0) return usage
def trial_tokens(trials: list[Path]) -> dict[str, int]: """Harbor's counts: its input includes the cached tokens.""" usage = dict.fromkeys(TOKEN_FIELDS, 0) for result in results(trials): agent = result.get("agent_result") or {} cached = int(agent.get("n_cache_tokens") or 0) usage["input"] += int(agent.get("n_input_tokens") or 0) - cached usage["cache_read"] += cached usage["output"] += int(agent.get("n_output_tokens") or 0) return usage
def board(run_dir: Path, start: float, end: float) -> tuple[list[dict], dict[int, dict], bool]: """(the run's messages, oldest first, channels by id, whether an export was found).""" messages, channels, found = {}, {}, False for export in run_dir.rglob("resources/message_board/board.jsonl"): found = True listing = export.with_name("channels.json") for channel in load_json(listing) if listing.is_file() else []: channels[channel["id"]] = channel for line in export.read_text(encoding="utf-8").splitlines(): if line.strip(): record = json.loads(line) message = record["message"] | {"channel_id": record["channel_id"]} if start <= epoch(message["created_at"]) <= end: messages[message["id"]] = message return sorted(messages.values(), key=lambda m: m["id"]), channels, found
def sender(message: dict) -> str | None: return (message.get("sender") or {}).get("external_id")
def edges(messages: list[dict], channels: dict[int, dict], team: list[str]) -> set[tuple]: """(sender, receiver) for each teammate a message mentions or is sent to directly.""" members = set(team) out = set() for message in messages: source = sender(message) if source not in members: continue targets = {m.get("external_id") for m in message.get("mentions") or []} channel = channels.get(message["channel_id"]) or {} if channel.get("kind") in ("dm", "private"): inside = {m.get("external_id") for m in channel.get("members") or []} & members if len(inside) == 2 and source in inside: # a DM, or a private channel of the two targets |= inside out |= {(source, target) for target in targets & members if target != source} return out
def centralization(graph: set[tuple], team: list[str]) -> float | None: """Appendix M: sum over agents of (k* - k_j) / (N - 1)^2, k_j agent j's in-degree and k* the largest: 0 when everyone receives from as many teammates, 1 when one agent receives from everyone and no one else from anyone. None for a team of one.""" n = len(team) if n < 2: return None degree = Counter(target for _, target in graph) k = [degree[a] for a in team] return sum(max(k) - kj for kj in k) / (n - 1) ** 2
def reciprocity(graph: set[tuple]) -> float | None: """Appendix M: the fraction of edges whose reverse edge exists. None without edges.""" return sum((b, a) in graph for a, b in graph) / len(graph) if graph else None
def maze_moves(run_dir: Path, team: list[str], trials: dict[str, list[Path]]) -> dict: """s3-maze: from each agent's move logs (`verifier/moves.jsonl`, with the export's `final.json` for its start room), its accepted and refused moves, the rooms it visited (R_i: the start and every room it moved into, over all its Trials) and whether it reached the exit; and the team's room overlap, Appendix M's (V - U) / V with V = sum_i (|R_i| - 1) and U = |union of the R_i| - 1: 0 when no two agents visit the same room, near 1 when all walk the same path; None when no agent moved. And the first exit: which agent reached it, how long after the team's Trials started (the earliest `started_at`), with how many moves of its own, and how many moves the whole team had made by then (`first_exit`, None when no agent got out). Empty for a run without move logs (not a maze).""" per_agent, union, missing, any_log = {}, set(), [], False accepted, exits = [], [] # (time, agent) of every accepted move; (time, agent, its moves) for name in team: rooms, moves, refused, reached, logs = set(), 0, 0, False, 0 for trial in trials.get(name, []): log, final = trial / "verifier" / "moves.jsonl", trial / "verifier" / "final.json" if verified(trial) is None or not log.is_file() or log.is_symlink(): continue logs += 1 export = {} if final.is_file() and not final.is_symlink(): export = load_json(final) rooms.add(export.get("start")) reached |= export.get("reached") is True last, own = None, 0 lines = log.read_text(encoding="utf-8").splitlines() for i, line in enumerate(lines): try: record = json.loads(line) if line.strip() else {} except ValueError: # e.g. cut off when the Trial stopped mid-write: the moves # (or the exit) after it are unknown, so the run doesn't count missing.append(f"move log: {name} (line {i + 1} of {len(lines)} unreadable)") continue if record.get("ok") is True: moves += 1 own += 1 rooms |= {record["from"], record["to"]} last = (epoch(record["time"]), record["to"]) accepted.append((last[0], name)) elif record: refused += 1 if export.get("reached") is True and last and last[1] == export.get("room"): exits.append((last[0], name, own)) rooms.discard(None) any_log |= logs > 0 if not logs: missing.append(f"move log: {name}") per_agent[name] = {"moves": moves, "refused": refused, "rooms": len(rooms), "reached_exit": reached} union |= rooms if not any_log: return {} v = sum(max(a["rooms"] - 1, 0) for a in per_agent.values()) first_exit = None if exits: at, who, own = min(exits) started = [epoch(r["started_at"]) for ts in trials.values() for r in results(ts) if r.get("started_at")] first_exit = {"agent": who, "agent_moves": own, "team_moves": sum(1 for t, _ in accepted if t <= at), "after_s": round(at - min(started), 1) if started else None} return {"moves": {n: a["moves"] for n, a in per_agent.items()}, "first_exit": first_exit, "refused_moves": {n: a["refused"] for n, a in per_agent.items()}, "rooms": {n: a["rooms"] for n, a in per_agent.items()}, "rooms_union": len(union), "room_overlap": (v - (len(union) - 1)) / v if v else None, "exit_reached_by": [n for n, a in per_agent.items() if a["reached_exit"]], "missing_moves": missing}
# Per-environment metrics: f(run_dir, team, Trial dirs by agent) -> extra row fields.EXTRAS: list[Callable[[Path, list[str], dict[str, list[Path]]], dict]] = [maze_moves]
def local_run(run: dict) -> dict: """What a local bundle says about the run.""" harbor = next((t.get("harbor") or {} for t in run["spec"]["types"].values()), {}) task = (harbor.get("config") or {}).get("task") or {} agents = sorted(run["agents"], key=lambda a: a["name"]) return {"swarm": run.get("swarm"), "task": task, "team": [a["name"] for a in agents], "start": epoch(run["started_at"]), "end": epoch(run["ended_at"]), "stop_reason": run.get("stop_reason"), "duration_s": run.get("duration_s"), "cost_usd": (run.get("totals") or {}).get("cost_usd"), "tokens": {a["name"]: bundle_tokens(a) for a in agents}, "turns": {a["name"]: a.get("turns_completed") for a in agents}}
PLACEHOLDER = re.compile(r"\$\{([A-Z_][A-Z0-9_]*)(?::-([^}]*))?\}")
def env_value(raw: str) -> str: """A `NAME=value` line's value as Legion reads it (specrender.read_env_file): a quoted value ends at its closing quote (what follows is a comment), an unquoted one at ` #`.""" value = raw.strip() if value and value[0] in "'\"" and (end := value.find(value[0], 1)) > 0: return value[1:end] return re.split(r"\s+#", raw, maxsplit=1)[0].strip()
def run_values(run_dir: Path) -> dict[str, str]: """The run's `cluster.env` then `run.env` (later wins), as the jobs read them: what fills the spec's `${VAR}`s. Lines Legion would refuse (no `=`, a bad name) are skipped.""" values = {} for name in ("cluster.env", "run.env"): path = run_dir / name for line in path.read_text().splitlines() if path.is_file() else []: line = line.strip() if not line or line.startswith("#"): continue key, sep, raw = line.removeprefix("export ").partition("=") if sep and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key.strip()): values[key.strip()] = env_value(raw) return values
def expand(text: str, values: dict[str, str]) -> str: """`${VAR}` and `${VAR:-default}` in the spec's text, as Legion fills them (empty = unset).""" return PLACEHOLDER.sub(lambda m: values.get(m[1]) or (m[2] if m[2] is not None else m[0]), text)
def slurm_run(run_dir: Path, trials: dict[str, list[Path]]) -> dict: """What a Slurm run's directory says: its spec as the run resolved it (`legion init`'s copy of the experiment, its `${VAR}`s filled from `cluster.env` then `run.env`, else their defaults) and the Trials the workers kept. The spec gives the task and the roster: every agent it planned is in the row, so one whose results are missing is flagged, not dropped. `problems` says where the spec and the Trials disagree (e.g. a `run.env` that is gone, its values replaced by the defaults).""" path = run_dir / "experiment" / "spec.yaml" spec = (yaml.safe_load(expand(path.read_text(), run_values(run_dir))) if path.is_file() else None) or {} problems = [] if spec else ["spec: no experiment/spec.yaml"] agents = spec.get("agents") or {} count = agents.get("count") if type(agents.get("count")) is int else None if spec and count is None: problems.append(f"spec: agents.count is {agents.get('count')!r}, not a number") if spec.get("naming") == "consecutive-id" and count is not None: team = [f"agent-{k:03d}" for k in range(1, count + 1)] else: team = list(trials) if count is not None and len(team) < count: problems.append(f"agents: {len(team)} of the {count} planned have Trials") if outside := sorted(set(trials) - set(team)): problems.append(f"agents: Trials of agents the spec didn't plan: {', '.join(outside)}") times = [(epoch(r["started_at"]), epoch(r["finished_at"])) for ts in trials.values() for r in results(ts) if r.get("started_at") and r.get("finished_at")] start, end = (min(t[0] for t in times), max(t[1] for t in times)) if times else (0, 0) ran = sorted({r["task_name"].split("/")[-1] for ts in trials.values() for r in results(ts) if r.get("task_name")}) task = spec.get("task") or {"selector": ran[0] if len(ran) == 1 else None} selector = task.get("selector") or "" if odd := [name for name in ran if not fnmatch.fnmatchcase(name, selector)]: problems.append(f"task: the spec selects {selector!r}, the Trials ran {', '.join(odd)}") swarm = next((t.name.removesuffix(f"-{a}-t{t.name.rsplit('-t', 1)[1]}") for a, ts in trials.items() for t in ts), spec.get("name")) return {"swarm": swarm, "task": task, "team": team, "start": start, "end": end, "stop_reason": None, "duration_s": round(end - start, 1) if times else None, "cost_usd": None, "tokens": {a: trial_tokens(trials.get(a, [])) for a in team}, "turns": dict.fromkeys(team), "problems": problems}
def row(run_dir: Path) -> dict: trials = all_trials(run_dir) run = bundle(run_dir) info = local_run(run) if run is not None else slurm_run(run_dir, trials) team = info["team"] messages, channels, exported = board(run_dir, info["start"], info["end"]) posts = Counter(sender(m) for m in messages) graph = edges(messages, channels, team) per_agent, missing = {}, list(info.get("problems", [])) for name in team: value = reward(trials.get(name, [])) if value is None: missing.append(f"reward: {name}") per_agent[name] = {"reward": value, "tokens": info["tokens"][name], "posts": posts[name], "turns": info["turns"][name]} if not exported: missing.append("board export") rewards = [a["reward"] for a in per_agent.values() if a["reward"] is not None] task = info["task"] out = { "run": run_dir.name, "swarm": info["swarm"], "task": re.sub(r"-s\*$", "", task.get("selector") or "") or None, # a team's slots "dataset": task.get("repo"), "revision": task.get("revision"), "agents": len(team), "stop_reason": info["stop_reason"], "duration_s": info["duration_s"], "success": any(r == 1 for r in rewards) if rewards else None, "rewards": {name: a["reward"] for name, a in per_agent.items()}, "tokens": {key: sum(a["tokens"][key] for a in per_agent.values()) for key in TOKEN_FIELDS}, "cost_usd": info["cost_usd"], "posts": sum(posts[name] for name in team), "other_posts": sum(n for who, n in posts.items() if who not in team), "per_agent": per_agent, "edges": sorted([a, b] for a, b in graph), "centralization": centralization(graph, team), "reciprocity": reciprocity(graph), "missing": missing, } for extra in EXTRAS: fields = extra(run_dir, team, trials) out["missing"] += fields.pop("missing_moves", []) out |= fields return out
def main(argv=None) -> int: parser = argparse.ArgumentParser(description="One row per team (JSON lines) from s³ runs.") parser.add_argument("run_dirs", nargs="+", type=Path) parser.add_argument("--out", type=Path, help="append the rows here (default: stdout)") args = parser.parse_args(argv) rows = [json.dumps(row(d)) for d in args.run_dirs] if args.out: with args.out.open("a", encoding="utf-8") as f: f.write("".join(r + "\n" for r in rows)) else: print("\n".join(rows)) return 0
if __name__ == "__main__": sys.exit(main())185 unmodified lines186187188189190191192185 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {{}} # main's way out (Flock replaces it with the agent's own network)maze:internal: true"""185 unmodified lines186187188189190191192185 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {{}} # main's egress networkmaze:internal: true"""
12345678910111213# podman's registries for the workers (CONTAINERS_REGISTRIES_CONF in the cluster profile):# Docker Hub images through Google's pull-through mirror first, since each worker job pulls the# task's base image into its own storage and the cluster's shared address meets Docker Hub's# unauthenticated pull limit (toomanyrequests). Docker Hub stays the fallback.unqualified-search-registries = ["docker.io"]short-name-mode = "permissive"
[[registry]]prefix = "docker.io"location = "docker.io"
[[registry.mirror]]location = "mirror.gcr.io"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273# s3-maze: N agents search their own copies of one tree of rooms for its exit, and the first one# out ends the run. The template of every team's spec: team.py fills in the tree (TREE), the# team (TEAM, e.g. maze-t07-n04) and this dataset's revision (REVISION), sizes the workers to the# team, and merges one of `where:` into it.# Don't launch this file; README.md.name: ${RUN_NAME:-TEAM} # team.py: the team's namemodel: Qwen/Qwen3.8-27Bnaming: consecutive-id # agent-001 .. agent-00N, all on the one treeinference: hf_router: provider: deepinfra api_key_env: HF_INFERENCE_TOKEN # inference only: never the workers' HF_TOKENtask: repo: https://huggingface.co/datasets/HuggingFaceSwarms/s3-maze # private for now selector: TREE # maze-t01 .. maze-t32: one task per tree revision: REVISION # team.py: --revision, default the Hub's headagents: count: 1 # team.py: N# The first agent to reach the exit ends the run. The check runs in that agent's maze service# (read-only, every 30 s), never in its container.stop_on_success: truesuccess_check: service: maze command: python3 -I -S /app/success.pyresources: # The board rules: identical for every eval run, since they shape how agents talk (the same # as s3-aggregation's). Enforced by each agent's rule proxy (docker and podman). message_board: channels: - general wake: - mention - thread rules: max_len: 1000 min_post_gap: 5s max_posts: 40 max_channels: 1workers: agents_per_worker: 1 # team.py: N, the whole team on one worker and board turn_timeout: 20mloop: prompt: Continue the task until it is complete, then stop. every: turn_end while: until: 45m max_rounds: 6limits: run_timeout_seconds: 3600 agent_max_turns: 150 # model calls per prompt
# Where the team runs: team.py merges one of these into the spec (--where). Each agent is a# compose stack (its container and its maze service), so docker or podman: HF Sandboxes run one# container per Trial.where: # Local docker, with the controller, the one worker and the board on this machine. docker: environment: backend: docker # The HF cluster: a Slurm worker on hopper-cpu running the team in rootless podman (podman # 4.9), with a local board on that worker (a new one each run). Results reach # <run dir>/results/ (Legion's docs/slurm.md "Results"). cluster: namespace: ${NAMESPACE} bucket: ${BUCKET} # the run's checkpoint bucket, hf://buckets/<ns>/<name> compute: kind: slurm partition: ${SLURM_PARTITION:-} # the cluster profile's cpus: 4 # team.py: N + 2, at least 4 mem: 7600M # team.py: 1900 MB per CPU (hopper-cpu allows 2000) time: '2:00:00' environment: backend: podman123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# s3-maze scaling sweep
The s³ paper's maze results (Figure 4 bottom: success against swarm size) with Legion: every treeof this dataset at N = 1, 2, 4, 8 and 16 agents, one team each, every team its own Legion run onthe HF cluster, for one model per grid. The results for `Qwen/Qwen3.5-27B` and`Qwen/Qwen3.5-2B` are on Legion's `s3-maze-results` branch (`experiments/s3-maze/results/`) and inhuggingface/legion#123's description; the raw runs are in the private`HuggingFaceSwarms/s3-maze-results`.
| File | || --- | --- || `serve-vllm.sbatch` | one model server: vLLM on one B200 (s3-aggregation's image and parsers) with thinking off, `MODEL` and `PORT` from the environment || `sweep.py` | runs one model's grid, one command, resumable: a row per team in `<root>/rows.jsonl` || `health-log.sh` | each model server's prefix-cache hit rate and load every minute, to `servers.jsonl` (`--health`) || `plot.py` | `scaling.png`, `teams.csv`, `by_n.csv` and `by_n.md` from the rows, one series per grid (`NAME=ROOT@light` draws one lighter) || `setaside.py` | why each attempt in `rows-discarded.jsonl` didn't count |
## Run it
From Legion's checkout (at or after `0401df9`, legion#129), with this dataset on the shared disk (`DS`; the workers read`legion/registries.conf`) and the private-repo credential helper exported (Legion's docs/slurm.md):
```shsbatch -p hopper-b200 -J s3-maze-vllm-27b-8011 --export=ALL,MODEL=Qwen/Qwen3.5-27B,PORT=8011 \ -o vllm-%j.log $DS/legion/sweep/serve-vllm.sbatch # one per GPU; the log ends with its URLuv run python $DS/legion/sweep/sweep.py --model Qwen/Qwen3.5-27B --tag q27- --revision <sha> \ --urls http://<node>:8011/v1,http://<node>:8012/v1,... --per-server 12 --parallel 50 \ --root runs/q27 --health servers.jsonl --dataset HuggingFaceSwarms/s3-maze-resultsuv run $DS/legion/sweep/plot.py --series Qwen3.5-27B=runs/q27 --series Qwen3.5-2B=runs/q2 --out results```
Each team is team.py's cluster spec with the model on the servers (`urls`): `compute: slurm`, oneworker on hopper-cpu running the team's compose Trials in rootless podman with a local board,and `stop_on_success`. The worker gets a CPU per agent, a quarter of one per maze service and twomore (at least 4), at 1900 MB per CPU. The driver inits and launches a team, waits for the firstexit (and the grading) or the end of the loop, releases it (`legion stop --release`, which alsoends its controller), and appends metrics.py's row with the team's exit branch and wall time.`--hint` gives every team the protocol hint (`team.py --hint`); the board allows `#general`only (`max_channels: 1`).
## What counts
A run counts only when its worker started within 2 minutes of its launch (the loop's 45 minutescount from the launch), on one worker incarnation, with its controller kept, every agent'sreward and move log and the board export, and no agent's model server thrashing for 5 minutes ormore during it (below). Anything else is the infrastructure's: the team runs again as`<task>-rK`, and `setaside.py` says why. A worker still not started 3 minutes after its launchis released at once, so its team reruns without waiting out its time cap. A rerun's servercapacity is reserved under the `-rK` name it runs as, since legion hashes agents by run and name.What the model does (no move, no post, no exit) is a result. A restarted driver adopts the teamsin flight and keeps each team's own start time.
## Model servers: thinking, KV cache and names
Every server sets `enable_thinking: false` as its chat template's default(`--default-chat-template-kwargs`): the Qwen3.5 templates' defaults differ (the 27B thinks bydefault, the 2B doesn't), and s3 runs compare models with thinking off. Check one response perserver before a grid starts: no `reasoning` field and no `<think>` in the content.
One B200 holds about 1.7M tokens of a 27B model's KV cache, and a maze agent's context grows past100k tokens. A server with more such agents than fit evicts their cached prefixes and recomputeseach agent's whole context on every call (its prefix-cache hit rate falls from ~95% to a fewpercent, and calls take minutes): the loop's time limit, not the move budget, then decides therun. So:
- **at most `--per-server` agents per server** (9 to 19 for the 27B model, read again from `<root>/per_server` before each launch, so it can change while the grid runs; the 2B model's smaller cache entries, ~13M tokens per B200, fit a whole grid on one GPU);- **every team gets the whole shared list.** Legion (from huggingface/legion#129, `0401df9`) sends each agent to a server by hashing its run and its name over the URLs, so teams with `naming: consecutive-id` spread over the servers instead of every team's `agent-001` calling the same one. The driver hashes a new team's agents the same way and starts it once the servers they land on are under the cap. (The sweeps before #129 gave each team its own subset of the servers instead, to the same end.)- **runs on a thrashing server don't count**: `health-log.sh` logs each server's hit rate every minute, and a run whose agents' server had under 50% while prefilling 200k+ tokens in 5 or more minutes runs again (`health-log.sh servers.jsonl <host:port> ...`).
## Workers: memory
Rootless podman on hopper-cpu can't hold a container to a memory limit, so a runaway process inone agent's container (the 2B model's agents sometimes start one) grows the whole worker untilLegion's memory guard drains or preempts it, and the team runs again on a second incarnation.For the 2B grid, `--cpus-per-agent 2` doubles each agent's share of the worker (and its memory,at 1900 MB per CPU) and `--memory-ladder 0.97,0.98,0.99` lets the worker go closer to its limitbefore the guard acts.123456789101112131415161718192021222324252627#!/bin/bash# Every 60 s, each model server's requests, prompt tokens, prefix-cache hit rate, running and# waiting requests over the last minute, one JSON line per server to OUT (sweep.py --health):# health-log.sh servers.jsonl 10.53.14.57:8011 10.53.14.57:8012 ...OUT=$1shiftdeclare -A lastwhile true; do for s in "$@"; do now=$(curl -s -m 5 "$s/metrics" | awk ' /^vllm:request_success_total\{/ {a+=$2} /^vllm:prompt_tokens_total\{/ {p+=$2} /^vllm:prefix_cache_hits_total\{/ {h+=$2} /^vllm:prefix_cache_queries_total\{/ {q+=$2} /^vllm:num_requests_running\{/ {r+=$2} /^vllm:num_requests_waiting\{/ {w+=$2} END {print a+0, p+0, h+0, q+0, r+0, w+0}') if [ -n "${last[$s]}" ] && [ -n "$now" ]; then python3 -c "import json, sys, timea0, p0, h0, q0, _, _ = map(float, sys.argv[1].split())a1, p1, h1, q1, r, w = map(float, sys.argv[2].split())print(json.dumps({'t': time.time(), 'server': sys.argv[3], 'requests': a1 - a0, 'prompt': p1 - p0, 'hit_rate': (h1 - h0) / (q1 - q0) if q1 > q0 else None, 'running': r, 'waiting': w}))" "${last[$s]}" "$now" "$s" >> "$OUT" fi last[$s]=$now done sleep 60done123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293# /// script# requires-python = ">=3.12"# dependencies = ["matplotlib>=3.8"]# ///"""The s3-maze sweep's figure, CSVs and table from sweep.py's rows (`<root>/rows.jsonl`):
uv run legion/sweep/plot.py --series Qwen3.5-27B=<root> --series Qwen3.5-2B=<root> --out <dir>
- `scaling.png`, eight panels, one series per model, after the s³ paper's maze results (Figure 4, bottom: success against swarm size; Figure 5c: success by the branch that holds the exit; Appendix M: room overlap): - success (%) against N, with 95% Wilson intervals over the trees, and best-of-N from the model's own N = 1 rate (1 - (1 - p1)^N, the paper's independent-attempts baseline) dashed; - the team's moves and the time (from its Trials' start) to the first exit, over the teams that got out: median and interquartile range; - room overlap, (V - U) / V, mean and 95% interval (N >= 2); - input and generated tokens per team (log scale): median and interquartile range; - board posts per agent: mean and 95% interval; - success by which of the start room's three doors, in the listed order, leads to the exit, over every N >= 2 team (95% Wilson intervals).- `teams.csv` (one row per team), `by_n.csv` and `by_n.md` (per model and N)."""
import argparseimport csvimport jsonimport mathimport statisticsimport sysfrom pathlib import Path
SURFACE, INK, INK_2, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#e4e3df"SERIES = ["#2a78d6", "#eb6834", "#1baf7a"]LIGHT: set[str] = set() # the series drawn lighter (`--series NAME=ROOT@light`)
def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]: if n == 0: return (math.nan, math.nan) p = k / n centre = (p + z * z / (2 * n)) / (1 + z * z / n) half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n) return (max(0.0, centre - half), min(1.0, centre + half))
def mean_ci(values: list[float]) -> tuple[float, float, float]: if not values: return (math.nan, math.nan, math.nan) m = statistics.fmean(values) half = 1.96 * statistics.stdev(values) / math.sqrt(len(values)) if len(values) > 1 else 0.0 return (m, m - half, m + half)
def quartiles(values: list[float]) -> tuple[float, float, float]: if not values: return (math.nan, math.nan, math.nan) q = statistics.quantiles(values, n=4) if len(values) > 1 else [values[0]] * 3 return (statistics.median(values), q[0], q[2])
def team_row(r: dict) -> dict: t, first = r["tokens"], r.get("first_exit") or {} return {"task": r["task"], "tree": r["tree"], "agents": r["agents"], "exit_branch": r["exit_branch"], "success": int(bool(r["success"])), "exit_by": first.get("agent"), "exit_after_s": first.get("after_s"), "exit_team_moves": first.get("team_moves"), "exit_agent_moves": first.get("agent_moves"), "moves": sum((r.get("moves") or {}).values()), "refused_moves": sum((r.get("refused_moves") or {}).values()), "room_overlap": r.get("room_overlap"), "rooms_union": r.get("rooms_union"), "input_uncached": t["input"], "cached": t["cache_read"], "output": t["output"], "posts": r["posts"], "posts_per_agent": r["posts"] / r["agents"], "edges": len(r["edges"]), "outcome": r.get("outcome"), "wall_s": r.get("wall_s"), "duration_s": r["duration_s"], "reruns": r.get("reruns", 0), "worker_wait_s": r.get("worker_wait_s"), "run": r["run"]}
def by_n(teams: list[dict]) -> list[dict]: """Per N. A tree with no team that counted at that N (every attempt set aside) is `missing`: left out of the rates, not a failure.""" out, p1 = [], None trees = {t["tree"] for t in teams} for n in sorted({t["agents"] for t in teams}): group = [t for t in teams if t["agents"] == n] missing = sorted(trees - {t["tree"] for t in group}) won = [t for t in group if t["success"]] k = len(won) low, high = wilson(k, len(group)) if n == 1: p1 = k / len(group) overlap = [t["room_overlap"] for t in group if t["room_overlap"] is not None] moves, minutes = (quartiles([t["exit_team_moves"] for t in won]), quartiles([t["exit_after_s"] / 60 for t in won])) out.append({ "agents": n, "teams": len(group), "missing": len(missing), "missing_trees": " ".join(f"t{x:02d}" for x in missing), "successes": k, "success_rate": k / len(group), "ci_low": low, "ci_high": high, "best_of_n_from_n1": 1 - (1 - p1) ** n if p1 is not None else math.nan, "exit_team_moves_median": moves[0], "exit_team_moves_q1": moves[1], "exit_team_moves_q3": moves[2], "exit_agent_moves_median": quartiles([t["exit_agent_moves"] for t in won])[0], "exit_minutes_median": minutes[0], "exit_minutes_q1": minutes[1], "exit_minutes_q3": minutes[2], "moves_per_agent": statistics.fmean(t["moves"] / n for t in group), "room_overlap": statistics.fmean(overlap) if overlap else math.nan, "input_per_team": statistics.fmean(t["input_uncached"] + t["cached"] for t in group), "output_per_team": statistics.fmean(t["output"] for t in group), "input_per_team_median": statistics.median(t["input_uncached"] + t["cached"] for t in group), "output_per_team_median": statistics.median(t["output"] for t in group), "posts_per_agent": statistics.fmean(t["posts_per_agent"] for t in group), "wall_minutes_median": statistics.median(t["wall_s"] / 60 for t in group if t["wall_s"] is not None), "reruns": sum(t["reruns"] for t in group)}) return out
def write_csv(path: Path, rows: list[dict]) -> None: with path.open("w", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(rows[0]), lineterminator="\n") writer.writeheader() writer.writerows(rows)
def table(series) -> str: lines = [("| model | N | teams | success | 95% CI | best-of-N from N=1 | team moves to exit " "| minutes to exit | moves per agent | median input / output tokens per team " "| posts per agent | room overlap |"), "|---|---|---|---|---|---|---|---|---|---|---|---|"] for model, _, summary in series: for s in summary: def num(x, f="{:.0f}"): return "-" if x is None or (isinstance(x, float) and math.isnan(x)) else f.format(x) gone = f" ({s['missing']} missing)" if s["missing"] else "" lines.append( f"| {model} | {s['agents']} | {s['teams']}{gone} | {s['successes']}/{s['teams']} " f"({100 * s['success_rate']:.0f}%) | {100 * s['ci_low']:.0f}-" f"{100 * s['ci_high']:.0f}% | {num(100 * s['best_of_n_from_n1'], '{:.0f}%')} " f"| {num(s['exit_team_moves_median'])} | {num(s['exit_minutes_median'], '{:.1f}')} " f"| {s['moves_per_agent']:.0f} | {s['input_per_team_median'] / 1e6:.1f}M / " f"{s['output_per_team_median'] / 1e3:.0f}k | {s['posts_per_agent']:.1f} " f"| {num(s['room_overlap'], '{:.2f}')} |") return "\n".join(lines) + "\n"
def panels(teams: list[dict], summary: list[dict]) -> list[tuple]: """(label, x values, [(middle, low, high)], y scale, dashed reference or None).""" ns = [s["agents"] for s in summary] group = {n: [t for t in teams if t["agents"] == n] for n in ns} won = {n: [t for t in group[n] if t["success"]] for n in ns} multi = [n for n in ns if n > 1] branches = [1, 2, 3] by_branch = [[t for t in teams if t["agents"] > 1 and t["exit_branch"] == b] for b in branches] return [ ("Success (%)", ns, [(100 * s["success_rate"], 100 * s["ci_low"], 100 * s["ci_high"]) for s in summary], (0, 105), [100 * s["best_of_n_from_n1"] for s in summary]), ("Team moves to the first exit", ns, [quartiles([t["exit_team_moves"] for t in won[n]]) for n in ns], None, None), ("Minutes to the first exit", ns, [quartiles([t["exit_after_s"] / 60 for t in won[n]]) for n in ns], None, None), ("Room overlap", multi, [mean_ci([t["room_overlap"] for t in group[n] if t["room_overlap"] is not None]) for n in multi], (0, 1), None), ("Input tokens per team", ns, [quartiles([t["input_uncached"] + t["cached"] for t in group[n]]) for n in ns], "log", None), ("Generated tokens per team", ns, [quartiles([t["output"] for t in group[n]]) for n in ns], "log", None), ("Board posts per agent", ns, [mean_ci([t["posts_per_agent"] for t in group[n]]) for n in ns], None, None), ("Success (%) by the exit's branch, N ≥ 2", branches, [(100 * sum(t["success"] for t in g) / len(g) if g else math.nan, *(100 * v for v in wilson(sum(t["success"] for t in g), len(g)))) for g in by_branch], (0, 105), None), ]
def tokens(value: float, _=None) -> str: for size, unit in ((1e6, "M"), (1e3, "k")): if value >= size: return f"{value / size:g}{unit}" return f"{value:g}"
def figure(path: Path, series, title: str) -> None: import matplotlib
matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import FixedLocator, FuncFormatter, NullFormatter
plt.rcParams.update({"font.size": 10, "axes.edgecolor": GRID, "axes.labelcolor": INK_2, "xtick.color": INK_2, "ytick.color": INK_2, "text.color": INK}) fig, grid = plt.subplots(2, 4, figsize=(17, 7.8), facecolor=SURFACE) axes = grid.flatten() xs_by_panel: dict[int, set] = {} colours, c = [], -1 # a light series (`@light`) takes the colour of the series before it for model, _, _ in series: c += model not in LIGHT or c < 0 colours.append(SERIES[c]) for k, (model, teams, summary) in enumerate(series): light = model in LIGHT look = ({"alpha": 0.4, "linewidth": 1.3, "markersize": 4, "elinewidth": 1.0} if light else {"linewidth": 2, "markersize": 6, "elinewidth": 1.4}) step = (k - (len(series) - 1) / 2) # side by side, so the bars don't hide each other for i, (ax, (label, xs, points, scale, reference)) in enumerate( zip(axes, panels(teams, summary), strict=True)): xs_by_panel.setdefault(i, set()).update(xs) # N on a log2 axis: shift by a factor; the branches (panel 7) by a step moved = [x + 0.08 * step if i == 7 else x * 2 ** (0.07 * step) for x in xs] ax.errorbar(moved, [p[0] for p in points], yerr=[[max(0.0, p[0] - p[1]) if not math.isnan(p[1]) else 0 for p in points], [max(0.0, p[2] - p[0]) if not math.isnan(p[2]) else 0 for p in points]], color=colours[k], marker="o", capsize=3, label=model, linestyle="-" if i != 7 else "none", **look) if reference and not light: ax.plot(xs, reference, color=colours[k], linewidth=1.3, linestyle="--", label=f"{model}: best-of-N from N = 1") ax.set_ylabel(label) scales = [p[3] for p in panels(*series[0][1:])] for i, ax in enumerate(axes): # after every series is in, so each scales to all of them if scales[i] == "log": ax.set_yscale("log") ax.yaxis.set_major_formatter(FuncFormatter(tokens)) ax.yaxis.set_minor_formatter(NullFormatter()) elif scales[i]: ax.set_ylim(*scales[i]) else: ax.set_ylim(bottom=0) ticks = sorted(xs_by_panel.get(i, ())) if i != 7 and ticks: ax.set_xlim(min(ticks) / 1.4, max(ticks) * 1.4) ax.set_xscale("log", base=2) ax.xaxis.set_minor_formatter(NullFormatter()) ax.xaxis.set_major_locator(FixedLocator(ticks)) ax.set_xticklabels([str(t) for t in ticks]) ax.set_facecolor(SURFACE) ax.grid(axis="y", color=GRID, linewidth=0.8) ax.set_axisbelow(True) ax.spines[["top", "right"]].set_visible(False) ax.set_xlabel("Door at the start room (listed order)" if i == 7 else "Swarm size N") axes[0].legend(frameon=False, loc="upper left", fontsize=8) fig.suptitle(title, fontsize=11, color=INK, x=0.01, ha="left") gone = "".join(f"; {m} at N = {s['agents']}: {s['missing']} missing (every attempt set " "aside), left out, not failures" for m, _, summary in series for s in summary if s["missing"]) fig.text(0.01, 0.012, f"One counted team per tree (32 trees{gone}). Success: share of " "teams in which any agent reached the exit, 95% Wilson intervals; dashed: best-of-N " "from the model's own N = 1 rate.\nMoves (all agents') and minutes (from the " "Trials' start) to the first exit: teams that got out; tokens per team (log scale): " "every team; medians and interquartile ranges. Overlap and posts: means, 95% " "intervals.", fontsize=8, color=INK_2, wrap=True) fig.tight_layout(rect=(0, 0.06, 1, 0.95)) fig.savefig(path, dpi=200, facecolor=SURFACE)
def load(root: Path) -> tuple[list[dict], list[dict]]: rows = [json.loads(line) for line in (root / "rows.jsonl").read_text().splitlines() if line] teams = sorted((team_row(r) for r in rows), key=lambda t: (t["agents"], t["tree"])) return teams, by_n(teams)
def main(argv=None) -> int: parser = argparse.ArgumentParser(description="The sweep's figure, CSVs and table.") parser.add_argument("--series", action="append", required=True, help="NAME=ROOT, repeatable; NAME=ROOT@light draws it lighter, in the " "colour of the series before it, without its best-of-N line") parser.add_argument("--title", default="s3-maze with legion: success and cost against swarm " "size") parser.add_argument("--out", type=Path, required=True) args = parser.parse_args(argv) sources = [] for s in args.series: name, root = s.split("=", 1) if root.endswith("@light"): root = root.removesuffix("@light") LIGHT.add(name) sources.append((name, Path(root))) args.out.mkdir(parents=True, exist_ok=True) series = [(model, *load(root)) for model, root in sources] write_csv(args.out / "teams.csv", [{"model": m} | t for m, teams, _ in series for t in teams]) write_csv(args.out / "by_n.csv", [{"model": m} | s for m, _, summary in series for s in summary]) (args.out / "by_n.md").write_text(table(series)) figure(args.out / "scaling.png", series, args.title) print(table(series)) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233#!/bin/bash# The s3-maze sweep's model server: one vLLM on one GPU, in Pyxis on hopper-b200, as# s3-aggregation's legion/sweep/serve-vllm.sbatch (the same image and parsers). The agents# (podman on hopper-cpu) reach it by this node's address.# 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# Its log ends with: serving <model> at http://<node address>:<port>/v1## Thinking is off for every model (`enable_thinking: false` as the chat template's default):# the Qwen3.5 templates' defaults differ (27B thinks by default, 2B doesn't), and s3 runs compare# models with thinking off. A request can still turn it on with its own chat_template_kwargs.# 11 CPUs, so eight servers fit a B200 node (92 CPUs).#SBATCH --job-name=s3-maze-vllm#SBATCH --gpus=1#SBATCH --cpus-per-task=11#SBATCH --mem=96G#SBATCH --time=12:00:00set -uo pipefailMODEL=${MODEL:-Qwen/Qwen3.5-27B}PORT=${PORT:-8000}IMAGE=${IMAGE:-/fsx/anton/shared/images/vllm-openai-v0.32.0.sqsh}export HF_HOME=/hfmkdir -p "/scratch/$USER/hf" # the weights, on the node's own disksrun --overlap --container-image="$IMAGE" --no-container-mount-home \ --container-mounts="/scratch/$USER/hf:/hf" --container-env=HF_HOME \ vllm serve "$MODEL" --port "$PORT" \ --enable-auto-tool-choice --tool-call-parser qwen3_coder --reasoning-parser qwen3 \ --default-chat-template-kwargs '{"enable_thinking": false}' &until curl -sf -o /dev/null "localhost:$PORT/v1/models"; do sleep 10 kill -0 $! 2>/dev/null || { echo "vLLM exited during startup"; exit 1; }doneecho "serving $MODEL at http://$(hostname -I | awk '{print $1}'):$PORT/v1"wait123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Why each set-aside attempt of a grid didn't count: `python legion/sweep/setaside.py <root>`,from `<root>/rows-discarded.jsonl` and the attempt's own logs (s3-aggregation's, for the maze).A restarted driver scores an attempt again from what it left, so one attempt can have severalentries: its reason uses them all. Writes `<root>/setaside.md`; the reasons, first that applies:
- it ran while its model server was overloaded (`--overloaded`), or an agent's server thrashed for 5 minutes or more (`--health`);- the worker was relaunched (more than one incarnation: legion#121's case), after running out of memory or after a node failure;- the launch failed (or was cancelled), so its controller never came up;- the worker never started, or started more than 2 min after the launch (the loop counts from the launch);- the controller's node was reclaimed (spot) mid-run;- the task images couldn't be pulled or built, so the Trials never started;- the worker ran out of memory;- the verifier timed out on a loaded worker;- an agent's Trial failed before its verifier ran;- the run was cancelled before its Trials were graded (e.g. the driver stopped).
What the model does (no move, no post, no exit) is never a reason: those runs count."""
import jsonimport reimport sysfrom collections import Counterfrom pathlib import Path
def reason(row: dict, run_dir: Path) -> str: logs = {p.name: p.read_text(errors="replace") for p in (run_dir / "logs").glob("*") if p.is_file()} if (run_dir / "logs").is_dir() else {} workers = " ".join(v for k, v in logs.items() if "-agent-w" in k) controllers = " ".join(v for k, v in logs.items() if k.startswith(("legion-ctl-", "controller-"))) if "overloaded model server" in (row.get("set_aside") or ""): return "ran on an overloaded model server (one 27B GPU, KV-cache thrash)" if (row.get("thrashed_min") or 0) >= 5: # sweep.py's THRASH_LIMIT return "an agent's model server thrashed (prefix-cache hits under 50%) for 5+ min" if (row.get("incarnations") or 0) > 1: if re.search(r"CANCELED: unresponsive", controllers): return "worker stopped answering (e.g. while grading its Trials) and was relaunched" if re.search(r"preempted \(memory\)|draining \(memory\)|rotation wanted", workers): return "worker relaunched after running out of memory (legion#121's case)" return "worker relaunched after a node failure (legion#121's case)" if row.get("outcome") == "launch": return "launch failed or was cancelled (the controller ended before it came up)" if row.get("worker_wait_s") is None: return "worker never started" if row["worker_wait_s"] > 120: # sweep.py's WAIT_LIMIT return "worker started more than 2 min after the launch (the loop counts from it)" if "DUE TO NODE FAILURE" in controllers or row.get("outcome") == "controller lost": return "controller's node reclaimed (spot)" if re.search(r"toomanyrequests|Error: building at STEP|failed to build", workers): return "task images not pulled or built: Trials never started" if re.search(r"preempted \(memory\)|oom_kill", workers): return "worker ran out of memory (preempted or killed, not relaunched)" results = list(run_dir.glob("results/*/agent-*/trials/*/result.json")) if any("VerifierTimeoutError" in p.read_text(errors="replace") for p in results): return "verifier timed out on a loaded worker" failed = [(json.loads(p.read_text()).get("exception_info") or {}).get("exception_type") for p in results] if kinds := sorted({k for k in failed if k and k != "CancelledError"}): return f"an agent's Trial failed before its verifier ran ({', '.join(kinds)})" return "cancelled before grading (e.g. the driver stopped)"
def main(root: Path) -> int: attempts = {} path = root / "rows-discarded.jsonl" for line in path.read_text().splitlines() if path.exists() else []: row = json.loads(line) seen = attempts.setdefault(row["run"], row) # the driver that watched it knew most seen["incarnations"] = max(seen.get("incarnations") or 0, row.get("incarnations") or 0) seen["set_aside"] = "; ".join(filter(None, {seen.get("set_aside"), row.get("set_aside")})) if row.get("outcome") == "controller lost": seen["outcome"] = row["outcome"] kept = [json.loads(x) for x in (root / "rows.jsonl").read_text().splitlines() if x] reasons = Counter(reason(r, root / "runs" / run) for run, r in attempts.items()) counted = {(r["tree"], r["agents"]) for r in kept} missing = sorted({(r["tree"], r["agents"]) for r in attempts.values()} - counted) rerun = sum(r.get("reruns", 0) > 0 for r in kept) + len(missing) lines = [(f"Attempts set aside: {len(attempts)} (rows-discarded.jsonl); teams that needed a " f"rerun: {rerun} of {len(counted) + len(missing)}"), ""] lines += [f"- {why}: {k}" for why, k in reasons.most_common()] if missing: lines += ["", f"Teams with no attempt that counted ({len(missing)}; missing from the " "results, not failures): " + ", ".join(f"tree {t:02d} at N = {n}" for t, n in missing)] (root / "setaside.md").write_text("\n".join(lines) + "\n") print("\n".join(lines)) return 0
if __name__ == "__main__": raise SystemExit(main(Path(sys.argv[1])))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570"""The s3-maze scaling sweep on the HF cluster, one command per model for the whole grid, runfrom Legion's checkout (its environment, and its `.venv` for the workers):
uv run python <this dataset>/legion/sweep/sweep.py --urls http://<vllm node>:8000/v1 \\ --model Qwen/Qwen3.5-27B --tag q27- --revision <sha> [--trees 1-32] \\ [--agents 1,2,4,8,16] [--parallel 20] [--max-agents 64] [--root .legion/s3-maze-sweep/q27]
s3-aggregation's legion/sweep/sweep.py for the maze. Each (tree, N) team is its own legion run(`compute: slurm`, podman agents on hopper-cpu, a local board on its one worker), from team.py'scluster spec with the sweep's model on `urls`: the same board rules, loop, limits and movebudget at every N, and `stop_on_success`. The worker gets a CPU per agent, a quarter of one permaze service and two more (at least 4), at 1900 MB per CPU. Per team: `legion init`,`legion launch`, then wait until the first agent's exit stops the run (and every Trial isgraded) or the loop is done and the agents are idle; `legion stop --release` (which grades theTrials of a run nobody won, and ends the controller in either case); then eval/metrics.py's rowplus the wall time and the tree's exit branch go to `<root>/rows.jsonl`.
A run counts only when its worker started within WAIT_LIMIT of its launch (the loop's timecounts from the launch), on one worker incarnation (legion#121), with its controller kept andnothing missing (every agent's reward and move log, the board export). Anything else is theinfrastructure's, so the team runs again as `<task>-rK` and the attempt goes to`rows-discarded.jsonl`; what the model does (no move, no post, no exit) is a result. A team witha row is skipped, so the same command resumes; a team a stopped driver launched is adopted andkeeps its own start time for its time cap.
At most `--parallel` teams and `--max-agents` agents run at once (the agents of the teams inflight; `<root>/max_agents`, when present, overrides it while the driver runs): one GPU's KVcache holds a few dozen agents' contexts of a large model, and an overloaded server would makethe loop's time limit, not the move budget, decide the result.
Needs HF_TOKEN (or `hf auth login`): the workers clone the private task dataset and sync theprivate state bucket with it. The agents get no Hub token; the vLLM servers take no key."""
import argparseimport importlib.utilimport jsonimport osimport reimport shutilimport subprocessimport sysimport threadingimport timefrom collections import Counterfrom concurrent.futures import ThreadPoolExecutorfrom datetime import UTC, datetimefrom pathlib import Path
import httpximport yamlfrom huggingface_hub import HfApi, get_token
from legion.models import Inference
HERE = Path(__file__).resolve().parentDATASET_DIR = HERE.parents[1]REPO = Path.cwd() # Legion's checkoutSECRET = re.compile(r"hf_[A-Za-z0-9]{30,}")lock, init_lock = threading.Lock(), threading.Semaphore(4)LOST, GONE = "controller lost", "no controller left"WAIT_LIMIT = 120 # s: a worker that started later than this after the launch doesn't countMB_PER_CPU = 1900# runs started in this window (`--overloaded START/END`, ISO times) ran on a model server whose# KV cache was thrashing (too many agents for its GPU): the server, not the model, decided themOVERLOADED: tuple[datetime, datetime] | None = None# the servers' health log (`--health`: one JSON line per server and minute, with its prefix-cache# hit rate): a run in which an agent's server thrashed this many minutes doesn't countHEALTH: Path | None = NoneTHRASH_LIMIT = 5
def load(name: str, path: Path): spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
team = load("team", HERE.parent / "team.py")metrics = load("metrics", DATASET_DIR / "eval" / "metrics.py")
def say(*parts) -> None: with lock: print(datetime.now(UTC).strftime("%H:%M:%S"), *parts, flush=True)
def numbers(text: str) -> list[int]: """`1-32` or `1,3,7` -> the numbers.""" out = [] for part in text.split(","): a, _, b = part.partition("-") out += range(int(a), int(b or a) + 1) return out
def legion(run_dir: Path, *args: str, timeout: float = 3600) -> subprocess.CompletedProcess: env = {**os.environ, "LEGION_RUN_DIR": str(run_dir)} env.pop("VIRTUAL_ENV", None) return subprocess.run([str(Path(sys.executable).with_name("legion")), *args], cwd=REPO, env=env, capture_output=True, text=True, timeout=timeout, check=False)
CPUS_PER_AGENT = 1 # --cpus-per-agent; memory follows at MB_PER_CPUHINT = False # --hint: every team gets team.py's protocol hint (team.md as its team_file)MEMORY_LADDER: dict | None = None # --memory-ladder: the workers' rotate/drain/preempt fractions
def worker_cpus(n: int) -> int: """CPUS_PER_AGENT per agent's container, a quarter of one per maze service, two for the worker, podman and the image builds.""" return max(4, CPUS_PER_AGENT * n + 2 + (n + 3) // 4)
def exit_branch(tree: int) -> int: """Which of the start room's doors (1, 2 or 3, in the listed order) leads to the exit.""" layout = json.loads((DATASET_DIR / "tasks" / f"maze-t{tree:02d}" / "environment" / "maze" / "tree.json").read_text()) path = load("generate", DATASET_DIR / "generate.py").shortest_path(layout) return layout["doors"][layout["start"]].index(path[0]) + 1
def write_experiment(src: Path, tree: int, n: int, name: str, urls: list[str], model: str, revision: str) -> None: """team.py's cluster spec at the dataset `revision`, with the sweep's model on its servers and a worker sized to the team, as swarm `name`; with HINT, the protocol hint as its team_file.""" team.main(["--tree", str(tree), "--agents", str(n), "--where", "cluster", "--revision", revision, "--out", str(src)] + (["--hint"] if HINT else [])) spec = yaml.safe_load((src / "spec.yaml").read_text()) spec["name"] = name spec["model"] = model spec["inference"] = {"urls": urls} # no key: the servers take none cpus = worker_cpus(n) spec["compute"] |= {"cpus": cpus, "mem": f"{cpus * MB_PER_CPU}M"} if MEMORY_LADDER: # an agent's runaway process spikes the worker's memory (podman can't # cap a container here): drain or rotate later, so the spike doesn't end the run spec["workers"].setdefault("worker", {})["memory"] = dict(MEMORY_LADDER) (src / "spec.yaml").write_text( f"# {spec['task']['selector']} with N = {n} for the scaling sweep (sweep.py): team.py's " f"cluster spec with {model} on the sweep's servers.\n" + yaml.safe_dump(spec, sort_keys=False))
def profile(root: Path) -> Path: """The cluster profile: hopper-cpu, the venv, podman pulling Docker Hub images through a mirror (registries.conf), and 15 minutes (not 5) for a controller to come up: with a hundred teams starting at once, its imports from the shared disk can take minutes.""" path = root / "profiles" / "cluster.env" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(f"SLURM_PARTITION=hopper-cpu\nSLURM_MAX_MEM_PER_CPU_MB=2000\n" f"VENV={REPO / '.venv'}\n" f"CONTAINERS_REGISTRIES_CONF={HERE.parent / 'registries.conf'}\n" "HEALTH_WAIT_S=900\n") path.chmod(0o644) return path
def serving(url: str) -> bool: """The model server answers `GET /models`.""" try: return httpx.get(f"{url.rstrip('/')}/models", timeout=10).status_code == 200 except httpx.HTTPError: return False
def job_state(name: str) -> str: """The Slurm state of the job called `name`, '' when there is none.""" out = subprocess.run(["squeue", "-h", "-n", name, "-o", "%T"], capture_output=True, text=True, check=False).stdout.split() return out[0] if out else ""
def wait_done(run_dir: Path, task: str, n: int, timeout: float) -> str: """Poll `legion status` until the first exit stopped the run and its Trials are graded ('success'), or the loop is done and every agent is idle ('done'): or why not. A controller that stops answering and isn't running (a spot reclaim requeued it, or it is gone) is LOST.""" deadline, unanswered, stopped = time.monotonic() + timeout, 0, None while time.monotonic() < deadline: # a worker that hasn't started WAIT_LIMIT after its launch can't count: stop waiting # for the team now, so it runs again at once, rather than after its whole time cap launches = list((run_dir / "launch").glob("*.env")) if (launches and not any((run_dir / "logs").glob("*-agent-w*.out")) and time.time() - min(p.stat().st_mtime for p in launches) > WAIT_LIMIT + 60): return f"worker not started {WAIT_LIMIT + 60} s after its launch" status = legion(run_dir, "status", task, timeout=120) text = status.stdout unanswered = unanswered + 1 if status.returncode != 0 else 0 if unanswered >= 3 and job_state(f"legion-ctl-{task}") != "RUNNING": return LOST if re.search(r"crashloop|launch_refused", text): return "worker failed: " + " ".join(text.split())[:300] if m := re.search(r"STOPPED ON SUCCESS: .*verification: (\w+)", text): stopped = stopped or time.monotonic() graded = m[1] != "pending" and not job_state(f"{task}-agent-w0000") if graded or time.monotonic() - stopped > 600: # the cleanup budget is 5 min return "success" elif re.search(r"^loop agent: done", text, re.MULTILINE) and (agents := re.search( r"^agent .*$", text, re.MULTILINE)) and "working:" not in agents[0]: return "done" # no agent in a turn (idle, or stuck: a turn that timed out) time.sleep(20) return f"not done after {timeout:.0f} s"
def release(run_dir: Path, name: str) -> bool: """`legion stop --release`: drains (and so grades) a run nobody won and ends its controller; then make sure no job of the run is left.""" out = legion(run_dir, "stop", name, "--release") # once the worker is gone its results are on the shared disk: a controller still up a # minute later (it sometimes outlives the release) only holds the team's slot, and SIGTERM # makes it push its state and exit for job, wait in ((f"{name}-agent-w0000", 900), (f"legion-ctl-{name}", 60)): for _ in range(wait // 10): # a draining worker is still grading its Trials if not job_state(job): break time.sleep(10) else: say(name, f"{job} still there after the release: cancelling it") subprocess.run(["scancel", "-n", job], check=False) return out.returncode == 0
def attempt(args, root: Path, secrets: Path, tree: int, n: int, name: str, urls: list[str]) -> dict | None: """One run of a team as swarm `name` on the servers `urls`: its row, or None when it could not start.""" run_dir, src = root / "runs" / name, root / "src" / name if run_dir.exists() and (any((run_dir / "launch").glob("*.env")) or (run_dir / "hosts" / "controller.host").exists()): # a previous driver launched it and stopped before its row: finish it from here (its # time cap counts from its own start, cluster.env's), or, with its controller gone, # score what it left alive = bool(job_state(f"legion-ctl-{name}")) say(name, "adopting the run a previous driver launched" + ("" if alive else " (no controller left)")) return finish(args, run_dir, name, tree, n, (run_dir / "cluster.env").stat().st_mtime, None if alive else GONE) if run_dir.exists(): shutil.rmtree(run_dir) # init failed before: nothing ran started = time.time() # servers retired while the grid drained (or down) are left out, e.g. for a rerun urls = [u for u in urls if serving(u)] or [u for u in args.urls if serving(u)] or urls write_experiment(src, tree, n, name, urls, args.model, args.revision) log = root / "logs" / f"{name}-init.log" log.parent.mkdir(parents=True, exist_ok=True) for tries in range(6): # its checks probe the model servers, which may be busy with init_lock: # a few at a time: many at once race on the bucket's write check init = legion(run_dir, "init", str(run_dir), "--from", str(src), "--profile", str(profile(root)), "--secrets", str(secrets)) log.write_text(init.stdout + init.stderr) if init.returncode == 0: break time.sleep(30 * (tries + 1)) else: failed = [x for x in init.stdout.splitlines() if x.startswith("FAIL")] say(name, "init failed 6 times:", failed or init.stdout[-300:], "(log:", log, ")") return None say(name, "launching") launch = legion(run_dir, "launch", str(run_dir / "experiment")) if launch.returncode != 0: say(name, "launch failed:", launch.stdout[-600:], launch.stderr[-600:]) return finish(args, run_dir, name, tree, n, started, "launch") return finish(args, run_dir, name, tree, n, started)
def finish(args, run_dir: Path, name: str, tree: int, n: int, started: float, why: str | None = None) -> dict: """Wait for a launched team, release it (its Trials are graded, its controller ends) and make its row.""" why = why or wait_done(run_dir, name, n, max(0.0, args.team_timeout - (time.time() - started))) if why == LOST: # nothing to release: end its jobs, and the team runs again say(name, "controller lost (spot reclaim?): cancelling its jobs") for job in (f"legion-ctl-{name}", f"{name}-agent-w0000"): subprocess.run(["scancel", "-n", job], check=False) released = False elif why == GONE: # its rewards and export are on disk, or it doesn't count released = False else: say(name, "outcome:", why, "- releasing") released = release(run_dir, name) ended = time.time() return metrics.row(run_dir) | { "model": args.model, "tree": tree, "exit_branch": exit_branch(tree), "wall_s": round(ended - started, 1), "outcome": why, "released": released, # each launch of the worker slot writes one env file: more than one is a relaunch or a # preemption, whose results a later incarnation overwrites (legion#121) "incarnations": len(list((run_dir / "launch").glob("*.env"))), "worker_wait_s": worker_wait(run_dir), "thrashed_min": thrashed_minutes(run_dir, n, started, ended), "started_at": datetime.fromtimestamp(started, UTC).isoformat()}
def thrashed_minutes(run_dir: Path, n: int, start: float, end: float) -> int | None: """Minutes, within the run, in which a server one of its agents calls was thrashing: a prefix-cache hit rate under 50% while prefilling at least 200k prompt tokens (every call recomputing an agent's long context; a cold server's first small prompts don't count), from the health log (`--health`); None without one.""" spec = run_dir / "experiment" / "spec.yaml" if HEALTH is None or not HEALTH.is_file() or not spec.is_file(): return None urls = yaml.safe_load(spec.read_text())["inference"]["urls"] servers = {u.split("//")[1].removesuffix("/v1") for u in agents_on(urls, n, run_dir.name)} minutes = set() for line in HEALTH.read_text().splitlines(): s = json.loads(line) if (start <= s["t"] <= end and s["server"] in servers and s["hit_rate"] is not None and s["hit_rate"] < 0.5 and s["prompt"] >= 200_000): minutes.add(int(s["t"] // 60)) return len(minutes)
def worker_wait(run_dir: Path) -> float | None: """Seconds from the controller writing the worker's first launch file to the worker job's first log line (None: not known).""" launches = sorted((run_dir / "launch").glob("*.env"), key=lambda p: p.stat().st_mtime) logs = sorted((run_dir / "logs").glob("*-agent-w*.out")) if not launches or not logs: return None first = logs[0].read_text(errors="replace").split("\n", 1)[0] try: began = datetime.fromisoformat(first.split(" ", 1)[0]) except ValueError: return None return round(began.timestamp() - launches[0].stat().st_mtime, 1)
def why_invalid(row: dict) -> str: """Why a team's run doesn't count ('' when it does): the infrastructure's failures, never the model's.""" wait = row.get("worker_wait_s") started = datetime.fromisoformat(row["started_at"]) if row.get("started_at") else None overloaded = bool(OVERLOADED and started and OVERLOADED[0] <= started < OVERLOADED[1]) thrashed = row.get("thrashed_min") or 0 return "; ".join(why for why, bad in ( ("ran on an overloaded model server (KV-cache thrash)", overloaded), (f"an agent's model server thrashed for {thrashed} min", thrashed >= THRASH_LIMIT), (f"{row.get('incarnations')} worker incarnations", row.get("incarnations") != 1), ("worker never started", wait is None), (f"worker started {wait or 0:.0f} s after the launch", (wait or 0) > WAIT_LIMIT), (LOST, row.get("outcome") == LOST), (f"missing {', '.join(row['missing'])}"[:160], bool(row["missing"]))) if bad)
def valid(row: dict) -> bool: return not why_invalid(row)
def run_team(args, root: Path, secrets: Path, tree: int, n: int, urls: list[str], slots: "Slots", held: dict) -> dict | None: """A team, run again (as `<task>-rK`) until its run counts. `held["run"]` is the run name its server capacity is reserved under: each attempt moves the reservation to its own name, since legion hashes agents by run and name (a rerun's agents land on other servers).""" task = f"{args.tag}maze-t{tree:02d}-n{n:02d}" row = None for reruns in range(args.max_reruns + 1): name = task if reruns == 0 else f"{task}-r{reruns}" if name != held["run"] and (not (root / "runs" / name).exists() or job_state(f"legion-ctl-{name}")): slots.give(n, held["run"], urls) # a finished attempt is only scored again: keep held["run"] = name slots.take(n, name, urls if job_state(f"legion-ctl-{name}") else None) row = attempt(args, root, secrets, tree, n, name, urls) if row is None: return None row["reruns"] = reruns if valid(row): break say(task, f"run doesn't count ({why_invalid(row)}): running it again") row["set_aside"] = why_invalid(row) with lock, (root / "rows-discarded.jsonl").open("a") as f: f.write(json.dumps(row) + "\n") else: say(task, f"gave up after {args.max_reruns} reruns") return row with lock, (root / "rows.jsonl").open("a") as f: f.write(json.dumps(row) + "\n") first = row.get("first_exit") or {} say(task, f"success={row['success']} exit={first.get('agent')} after " f"{first.get('after_s')} s, {first.get('team_moves')} team moves; posts={row['posts']} " f"overlap={row.get('room_overlap')} wall={row['wall_s']} s reruns={row['reruns']}") return row
def agents_on(urls: list[str], n: int, run: str) -> Counter: """How many of run `run`'s agents (agent-001 .. agent-00N) call each server: legion hashes each agent's run and name over the URLs (Inference.endpoint_for, legion#129), so teams on one shared list spread over its servers.""" block = Inference(urls=urls) return Counter(block.endpoint_for(run, f"agent-{k:03d}") for k in range(1, n + 1))
class Slots: """At most `parallel` teams, `max_agents` agents and `per_server` agents per model server (`<root>/max_agents` and `<root>/per_server` override them while the driver runs) in flight, granted in order. Every team gets the whole shared list; legion (#129) spreads its agents over it by run and name, and a team waits until the servers its agents land on have room (one server's KV cache holds about a dozen long agent contexts)."""
def __init__(self, root: Path, urls: list[str], parallel: int, max_agents: int, per_server: int): self.root, self.urls, self.parallel = root, urls, parallel self.defaults = {"max_agents": max_agents, "per_server": per_server} self.cond, self.teams, self.agents, self.load = threading.Condition(), 0, 0, Counter()
def cap(self, name: str) -> int: try: return int((self.root / name).read_text().strip()) except (OSError, ValueError): return self.defaults[name]
def take(self, n: int, run: str, urls: list[str] | None = None) -> list[str]: """Wait for room for team `run` of n (its agents' servers within the cap); `urls`: an adopted team's own (it already runs).""" chosen = urls or list(self.urls) added = agents_on(chosen, n, run) with self.cond: while not (self.teams < self.parallel and ( not self.agents or urls is not None or ( self.agents + n <= self.cap("max_agents") and all(self.load[u] + k <= self.cap("per_server") for u, k in added.items())))): self.cond.wait(30) self.teams, self.agents = self.teams + 1, self.agents + n self.load += added return chosen
def give(self, n: int, run: str, urls: list[str]) -> None: with self.cond: self.teams, self.agents = self.teams - 1, self.agents - n self.load -= agents_on(urls, n, run) self.cond.notify_all()
def live_run(root: Path, tag: str, tree: int, n: int) -> tuple[str, list[str] | None]: """The run of a team that a stopped driver launched and whose controller is still there, with its URLs (it keeps them); else the team's first run name and None.""" for spec in sorted((root / "src").glob(f"{tag}maze-t{tree:02d}-n{n:02d}*/spec.yaml")): if job_state(f"legion-ctl-{spec.parent.name}"): return spec.parent.name, yaml.safe_load(spec.read_text())["inference"]["urls"] return f"{tag}maze-t{tree:02d}-n{n:02d}", None
def upload(root: Path, dataset: str, prefix: str) -> None: """Each run directory's spec, results and logs, and the rows, to a private dataset; never run.env, and nothing that holds a Hub token.""" api = HfApi() api.create_repo(dataset, repo_type="dataset", private=True, exist_ok=True) if not api.dataset_info(dataset).private: raise SystemExit(f"{dataset} is public: refusing to upload") allow = ["*.jsonl", "*.csv", "*.md", "*.png", "runs/*/experiment/**", "runs/*/results/**", "runs/*/logs/**", "driver.log"] leaks = [str(p) for p in root.rglob("*") if p.is_file() and not p.name.endswith(".env") and SECRET.search(p.read_text(errors="ignore"))] if leaks: raise SystemExit(f"refusing to upload: Hub tokens in {leaks[:5]}") api.upload_folder(repo_id=dataset, repo_type="dataset", folder_path=root, path_in_repo=prefix, allow_patterns=allow, commit_message=f"s3-maze sweep: {prefix}") say("uploaded", root, "to", f"{dataset}/{prefix}")
def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--urls", required=True, help="the model servers, comma-separated") parser.add_argument("--model", required=True) parser.add_argument("--tag", required=True, help="put before every run and swarm name (e.g. q27-): two grids at " "once then never share a Slurm job name") parser.add_argument("--revision", help="the dataset revision every team pins (default: its " "head)") parser.add_argument("--trees", default="1-32") parser.add_argument("--agents", default="1,2,4,8,16") parser.add_argument("--parallel", type=int, default=20, help="teams at once") parser.add_argument("--max-agents", type=int, default=1000, help="agents at once") parser.add_argument("--per-server", type=int, default=1000, help="agents at once per model server (a team waits until the servers " "its agents hash to are within it)") parser.add_argument("--team-timeout", type=float, default=4800, help="s from a team's start until it is released anyway") parser.add_argument("--max-reruns", type=int, default=4, help="runs again of a team whose run doesn't count (why_invalid)") parser.add_argument("--root", type=Path, required=True) parser.add_argument("--bucket", default="lewtun/s3-maze-sweep", help="private bucket for the runs' state (a swarm's name is used once " "in a bucket)") parser.add_argument("--namespace", default="lewtun") parser.add_argument("--dataset", help="private dataset for the run directories") parser.add_argument("--prefix", help="folder in the dataset (default: the root's name)") parser.add_argument("--overloaded", help="START/END (ISO times): runs started then ran on " "an overloaded model server, and run again") parser.add_argument("--health", type=Path, help="the servers' health log (health-log.sh's servers.jsonl)") parser.add_argument("--cpus-per-agent", type=int, default=1, help="worker CPUs (and so memory, at 1900 MB each) per agent") parser.add_argument("--memory-ladder", help="ROTATE,DRAIN,PREEMPT: the workers' memory " "fractions (default: legion's 0.75,0.85,0.93)") parser.add_argument("--hint", action="store_true", help="every team gets the protocol hint (team.py --hint)") args = parser.parse_args(argv) global HEALTH, CPUS_PER_AGENT, MEMORY_LADDER, HINT HEALTH, HINT = args.health, args.hint CPUS_PER_AGENT = args.cpus_per_agent if args.memory_ladder: MEMORY_LADDER = dict(zip(("rotate", "drain", "preempt"), map(float, args.memory_ladder.split(",")), strict=True)) if args.overloaded: global OVERLOADED start, end = (datetime.fromisoformat(t) for t in args.overloaded.split("/")) OVERLOADED = (start, end) args.urls = args.urls.split(",") args.revision = team.pinned(args.revision) root = args.root.resolve() root.mkdir(parents=True, exist_ok=True) api = HfApi() api.create_bucket(args.bucket, private=True, exist_ok=True) if not api.bucket_info(args.bucket).private: raise SystemExit(f"bucket {args.bucket} is public: refusing") token = os.environ.get("HF_TOKEN") or get_token() secrets = root / f"secrets-{os.getpid()}.env" # per driver old = os.umask(0o077) secrets.write_text(f"HF_TOKEN={token}\nNAMESPACE={args.namespace}\n" f"BUCKET=hf://buckets/{args.bucket}\n") os.umask(old) rows_file = root / "rows.jsonl" rows = [json.loads(x) for x in rows_file.read_text().splitlines()] if rows_file.exists() else [] for r in rows: # rows from before the health check get it too if r.get("thrashed_min") is None and r.get("started_at") and r.get("wall_s"): start = datetime.fromisoformat(r["started_at"]).timestamp() r["thrashed_min"] = thrashed_minutes(root / "runs" / r["run"], r["agents"], start, start + r["wall_s"]) if bad := [r for r in rows if not valid(r)]: # an earlier driver kept them: run them again with (root / "rows-discarded.jsonl").open("a") as f: f.write("".join(json.dumps(r | {"set_aside": why_invalid(r)}) + "\n" for r in bad)) rows_file.write_text("".join(json.dumps(r) + "\n" for r in rows if valid(r))) say(f"{len(bad)} rows that don't count moved to rows-discarded.jsonl") done = {(r["tree"], r["agents"]) for r in rows if valid(r)} teams = [(t, n) for t in numbers(args.trees) for n in numbers(args.agents) if (t, n) not in done] # teams a stopped driver launched first: they hold their own time and their workers launched = {(t, n) for t, n in teams if any((root / "runs").glob( f"{args.tag}maze-t{t:02d}-n{n:02d}*/launch/*.env"))} teams.sort(key=lambda t: t not in launched) say(f"{len(teams)} teams to run ({len(done)} done, {len(launched)} to adopt), " f"{args.parallel} teams and {args.max_agents} agents at once, on {args.urls}") slots = Slots(root, args.urls, args.parallel, args.max_agents, args.per_server)
def one(t: int, n: int, urls: list[str], held: dict): try: return run_team(args, root, secrets, t, n, urls, slots, held) except Exception as e: # noqa: BLE001 - one team's failure must not stop the grid say(f"{args.tag}maze-t{t:02d}-n{n:02d}", "failed:", repr(e)[:300]) finally: slots.give(n, held["run"], urls)
try: with ThreadPoolExecutor(args.parallel) as pool: for t, n in teams: run, live = live_run(root, args.tag, t, n) urls = slots.take(n, run, live) pool.submit(one, t, n, urls, {"run": run}) finally: secrets.unlink(missing_ok=True) if args.dataset: upload(root, args.dataset, args.prefix or root.name) return 0
if __name__ == "__main__": sys.exit(main())1Before you go through a door, read the board and post which door you are taking; pick one no teammate has claimed; post when a branch is a dead end.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Write the Legion spec for one s3-maze team, from Legion's checkout (it needs Legion):
uv run python <this dataset>/legion/team.py --tree 7 --agents 4 [--where cluster|docker]
writes `out/maze-t07-n04/spec.yaml` next to this script (or `--out DIR`) fromspec.template.yaml: the tree `maze-t07` at `--revision` (default: the dataset's head on theHub), its 4 agents (agent-001 .. agent-004) all on that tree, on one worker with one board, and`stop_on_success` with the maze service's success check. `--where` picks the template's`where:` block: the HF cluster (Slurm, rootless podman, a worker of N + 2 CPUs) or local docker.`--hint` adds the protocol hint (team.md, next to this script) as the team's `team_file`.The dataset is private for now: HF_TOKEN must read it."""
import argparseimport copyimport shutilimport sysfrom pathlib import Path
import yamlfrom huggingface_hub import HfApi
from legion.models import load_spec_yaml
HERE = Path(__file__).resolve().parentDATASET = "HuggingFaceSwarms/s3-maze"TREES, SIZES = range(1, 33), (1, 2, 4, 8, 16)MB_PER_CPU = 1900 # hopper-cpu's MaxMemPerCPU is 2000
def merge(base: dict, extra: dict) -> dict: out = dict(base) for key, value in extra.items(): both = isinstance(value, dict) and isinstance(out.get(key), dict) out[key] = merge(out[key], value) if both else value return out
def fill(value, names: dict[str, str]): if isinstance(value, dict): return {k: fill(v, names) for k, v in value.items()} if isinstance(value, list): return [fill(v, names) for v in value] if isinstance(value, str): for placeholder, text in names.items(): value = value.replace(placeholder, text) return value
def worker_cpus(agents: int) -> int: """A CPU per agent (its container), two for the worker, the maze services and builds.""" return max(4, agents + 2)
def team_spec(template: dict, tree: int, agents: int, where: str, revision: str) -> tuple[str, dict]: """(the team's name, its spec) from the template.""" template = copy.deepcopy(template) places = template.pop("where") task, team = f"maze-t{tree:02d}", f"maze-t{tree:02d}-n{agents:02d}" spec = fill(merge(template, places[where]), {"TEAM": team, "TREE": task, "REVISION": revision}) spec["agents"] = {"count": agents} spec["workers"]["agents_per_worker"] = agents if where == "cluster": cpus = worker_cpus(agents) spec["compute"] |= {"cpus": cpus, "mem": f"{cpus * MB_PER_CPU}M"} return team, spec
def pinned(revision: str | None) -> str: """The revision (default: the dataset's head) as a commit.""" return HfApi().dataset_info(DATASET, revision=revision).sha
def main(argv=None) -> int: parser = argparse.ArgumentParser(description="Write one s3-maze team's Legion spec.") parser.add_argument("--tree", type=int, required=True, choices=TREES) parser.add_argument("--agents", type=int, required=True, choices=SIZES) parser.add_argument("--where", choices=("cluster", "docker"), default="cluster") parser.add_argument("--revision", help="the dataset revision to pin (default: its head)") parser.add_argument("--out", type=Path, help="default: out/<team> next to this script") parser.add_argument("--hint", action="store_true", help="add the protocol hint (team.md) as the team's team_file") args = parser.parse_args(argv) template = load_spec_yaml((HERE / "spec.template.yaml").read_text()) team, spec = team_spec(template, args.tree, args.agents, args.where, pinned(args.revision)) out = args.out or HERE / "out" / team out.mkdir(parents=True, exist_ok=True) if args.hint: shutil.copyfile(HERE / "team.md", out / "team.md") spec["team_file"] = "team.md" header = (f"# {team} ({args.where}), written by {DATASET}'s legion/team.py from " "spec.template.yaml: edit the template, not this file.\n") (out / "spec.yaml").write_text(header + yaml.safe_dump(spec, sort_keys=False, width=100)) print(out / "spec.yaml") return 0
if __name__ == "__main__": sys.exit(main())8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t01-5d40939e94c9build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t01-f95fbf219418build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t02-588ed6cc37d1build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t02-446d4937ddafbuild:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t03-6a9f79a6d257build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t03-2f1c9db92d2dbuild:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t04-69783b4912eebuild:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t04-ff2621b36334build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t05-65872ba1a0b8build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t05-70ed430ae624build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t06-669df04bb032build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t06-b899e2c5042abuild:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t07-4653c3938d80build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t07-564a0ae975bfbuild:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t08-effcdb7d44a8build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t08-aedfe0bcc69cbuild:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t09-c57f68449189build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t09-ba69534fb0f1build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t10-bced090b1577build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t10-1ee257ade8c3build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t11-00747a305f04build:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t11-c21af2c3f5debuild:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
12345"""flock's success_check for s3-maze (`stop_on_success`), run in this maze service, never in theagent's container: `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a1234"""Read the exit status from the maze service with `python3 -I -S /app/success.py`.Read-only: it prints `{"success": <the exit was reached>, "evidence": {...}}` from the walk'sstate file, which only service.py writes. No state yet, or one that can't be read, is not a
8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t12-1f31816477cfbuild:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's way out (Flock replaces it with the agent's own network)maze:internal: true8 unmodified lines91011121314154 unmodified lines2021222324258 unmodified linessecurity_opt: [no-new-privileges:true]depends_on: [maze]maze:image: s3-maze-service:maze-t12-b1d1bfd933dfbuild:context: ./mazenetworks: [maze]4 unmodified linespids_limit: 64mem_limit: 256mnetworks:default: {} # main's egress networkmaze:internal: true
5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (flock's success_check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""5 unmodified lines67891011125 unmodified linesand that a room is the exit only by reaching it.Every move, accepted or refused, is appended to the move log (agent, from, to, time) before it isanswered, and the walk's state file is replaced after it: success.py (the exit status check)and export.py (Harbor's collect hook, for the grader) read those two files. A restartedcontainer resumes from them. Python 3.10+, standard library only."""
README.md+25-150
budget.py+1-1
check.py+6-114
eval/metrics.pyDeleted-404
generate.py+1-1
legion/registries.confDeleted-13
legion/spec.template.yamlDeleted-73
legion/sweep/README.mdDeleted-87
legion/sweep/health-log.shDeleted-27
legion/sweep/plot.pyDeleted-293
legion/sweep/serve-vllm.sbatchDeleted-33
legion/sweep/setaside.pyDeleted-96
legion/sweep/sweep.pyDeleted-570
legion/team.mdDeleted-1
legion/team.pyDeleted-101
tasks/maze-t01/environment/docker-compose.yaml+2-2
tasks/maze-t01/environment/maze/service.py+1-1
tasks/maze-t01/environment/maze/success.py+1-2
tasks/maze-t02/environment/docker-compose.yaml+2-2
tasks/maze-t02/environment/maze/service.py+1-1
tasks/maze-t02/environment/maze/success.py+1-2
tasks/maze-t03/environment/docker-compose.yaml+2-2
tasks/maze-t03/environment/maze/service.py+1-1
tasks/maze-t03/environment/maze/success.py+1-2
tasks/maze-t04/environment/docker-compose.yaml+2-2
tasks/maze-t04/environment/maze/service.py+1-1
tasks/maze-t04/environment/maze/success.py+1-2
tasks/maze-t05/environment/docker-compose.yaml+2-2
tasks/maze-t05/environment/maze/service.py+1-1
tasks/maze-t05/environment/maze/success.py+1-2
tasks/maze-t06/environment/docker-compose.yaml+2-2
tasks/maze-t06/environment/maze/service.py+1-1
tasks/maze-t06/environment/maze/success.py+1-2
tasks/maze-t07/environment/docker-compose.yaml+2-2
tasks/maze-t07/environment/maze/service.py+1-1
tasks/maze-t07/environment/maze/success.py+1-2
tasks/maze-t08/environment/docker-compose.yaml+2-2
tasks/maze-t08/environment/maze/service.py+1-1
tasks/maze-t08/environment/maze/success.py+1-2
tasks/maze-t09/environment/docker-compose.yaml+2-2
tasks/maze-t09/environment/maze/service.py+1-1
tasks/maze-t09/environment/maze/success.py+1-2
tasks/maze-t10/environment/docker-compose.yaml+2-2
tasks/maze-t10/environment/maze/service.py+1-1
tasks/maze-t10/environment/maze/success.py+1-2
tasks/maze-t11/environment/docker-compose.yaml+2-2
tasks/maze-t11/environment/maze/service.py+1-1
tasks/maze-t11/environment/maze/success.py+1-2
tasks/maze-t12/environment/docker-compose.yaml+2-2
tasks/maze-t12/environment/maze/service.py+1-1