Keep s3-aggregation Harbor-native
#1
by lewtun HF Staff - opened
Files changed (14)
- README.md+17-143
- check.py+3-333
- eval/metrics.pyDeleted-329
- generate.py+3-4
- legion/spec.template.yamlDeleted-72
- legion/sweep/README.mdDeleted-86
- legion/sweep/failures.pyDeleted-134
- legion/sweep/plot.pyDeleted-224
- legion/sweep/registries.confDeleted-13
- legion/sweep/serve-vllm.sbatchDeleted-29
- legion/sweep/setaside.pyDeleted-74
- legion/sweep/sweep.pyDeleted-341
- legion/sweep/waits.pyDeleted-41
- legion/team.pyDeleted-85
16 unmodified lines17181920212223242520212223242521 unmodified lines4748495354555657505152535463646566676855565758596011 unmodified lines727374868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012175761231241251261271287778791311321331341351361378081821401411421438384851458687147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181888990913 unmodified lines959697191989910025 unmodified lines12612712822322422522622722822923023123223323423523623723823924024124224324424524624724812913025125225325425513113213313413513613713826226326426526613914014114214316 unmodified linesA [Harbor](https://harborframework.com) environment that measures whether a swarm of agents**communicates**: each agent holds one private number, and no agent can solve the task alone. Itadapts the information-aggregation 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.
**This dataset is private for now.**[s³: Simple Scaling of Swarms via Cooperative Multi-agent RL](https://arxiv.org/abs/2611.08615).A team uses a shared message board supplied by the runner. Each participant receives its ownHarbor task.
## The task
21 unmodified lines tests/test.sh the grader, the same for every slot of the team tests/expected.json the team's answer: copied in only after the agent is done solution/solve.sh an oracle with its own copy of the answerlegion/ spec.template.yaml what every team's Legion run shares: model, board rules, loop, limits team.py writes one team's spec (docker, HF Sandboxes or the HF cluster) sweep/ the scaling sweep on the HF cluster (legion/sweep/README.md)eval/metrics.py one row per team from Legion run directoriesproblems.json the 32 problemsgenerate.py writes problems.json and tasks/ from its seed (115)check.py the checks that need no model```
**Private numbers** reach each agent only through its own task. Legion runs a team with theselector `agg-pPP-nNN-s*`, `agents.count: N` and `naming: consecutive-id`: the selector matchesthe team's N slots, sorted by name, and `agent-00K` runs slot K's task, so its instructionholds its own number and no one else's. A task folder puts nothing in the container while theagent works (no `environment/`; `tests/` arrives after the agent is done), so no agent can readanother agent's number until that agent posts it.**Private numbers** reach each participant through its own task. To run a team, assign eachparticipant one of its slots in name order and give the team a fresh board shared only amongits members. Harbor copies `tests/` in after the agent has finished.
## Reward
11 unmodified linescan change what it imports; besides `bash`, `python3` is the only command it runs. Each agent isscored on its own answer; the team succeeds if any agent scores 1.
## Run it with Legion
Legion's [`experiments/s3-aggregation/spec.yaml`](https://github.com/huggingface/legion/tree/main/experiments/s3-aggregation)runs one team on HF Sandboxes (`TEAM`, default `agg-p01-n04`, with `N` its size) at the revisionit pins: `uv run legion launch experiments/s3-aggregation/spec.yaml`. Its board is a public Spacefor the run: delete it afterwards.
For any other team or place, `legion/team.py` writes the spec from `legion/spec.template.yaml`,run from Legion's checkout. **Needs** `HF_TOKEN`, which reads the private dataset (and starts thesandboxes and deploys the board's Space), and `HF_INFERENCE_TOKEN`, a fine-grained token withonly "Make calls to Inference Providers", which goes into the agents' containers. Never the sametoken. Each agent of a team is `agent-001` ... (`naming: consecutive-id`), all one Legion type onone worker (`agents_per_worker: N`), so they share that worker's board.
### On HF Sandboxes
The controller and the team's one worker run on this machine, each agent in its own HF Sandbox(`cpu-basic`) and the board on a Space:
```shDS=../s3-aggregation # this dataset, at the revision team.py pinsuv run python $DS/legion/team.py --problem 7 --agents 4 --where sandbox --out runs/agg-p07-n04BOARD_SPACE=<you>/s3-agg-p07-n04 uv run legion launch runs/agg-p07-n04/spec.yamluv run legion status agg-p07-n04uv run python $DS/eval/metrics.py .legion/agg-p07-n04-<time>/ # once the run has endedhf repos delete <you>/s3-agg-p07-n04 --repo-type space -y # a new board for every teamhf buckets delete <you>/s3-agg-p07-n04-bucket # its snapshots```
The run ends by itself once its loop is over (4 rounds or 15 minutes) and every agent is idle,then Harbor grades each agent's `/app/answer.json` and the board is exported into the rundirectory. The board's Space must be public while the run uses it (the sandboxes hold no Hubtoken), and the instruction has no run tag, so give each team a new Space and delete it, and itssnapshot bucket, once the run directory has the export.
### On the HF cluster## Run a Harbor task
`--where cluster` writes the spec for one Slurm worker running the team in rootless podman(hopper-cpu has podman 4.9), with a local board on that worker, new each run, so no Space. Therun directory goes on the shared disk (Legion's docs/slurm.md "Deploying"): a cluster profile with`SLURM_PARTITION=hopper-cpu`, `WORKER_CPUS` and `WORKER_MEM` (at most 2000 MB per CPU there)and `VENV`, and a mode-600 secrets file with `HF_TOKEN`, `HF_INFERENCE_TOKEN`, `NAMESPACE` and`BUCKET` (a private bucket for the run's state):Validate the grader with the oracle for one slot:
```shuv run python $DS/legion/team.py --problem 7 --agents 4 --where cluster --out runs/src/agg-p07-n04uv run legion init $PWD/runs/agg-p07-n04 --from runs/src/agg-p07-n04 --profile cluster.env --secrets secrets.envexport LEGION_RUN_DIR=$PWD/runs/agg-p07-n04uv run legion launch $LEGION_RUN_DIR/experimentuv run legion status agg-p07-n04 # until the loop is done and the agents idleuv run legion stop agg-p07-n04 --release # drain: each Trial is graded, then the jobs enduv run python $DS/eval/metrics.py $LEGION_RUN_DIRuv run --with harbor==0.25.0 harbor run --path tasks/agg-p01-n02-s01 --agent oracle --env docker```
A Slurm run doesn't end by itself: `--release` drains its worker, which is when each Trial isgraded. With Legion's Slurm results (huggingface/legion#122) the worker copies the gradingand the board export to `<run dir>/results/` (its own files are in the node's `/tmp`), and`metrics.py` reads them from there. `legion/sweep/` runs the whole grid this way.For a cooperative run, the runner supplies the shared message board and aggregates theindividual Trial rewards. The team succeeds if any participant earns 1.
### The board rulesThe maintained team recipe uses these tasks with a shared board. [Legion experiment](https://github.com/huggingface/legion/tree/main/experiments/s3-aggregation)
The same for every eval run, since they shape how agents talk (`legion/spec.template.yaml`): onechannel, `#general`, and no other (`max_channels: 1`: an agent can't create a channel); anagent is woken by a mention or a reply in its thread; a post isat most 1000 characters, at least 5 s after the agent's previous one, and at most 40 per agent.One channel keeps every number in one place, as the paper's broadcast does (in earlier runs,without the cap, about 70% of Qwen3.5-2B teams made extra channels, though about 98% of theirposts stayed in `#general`); waking on mentions andthreads lets agents talk to each other without a reply to every post; the length, gap and countcaps bound what a looping agent can flood the board with, well above what the task needs (onepost per agent). Docker and podman enforce them in each agent's rule proxy. HF Sandboxes have noproxy, so there they are not enforced and each Trial records a `message_board.warning` event.
## Metrics
`uv run python eval/metrics.py RUN_DIR [RUN_DIR ...] [--out rows.jsonl]` writes one JSON lineper run directory (one team): a local run's `.legion/<swarm>-<time>/`, or a Slurm run'sdirectory. A Slurm run has no local bundle, so there the tokens come from Harbor's Trial results(no reasoning split) and `stop_reason`, `cost_usd` and the turns are `null`:
| 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; 0 when every agent receives from as many teammates, 1 when one receives from all and no one else from anyone; `null` for N = 1 || `reciprocity` | the fraction of edges whose reverse exists; `null` without edges || `missing` | what the run directory lacks: an agent's reward, the board export |
Only messages posted between the run's start and end count. A post that mentions no one adds noedge: on a board everyone reads every post, so a broadcast edge (the paper's) would connectevery pair that posts. s3-maze adds its move-log metrics to the same rows (`EXTRAS`).The prior sweep and metrics are archived with the original run setup. [Dataset revision `bc8474f`](https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation/tree/bc8474f012ef8270fde97e93a828c929e867ff3d)
## Checks
3 unmodified linesuv run check.py # the Trials on HF Sandboxes (HF_TOKEN, twenty cpu-basic sandboxes)uv run check.py --env docker # the Trials in local dockeruv run check.py --env none # without the Trialsuv run check.py --env none --run RUN_DIR # also a Legion run of a team (below)```
1. **Generator:** `generate.py` reproduces `problems.json` and `tasks/` byte for byte; another25 unmodified lines and the verifier scores each 0: `/app/answer.json` as a symlink to `/tests/expected.json`; `/app` as a symlink into a `/tests` they made; a `json.py` that reads any answer as right wherever the verifier may start; a `sitecustomize` in site-packages that does the same.5. **No-cheat, a Legion run** (`--run RUN_DIR`, a local run's `.legion/<swarm>-<time>/`): each agent's first prompt (its task's instruction and Legion's) holds its own number and no teammate's; the first tool output in which an agent sees a teammate's number is a board read, after that teammate posted it; and the first post holding each number is its owner's. A number counts in words and in digits where they read as a held number: an array of the team's integers (the JSON answer, or part of it, down to `[26]`), an agent's number in a mapping (`"agent-002": 26`) or a stated number (`number is 26`); bare ids, counts and timestamps don't. A board read is a `legion-tool message_board.*` command, not one that names the board (`cat /tmp/message_board.txt`). The audit itself runs on synthetic runs every time: a clean one, and one whose ids and timestamps hold the team's numbers, pass; a teammate's number in words, the JSON answer, a one-element array, a mapping or a stated number in the first prompt or in a non-board output before the board (one from a file named after the board included) fail, and so does a number first posted by an agent that doesn't hold it.6. **Metrics:** `eval/metrics.py` on Slurm run directories (the spec Legion's example copies, with `${TEAM:-...}` and `${N:-4}`, and Trials graded by the tasks' own grader): the task and the roster come from the spec as the run resolved it (`cluster.env`, then `run.env`, else the defaults), and a planned agent without results, Trials of an unplanned agent and Trials of another task than the spec selects are flagged in `missing`, never dropped.
`--env` takes a Harbor environment type or an import path. Harbor 0.25.0's `hf-sandbox` uploads`tests/` with the host's file owner, which a sandbox can't take when the host's uid is over65535 (some clusters); Legion's `--env legion.harbor.envs:HFSandbox`, with Legion installed, keepsno owner.
To check the grader alone with Harbor: `harbor run --path tasks/agg-p07-n04-s01 --agent oracle --env hf-sandbox`.
## Known limits
- **Private for now**, so whatever resolves and downloads the task (Legion's worker, which then uploads it into the sandbox) needs a Hub token that can read it. The sandboxes never do.- **A team needs one agent per slot.** Each slot's task is one agent's view: run a team's N slots together on one board (Legion's selector `agg-pPP-nNN-s*` with `agents.count: N`), or a task alone is an agent whose teammates never post.- Each multi-agent task is one participant's view. Its teammates' numbers are available through the runner's message board.- **The grader can't see the board:** an agent could guess or copy a wrong number and still be scored only on its file. The board export in the run directory shows what was said.- **The verifier runs in the agent's container**, as in every Harbor task. The grader closes the file and import holes above, but an agent that replaced the container's `python3`, `bash` or Python's standard library, or left a process running to rewrite the reward, could still forge one: check the run's board export and the agents' transcripts when a result looks too good.- **One board per team.** The instruction has no run tag, so a reused board's earlier posts would read as this team's: give each team a new board (Legion's local board is new each run; delete a Space board after its run).- **Board rules** are enforced only where Legion's rule proxy runs (docker, podman); on HF Sandboxes they are not.- Give each team a fresh board so it only sees posts from its own run.
- **Not the paper's setup:** a message board instead of `message`/`read_messages` tools with notifications, an answer file instead of a `####` line, no example message, no token cost in the reward, and N = 1 is a solo control rather than a team.6 unmodified lines7891010111226 unmodified lines3940414344454647484950515253545556575859606162636465424344457 unmodified lines5354557956575839 unmodified lines9899100125101102103104232 unmodified lines337338339364365340341342343203 unmodified lines54754854957557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386455055155255355455587187255655755811 unmodified lines5705715728908918928938948958968978988999009019025735745756 unmodified lines uv run check.py # all of them; the Trials run on HF Sandboxes (HF_TOKEN) uv run check.py --env docker # the Trials in local docker instead uv run check.py --env none # skip the Trials uv run check.py --run RUN_DIR # also a Legion run of a team (group 5)
1. Generator: generate.py reproduces problems.json and tasks/ byte for byte from its seed; another seed gives other problems; 32 problems of 16 integers in 1..99; the English words26 unmodified lines /tests/expected.json; a symlinked /app into a /tests they made; a json.py that reads any answer as right wherever the verifier may start; a sitecustomize in site-packages that does the same. The verifier scores each 0. `--env` takes a Harbor environment type or an import path. Harbor 0.25.0's hf-sandbox uploads tests/ with the host's file owner, which a sandbox can't take when the host's uid is over 65535 (some clusters): use legion's `--env legion.harbor.envs:HFSandbox` there.5. No-cheat, a Legion run (`--run`, a local run's directory with its agents' event streams and the board export; the team is the selector's `agg-pPP-nNN`, agent K on slot K): no system prompt or first prompt holds a teammate's number, and each agent's first prompt holds its own; the first output in which an agent sees a teammate's number is a board read, or a later prompt (a wake-up quoting the board); and the first post holding each number is its owner's. A number counts in words ("twenty-six") and in digits where they read as a held number: an array of the team's integers (the JSON answer, or part of it, down to `[26]`), an agent's number in a mapping (`"agent-002": 26`) and a stated number (`number is 26`); bare ids, counts and timestamps don't. A board read is a `legion-tool message_board.*` command, not a command that names the board (`cat /tmp/message_board.txt`). The audit itself is checked on synthetic runs, always: a clean one and one whose ids and timestamps hold the team's numbers pass, and each leak fails (a teammate's number in words, the JSON answer, a one-element array, a mapping and a stated number, in the first prompt or in a non-board output before the board, including one from a file named after the board, and a number first posted by an agent that doesn't hold it).6. Metrics: eval/metrics.py on Slurm run directories (the spec Legion's example copies, its `${TEAM:-...}` and `${N:-4}`, Trials graded by the tasks' own grader): the task and the roster come from the spec as the run resolved it (`cluster.env`, then `run.env`, else the defaults), and a planned agent without results, Trials of an unplanned agent and Trials of another task than the spec selects are flagged in `missing`, never dropped. `--env` takes a Harbor environment type or an import path."""
import argparse7 unmodified linesimport subprocessimport sysimport tempfilefrom collections import Counterfrom pathlib import Path
HERE = Path(__file__).resolve().parent39 unmodified lines
def held(team: str) -> dict[str, str]: """A team's agents (Legion's consecutive names: agent K on slot K) and their numbers.""" """A team's slot labels and their private numbers.""" problem, n = team_of(team) numbers = json.loads((HERE / "problems.json").read_text())["problems"][f"p{problem:02d}"] return {f"agent-{k:03d}": g.words(x) for k, x in enumerate(numbers[:n], 1)}232 unmodified lines f"{task.name}: the answer is in {sorted(holders)}") check(all(len(v) == 1 for v in by_size.values()), "an instruction (but its number) or task.toml differs between tasks of one team size") beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {"tasks", "legion", "eval", ".cache", "__pycache__", ".git"} beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {"tasks", ".cache", "__pycache__", ".git"} check(not beside, f"folders beside tasks/: {sorted(beside)}")
203 unmodified lines return report
def texts(message: dict) -> str: return "\n".join(part.get("text", "") for part in message.get("content") or [] if isinstance(part, dict))
ARRAY = re.compile(r"\[\s*\d{1,2}(?:\s*,\s*\d{1,2})*\s*\]") # one element or more# a board tool run as a command (Legion's legion-tool CLI, not a path that ends in it), not a file# or word that merely names the boardBOARD_CALL = re.compile(r"(?<![\w./-])legion-tool\s+message_board\.[a-z_]+")STATED = ( # digits that read as a number someone holds; bare ids, counts and timestamps don't re.compile(r"agent-\d{3}[\"']?\s*[:=]\s*[\"']?(\d{1,2})(?![\d.:])"), # "agent-002": 26 re.compile(r"\bnumbers?\b(?:\s+(?:is|are|was|were)|:|=)?\s*[\"']?(\d{1,2})(?![\d.:])", re.IGNORECASE), # number is 26)
def given_away(text: str, team: dict[str, str]) -> set[int]: """The team's numbers that `text` holds: as words ("twenty-six"), or as digits where they read as a held number: an array of the team's integers (a whole or partial answer, e.g. `[15, 26, 37]`), an agent's number in a mapping or a line (`"agent-002": 26`), or a number stated as one (`number is 26`, `numbers: 15`).""" values = Counter(read_words(w) for w in team.values()) out = {read_words(w) for w in holds(text, set(team.values()))} for array in ARRAY.findall(text): numbers = Counter(int(x) for x in re.findall(r"\d+", array)) if not numbers - values: # all of them the team's out |= set(numbers) for pattern in STATED: out |= {int(x) for x in pattern.findall(text)} & set(values) return out
def audit_run(run: Path) -> tuple[list[str], dict]: """(problems, report) for a Legion run of one team (a local run's `.legion/<swarm>-<time>/`): no prompt Legion gave an agent holds a teammate's number, and its first prompt holds its own; the first output in which an agent sees a teammate's number is a board read (or a wake-up that quotes the board), and the first post holding each number is its owner's. A number counts as words or as digits (given_away).""" problems = [] spec = json.loads((run / "run.json").read_text())["spec"] harbor = next(t["harbor"] for t in spec["types"].values() if t.get("harbor")) selector = harbor["config"]["task"]["selector"] # agent K on slot K task = selector[0] if isinstance(selector, list) else selector team = held(task) numbers = {agent: read_words(word) for agent, word in team.items()} boards = sorted(run.rglob("resources/message_board/board.jsonl")) if len(boards) != 1: problems.append(f"run {run.name}: {len(boards)} board exports") posts = sorted((json.loads(x)["message"] for b in boards[:1] for x in b.read_text().splitlines() if x.strip()), key=lambda m: m["created_at"]) first = {} for post in posts: for number in given_away(post["body"], team): first.setdefault(number, post["sender"]["external_id"]) for number, who in first.items(): if numbers.get(who) != number: problems.append(f"run {run.name}: {number} was first posted by {who}") report = {"task": task, "posts": len(posts), "first_posts": first} for agent, own in team.items(): path = run / "agents" / "_sessions" / f"{agent}.jsonl" if not path.is_file(): problems.append(f"run {run.name}: no event stream for {agent}") continue others = set(numbers.values()) - {numbers[agent]} seen, calls, prompts, got_own, board_reads = set(), {}, 0, False, 0 for line in path.read_text().splitlines(): event = json.loads(line) if line.strip() else {} message = event.get("message") or {} if event.get("type") != "message": continue role, text = message.get("role"), texts(message) if role == "assistant": for part in message.get("content") or []: if isinstance(part, dict) and part.get("type") == "toolCall": arguments = part.get("arguments") or {} calls[part.get("id")] = str(arguments.get("command") or json.dumps( arguments)) elif role in ("system", "user"): if role == "system" or prompts == 0: # what Legion and the task tell the agent if given := given_away(text, team) & others: problems.append(f"run {agent}: its {role} prompt holds {sorted(given)}") got_own |= role == "user" and own in holds(text, {own}) else: # a later prompt may quote the board (a wake-up on a mention) seen |= given_away(text, team) & others prompts += role == "user" elif role == "toolResult": command = calls.get(message.get("toolCallId"), "") board_read = bool(BOARD_CALL.search(command)) board_reads += board_read new = given_away(text, team) & others - seen if new and not board_read: problems.append(f"run {agent}: first saw {sorted(new)} in the output of " f"{command[:120]}") seen |= new if not got_own: problems.append(f"run {agent}: its first prompt doesn't hold its own number") report[agent] = {"saw": len(seen), "got_own": got_own, "board_reads": board_reads} return problems, report
def check_run(run: Path) -> dict: problems, report = audit_run(run) failures.extend(problems) return report
AUDIT_TEAM = "agg-p01-n04"
def synthetic_run(root: Path, prompt: str = "", output: str = "", poster: dict | None = None, command: str = "cat /tmp/notes.json") -> Path: """A local run directory of AUDIT_TEAM as Legion leaves it, whose agents behave: each posts its number and reads the board. `prompt` joins agent-001's first prompt, `output` is the output of a non-board `command` it runs before it reads the board, and `poster` posts a number in another agent's name first (agent -> number). Each agent's first prompt is its own slot's instruction.""" team = held(AUDIT_TEAM) run = root / f"run-{len(list(root.iterdir()))}" (run / "agents" / "_sessions").mkdir(parents=True) (run / "run.json").write_text(json.dumps({"spec": {"types": {"agent": {"harbor": { "config": {"task": {"selector": [f"{AUDIT_TEAM}-s01", f"{AUDIT_TEAM}-s02"]}}}}}}})) board = run / "agents" / "_harbor" / "_worker" / "resources" / "message_board" board.mkdir(parents=True) lines = [f"{who}: my number is {g.words(number)} ({number})" for who, number in (poster or {}).items()] lines += [f"{agent}: my number is {word} ({read_words(word)})" for agent, word in team.items()] senders = [*(poster or {}), *team] board_lines = [json.dumps({"channel_id": 1, "message": { "seq": k, "created_at": 1000.0 + k, "body": body, "sender": {"external_id": who}}}) for k, (who, body) in enumerate(zip(senders, lines, strict=True), 1)] (board / "board.jsonl").write_text("\n".join(board_lines) + "\n")
def message(role, content, **extra): return json.dumps({"type": "message", "message": {"role": role, "content": content, **extra}})
def call(k, command): return message("assistant", [{"type": "toolCall", "id": f"c{k}", "arguments": {"command": command}}])
def result(k, text): return message("toolResult", [{"type": "text", "text": text}], toolCallId=f"c{k}")
for agent in team: own = HERE / "tasks" / f"{AUDIT_TEAM}-s{agent[-2:]}" / "instruction.md" events = [message("system", [{"type": "text", "text": "You are Pi."}]), message("user", [{"type": "text", "text": own.read_text() + ( prompt if agent == "agent-001" else "")}])] if agent == "agent-001" and output: events += [call(2, command), result(2, output)] events += [call(3, "legion-tool message_board.read --json '{}'"), result(3, json.dumps({"messages": lines}))] (run / "agents" / "_sessions" / f"{agent}.jsonl").write_text("\n".join(events) + "\n") return run
def check_audit() -> int: """audit_run on synthetic runs: a clean one passes, ids and timestamps that happen to be the team's numbers pass, and each leak fails: words, the JSON answer, a one-element array, a mapping and a stated number, in the first prompt or a non-board output before the board (a file named after the board is not the board); and a number first posted by an agent that doesn't hold it. Returns the cases checked.""" team = held(AUDIT_TEAM) numbers = [read_words(w) for w in team.values()] # agent-001's first answer = json.dumps(sorted(numbers)) mapping = json.dumps({a: read_words(w) for a, w in team.items()}) noise = json.dumps({"id": numbers[1], "seq": numbers[2], "count": numbers[3], "created_at": f"2026-11-16T{numbers[2]:02d}:{numbers[3]:02d}:00Z"}) cases = { "clean": ({}, False), "ids, counts and a timestamp that hold the numbers": ({"output": noise}, False), "a teammate's number in words in the first prompt": ( {"prompt": f"\nagent-002 holds {team['agent-002']}."}, True), "the JSON answer in the first prompt": ({"prompt": f"\nThe answer is {answer}."}, True), "the JSON answer in a non-board output": ({"output": answer}, True), "a mapping of agents to numbers in a non-board output": ({"output": mapping}, True), "a teammate's number stated in digits in a non-board output": ( {"output": f"agent-003's number is {numbers[2]}"}, True), "a stated number from a file whose name mentions the board": ( {"output": f"agent-002's number is {numbers[1]}", "command": "cat /tmp/message_board.txt"}, True), "a teammate's number as a one-element array in the first prompt": ( {"prompt": f"\nagent-002: [{numbers[1]}]"}, True), "a teammate's number as a one-element array in a non-board output": ( {"output": f"[{numbers[1]}]"}, True), "a number first posted by an agent that doesn't hold it": ( {"poster": {"agent-001": numbers[1]}}, True), } with tempfile.TemporaryDirectory() as d: for case, (kwargs, leaks) in cases.items(): problems, _ = audit_run(synthetic_run(Path(d), **kwargs)) check(bool(problems) == leaks, f"audit: {case}: {problems or 'no problem found'}") return len(cases)
# ------------------------------------------------------------------ metrics
# The lines of Legion's experiments/s3-aggregation/spec.yaml that eval/metrics.py readsRUN_SPEC = """name: ${TEAM:-agg-p01-n04}naming: consecutive-idtask: repo: https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation selector: ${TEAM:-agg-p01-n04}-s* revision: REVISIONagents: count: ${N:-4}"""
def metrics_module(): import importlib.util
spec = importlib.util.spec_from_file_location("_s3_metrics", HERE / "eval" / "metrics.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
def slurm_dir(root: Path, team: str, agents: list[str], env_files: dict[str, str]) -> Path: """A Slurm run's directory as `legion init` and the workers leave it: the spec, the env files and, per agent in `agents`, one Trial of its own slot of `team`, graded by the task's own grader (agent-001 answers right, the others wrong).""" (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 in enumerate(agents, 1): task = HERE / "tasks" / f"{team}-s{int(agent[-3:]):02d}" right = json.loads((task / "tests" / "expected.json").read_text()) reward = grade(task, json.dumps(right if k == 1 else [0]).encode()) trial = root / "results" / "s3" / agent / "trials" / f"s3-{agent}-t1" (trial / "verifier").mkdir(parents=True) (trial / "verifier" / "reward.txt").write_text(str(reward)) (trial / "result.json").write_text(json.dumps({ "task_name": f"HuggingFaceSwarms/{task.name}", "trial_name": trial.name, "started_at": f"2026-11-17T11:38:1{k % 10}+00:00", "finished_at": "2026-11-17T11:50:04+00:00", "agent_result": {"n_input_tokens": 1000, "n_cache_tokens": 0, "n_output_tokens": 50}, "verifier_result": {"rewards": {"reward": float(reward)}}})) return root
def check_metrics() -> int: """eval/metrics.py on Slurm run directories: the spec as the run resolved it (`cluster.env` then `run.env`, else the defaults) gives the task and the roster; a planned agent without results, Trials of an unplanned agent and Trials of another task are flagged, never dropped. Returns the cases checked.""" metrics = metrics_module() four = [f"agent-{k:03d}" for k in range(1, 5)] cases = { # name: (team the Trials ran, agents with Trials, env files, task, agents, missing) "defaults": ("agg-p01-n04", four, {}, "agg-p01-n04", 4, []), "run.env": ("agg-p02-n02", four[:2], {"cluster.env": "N=3\nTEAM=agg-p05-n04\n", "run.env": "#TEAM=agg-p01-n04\nTEAM=agg-p02-n02\nN=2\n"}, "agg-p02-n02", 2, []), "an agent's results gone": ("agg-p01-n04", four[:3], {}, "agg-p01-n04", 4, ["reward: agent-004"]), "run.env gone": ("agg-p02-n02", four[:2], {}, "agg-p01-n04", 4, [("task: the spec selects 'agg-p01-n04-s*', the Trials ran " "agg-p02-n02-s01, agg-p02-n02-s02"), "reward: agent-003", "reward: agent-004"]), "an unplanned agent": ("agg-p01-n04", four[:3], {"run.env": "N=2\n"}, "agg-p01-n04", 2, ["agents: Trials of agents the spec didn't plan: agent-003"]), # inline comments, as Legion's read_env_file reads them: after a quoted value's closing # quote, and after whitespace in an unquoted one "quoted values with comments": ("agg-p03-n04", four[:3], {"run.env": 'TEAM="agg-p03-n04" # group\nN="4" # size\n'}, "agg-p03-n04", 4, ["reward: agent-004"]), "unquoted values with comments": ("agg-p02-n02", four[:2], {"cluster.env": "N=3 # size\n", "run.env": "export TEAM=agg-p02-n02 # group\n" "N=2\t# size\n"}, "agg-p02-n02", 2, []), } with tempfile.TemporaryDirectory() as d: for case, (team, agents, env_files, task, count, missing) in cases.items(): root = Path(d) / ("run-" + re.sub(r"\W+", "-", case)) r = metrics.row(slurm_dir(root, team, agents, env_files)) check(r["task"] == task and r["agents"] == count and len(r["rewards"]) == count, f"metrics, {case}: task {r['task']!r}, {r['agents']} agents, not {task!r}, " f"{count}") check(sorted(r["missing"]) == sorted([*missing, "board export"]), f"metrics, {case}: missing {r['missing']}") expected = {a: 1.0 if a == "agent-001" else 0.0 for a in agents if a in r["rewards"]} check({a: v for a, v in r["rewards"].items() if v is not None} == expected and r["success"] is True, f"metrics, {case}: rewards {r['rewards']}") return len(cases)
def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--env", default="hf-sandbox", help="Harbor environment type or import path for the Trials; none: skip") parser.add_argument("--jobs-dir", type=Path, default=None, help="keep the Trials' files here (default: a temporary directory)") parser.add_argument("--run", type=Path, action="append", default=[], help="also check a Legion run of a team (a local run's directory)") args = parser.parse_args() check_generator() print(f"1. generator: {len(failures)} failures")11 unmodified lines report = asyncio.run(check_trials(args.env, jobs)) print(f"4. no-cheat (Trials on {args.env}, {PROBE_TEAM}): {len(failures) - before} " f"failures; {json.dumps(report)}") before = len(failures) cases = check_audit() print(f"5. no-cheat (the Legion-run audit on {cases} synthetic runs): " f"{len(failures) - before} failures") before = len(failures) cases = check_metrics() print(f"6. metrics (eval/metrics.py on {cases} Slurm run directories): " f"{len(failures) - before} failures") for run in args.run: before = len(failures) report = check_run(run) print(f"5. no-cheat (Legion run {run.name}): {len(failures) - before} failures; " f"{json.dumps(report)}") for failure in failures: print("FAIL:", failure) print("all checks passed" if not failures else f"{len(failures)} checks failed")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329"""One row per team from s³ runs (huggingface/legion#115): `uv run eval/metrics.pyRUN_DIR [RUN_DIR ...] [--out rows.jsonl]`.
A run directory is one team: a local run's bundle (`.legion/<swarm>-<time>/`, docs/local.md), ora Slurm run's directory (`legion init`'s RUN_DIR, docs/slurm.md), where the workers copy what arun 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;- `missing`: what the run directory lacks (an agent's reward, the board export) or where its spec and its Trials disagree, so a row never passes for complete when it is not.
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's span count. `EXTRAS` takes per-environment metrics (s3-maze:moves per agent and room overlap, from the move logs its verifier copies next to the reward)."""
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 reward(trials: list[Path]) -> float | None: """The reward of the agent's latest Trial that has one.""" for trial in reversed(trials): result = trial / "result.json" rewards = ((load_json(result).get("verifier_result") or {}).get("rewards") if result.is_file() else None) if rewards and "reward" in rewards: return float(rewards["reward"]) text = trial / "verifier" / "reward.txt" if text.is_file() and not text.is_symlink() and text.read_text().strip(): return float(text.read_text().strip()) 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
# Per-environment metrics: f(run_dir, team, Trial dirs by agent) -> extra row fields.# s3-maze adds moves per agent and room overlap, (V - U) / V, from its move logs here.EXTRAS: list[Callable[[Path, list[str], dict[str, list[Path]]], dict]] = []
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_values(path: Path) -> dict[str, str]: """NAME=value lines as Legion reads them (legion.specrender.read_env_file): an `export ` prefix and `#` comment lines allowed; a quoted value ends at its closing quote (what follows is a comment), and an unquoted one at whitespace followed by `#`. A line that isn't NAME=value is skipped, where Legion refuses the file.""" values = {} for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#"): continue name, sep, raw = line.removeprefix("export ").partition("=") name, value = name.strip(), raw.strip() if not sep or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name): continue if value and value[0] in "'\"" and (end := value.find(value[0], 1)) > 0: value = value[1:end] else: value = re.split(r"\s+#", raw, maxsplit=1)[0].strip() values[name] = value return values
def run_values(run_dir: Path) -> dict[str, str]: """The run's `cluster.env` then `run.env` (later wins), as Legion reads them: what fills the spec's `${VAR}`s.""" values = {} for name in ("cluster.env", "run.env"): if (run_dir / name).is_file(): values |= env_values(run_dir / name) 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: out |= extra(run_dir, team, trials) 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())4 unmodified lines56789108910111238 unmodified lines51525355545556574 unmodified lines- per problem and team size N in SIZES, a team `agg-pPP-nNN` that holds the problem's first N numbers, and one task per slot of it, `agg-pPP-nNN-sKK` (K = 1..N, zero-padded so that name order is slot order): its instruction states that slot's number, and only that one. Every slot of a team shares the grader and the answer. Legion runs a team with the selector `agg-pPP-nNN-s*`, `agents.count: N` and `naming: consecutive-id`: agent K gets slot K's task, and no other agent's. slot of a team shares the grader and the answer. A team runner assigns each participant its own slot's task.
check.py checks that this reproduces the committed files byte for byte."""38 unmodified lines
def task_name(problem: int, n: int, slot: int) -> str: """Slot `slot` (from 1) of the team: Legion's agent `agent-00K` (naming: consecutive-id).""" """Task for slot K of the team, with the first slot numbered 1.""" return f"{team_name(problem, n)}-s{slot:02d}"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172# s3-aggregation: N agents each hold a private number and list the team's numbers in ascending# order. The template of every team's spec: team.py fills in the team (TEAM) and this dataset's# revision (REVISION), and merges one of `where:` into it.# Don't launch this file; README.md.name: ${RUN_NAME:-TEAM} # team.py: the task's namemodel: Qwen/Qwen3.8-27Bnaming: consecutive-id # agent-00K runs slot K's task (the K-th by name)inference: hf_router: provider: deepinfra api_key_env: HF_INFERENCE_TOKEN # inference only: never the workers' HF_TOKENtask: repo: https://huggingface.co/datasets/HuggingFaceSwarms/s3-aggregation # private for now selector: TEAM-s* # one task per agent: agg-pPP-nNN-s01 ... revision: REVISION # team.py: --revision, default the Hub's headagents: count: 1 # team.py: Nresources: # The board rules: identical for every eval run, since they shape how agents talk. # Enforced on docker and podman (each agent's rule proxy); on HF Sandboxes there is no proxy, # so they are not enforced and each Trial records a message_board.warning event. message_board: channels: [general] wake: [mention, thread] rules: max_len: 1000 min_post_gap: 5s max_posts: 40 max_channels: 1 # #general only: no new channelsworkers: agents_per_worker: 1 # team.py: N, the whole team on one worker and board turn_timeout: 10mloop: prompt: Continue the task until it is complete, then stop. every: turn_end while: until: 15m max_rounds: 4limits: run_timeout_seconds: 1200 agent_max_turns: 60
# Where the team runs: team.py merges one of these into the spec (--where).where: # Local docker, with the controller, the one worker and the board on this machine. docker: environment: backend: docker # HF Sandboxes (cpu-basic), with the controller and the one worker on this machine and the # board on a Space. Give each team a new Space and delete it afterwards: the instruction has no # run tag, so an earlier team's posts on a reused board would read as this team's. sandbox: namespace: ${SANDBOX_NAMESPACE:-} # bills the sandboxes; unset: HF_TOKEN's account environment: backend: hf-sandbox resources: message_board: space_id: ${BOARD_SPACE:-s3-TEAM} # bare name: HF_TOKEN's account private: false # a private Space's gate needs HF_TOKEN in every sandbox # The HF cluster: a Slurm worker running the team in rootless podman, with a local board on # that worker (a new one each run). Results reach <run dir>/results/ (Legion's docs/slurm.md). 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: ${WORKER_CPUS:-16} mem: ${WORKER_MEM:-30G} # at most 2000 MB per CPU on hopper-cpu time: '3:00:00' environment: backend: podman1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# s3-aggregation scaling sweep
What the s³ paper's Figure 5 (information aggregation: success against swarm size) looks likewith Legion: every problem of this dataset at N = 1, 2, 4, 8 and 16 agents, each team its ownLegion run on the HF cluster. The results so far (`Qwen/Qwen3.5-27B` and `Qwen/Qwen3.5-2B`) arein huggingface/legion#120's comments and on Legion's `s3-aggregation-results` branch, and the rawruns in the private `HuggingFaceSwarms/s3-aggregation-results`.
| File | || --- | --- || `serve-vllm.sbatch` | the model server: vLLM with `$MODEL` (default `Qwen/Qwen3.5-27B`) on one B200 GPU (Legion's docs/open-models.md), thinking off for every request (the Qwen3.5 templates' defaults differ: the 27B's thinks, the 2B's doesn't) || `sweep.py` | runs the grid, one command, resumable: a row per team in `<root>/rows.jsonl` || `plot.py` | `scaling.png` (Figure 5's style), `teams.csv`, `by_n.csv` and `by_n.md` from the rows, one series per model || `setaside.py` | why each attempt in `rows-discarded.jsonl` didn't count, and how many teams needed a rerun || `failures.py` | per agent: the answer the verifier saw (no answer, malformed, wrong count, wrong numbers, right) and, from the state bucket's event streams, its tool calls, failed calls and posts || `waits.py` | how long each kept team's worker queued || `registries.conf` | the workers' podman pulls Docker Hub images through `mirror.gcr.io` |
## Run it
From Legion's checkout at or after `0401df9` (with its Slurm results, huggingface/legion#122, soeach Trial's grading reaches the run directory, and huggingface/legion#129, so the teams' agentsspread over the servers), with this dataset downloaded on the shared disk at the revisionthe teams pin (`DS` below), since the workers read `registries.conf` from it. Two model servers,one GPU each: one B200 is saturated by about 50 agents at a time (the 27B grid needs about 70Mprompt and 2M generated tokens), and a job's time limit is 3 hours.
```shhf download HuggingFaceSwarms/s3-aggregation --repo-type dataset --revision <sha> --local-dir $DSsbatch -p hopper-b200 -o .legion/s3-sweep/vllm-%j.log $DS/legion/sweep/serve-vllm.sbatchsbatch -p hopper-b200 --export=ALL,PORT=8001 -o .legion/s3-sweep/vllm-%j.log $DS/legion/sweep/serve-vllm.sbatch# each log ends with: serving Qwen/Qwen3.5-27B at http://<node address>:<port>/v1uv run python $DS/legion/sweep/sweep.py --urls http://<node 1>:8000/v1,http://<node 2>:8001/v1 \ --revision <sha> --parallel 12 --bucket <you>/s3-aggregation-grid \ --dataset HuggingFaceSwarms/s3-aggregation-results --prefix gridscancel -n s3-sweep-vllm```
The 2B grid is the same with `--export=ALL,MODEL=Qwen/Qwen3.5-2B` for the server, and`--model Qwen/Qwen3.5-2B --tag q2b-` and its own bucket and `--prefix` for the driver. Itsagents run far longer, so more teams are in flight at once: `--max-worker-cpus 8` keeps theirworkers small enough to be scheduled, except at N = 16, whose 2B teams need 16 CPUs (30 GB) andrun from a second driver (`--agents 16`) on the same root. Then plot both:`plot.py --series Qwen3.5-27B=<root> --series Qwen3.5-2B=<root> --out <dir>`.
Each team is team.py's cluster spec (`--where cluster`) with the model on all the servers' URLs(each agent calls one: Legion at or after `0401df9`, huggingface/legion#129, picks it from the runand the agent's name, so concurrent teams' agents spread over the servers; with an older Legionevery team's `agent-001` lands on the same server): `compute: slurm`, one worker on hopper-cpurunning the team in rootless podman with a local board, sized to the team (a CPU per agent, atleast 4). The board rules, loop and limits are the template's at every N. sweep.py inits andlaunches a team, waits until its loop is done and its agents are idle, releases it(`legion stop --release`: each Trial is graded as the worker drains, and the results land in therun directory), and appends metrics.py's row with the wall time. The run state goes to aprivate bucket (a new one per grid: a swarm's name is used once in a bucket), the rundirectories (spec, results, logs; never `run.env`) to the private dataset, and plot.py runs atthe end.
**A run counts only when it is complete**: one worker incarnation (until legion#121 is fixed, arelaunched or preempted worker overwrites results), its controller kept, every agent's rewardand the board export, and its worker started within 2 min of the launch (the loop's 15 minutesand the driver's 40 count from the launch, also for a team a restarted driver adopts). hopper-cpu is spot capacity, so reclaims take workers and controllersmid-run, and a missing reward means the verifier never ran. A run that doesn't count goes to`rows-discarded.jsonl` and the team runs again as `<task>-rK` (up to 5 times); its row recordsthe reruns.
**Resuming.** The same command resumes: a team with a row is skipped, a team a stopped driverlaunched is adopted (waited for, released and scored, or scored from what it left when itscontroller is gone), and one that never launched runs again. Stopping the driver to add a serveris safe: in-flight teams keep running and are adopted.
## How it differs from the paper's Figure 5
| | s³ (Figure 5, top row) | here || --- | --- | --- || Agents | Qwen3-0.6B trained with RL at N = 4, and its controls | `Qwen/Qwen3.5-27B` and `Qwen/Qwen3.5-2B`, not trained: one prompted condition each || Harness | their asynchronous harness: `message(to, text)` and `read_messages()`, notifications that interrupt generation, idle until a message arrives | Pi in a container per agent, with legion's board tools (`legion-tool message_board.*`) through its shell; a shared `#general` channel, mentions and a long-poll `wait`; legion's loop prompts again at each turn's end || Messages | to one teammate or broadcast | posts on `#general`, the only channel (`max_channels: 1`), which every agent reads || Private number | in the agent's prompt | in its own task's instruction (one task per slot) || Names | sampled from `agent_1`..`agent_64`, teammates in shuffled order | `agent-001`..`agent-00N`, in order || Budget | 8,192 work tokens + 1,024 for the answer per agent; reward reduced by tokens used | no token allowance: 60 model calls per prompt, 4 loop rounds, 15 min, 10 min per turn, 262,144-token window || Answer | `####` and a JSON array, from any agent active at the end | `/app/answer.json` per agent, graded after the run; the team succeeds if any agent's is right || Instruction | Appendix G's, with an example message and the token-cost rule | adapted from Appendix G for the board, with no example message and no token cost || Problems | 32 held-out problems x 6 seeds; N = 1, 2, 4, 6, 8, 12, 16 | 32 problems (our seed, the same recipe: 16 numbers in 1..99, the first N) x 1 attempt; N = 1, 2, 4, 8, 16 || Intervals | mean ± SE across six seeds | 95% Wilson intervals across problems || Right panel | token efficiency (needs the allowance) | four cost panels: input and generated tokens per team (as the paper's Figure 10), wall time per team and board posts per agent |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""How the teams of a grid fail: `uv run legion/sweep/failures.py <root>[--sessions <dir>]`, writing `<root>/failures.md` and `<root>/agents.csv`.
For each agent of each team in `<root>/rows.jsonl`: the answer the verifier saw (none, malformed,the wrong count, the wrong numbers, unsorted, or right), against the problem's numbers(this checkout's problems.json), and, from its event stream (`--sessions`:a copy of the state bucket, `<dir>/<run>/agent/<agent>/sessions/<agent>.jsonl`, e.g. from`hf buckets sync hf://buckets/<bucket> <dir> --include "*/sessions/agent-*.jsonl"`), what it did: board poststhrough `legion-tool`, tool calls that failed, and whether it ever reached `legion-tool` at all(a small model may call util-linux's `flock` instead). A team fails when no agent's answer isright; the summary counts the failed teams' agents by answer and behaviour."""
import argparseimport csvimport jsonimport refrom collections import Counterfrom pathlib import Path
PROBLEMS = Path(__file__).resolve().parents[2] / "problems.json"
def problems() -> dict[str, list[int]]: return json.loads(PROBLEMS.read_text())["problems"]
def answer_kind(text: str | None, team: list[int]) -> str: if text is None: return "no answer" try: answer = json.loads(text) except ValueError: return "malformed" if not isinstance(answer, list) or not all(type(x) is int for x in answer): return "malformed" if answer == sorted(team): return "right" if len(answer) != len(team): return "wrong count" if sorted(answer) == sorted(team): return "unsorted" return "wrong numbers"
def latest_answer(run_dir: Path, agent: str) -> str | None: trials = sorted(run_dir.rglob(f"{agent}/trials/*-{agent}-t*"), key=lambda p: int(re.search(r"-t(\d+)$", p.name)[1])) for trial in reversed(trials): path = trial / "verifier" / "answer.json" if path.is_file(): return path.read_text(errors="replace") if (trial / "verifier" / "reward.txt").is_file(): return None # graded, and no answer file return None
def behaviour(path: Path | None) -> dict: """What an agent did, from its event stream: tool calls, failed ones, board posts.""" out = {"tool_calls": 0, "tool_errors": 0, "posts": 0, "used_legion_tool": False, "called_util_flock": False, "session": path is not None and path.is_file()} if not out["session"]: return out calls = {} for line in path.read_text(errors="replace").splitlines(): event = json.loads(line) message = event.get("message") or {} if event.get("type") != "message": continue if message.get("role") == "assistant": for part in message.get("content") or []: if isinstance(part, dict) and part.get("type") == "toolCall": out["tool_calls"] += 1 command = json.dumps(part.get("arguments") or {}) calls[part.get("id")] = command out["used_legion_tool"] |= "legion-tool" in command out["called_util_flock"] |= bool(re.search(r"(^|[^-\w])flock (?!-tool)", command.replace("\\\\n", " "))) elif message.get("role") == "toolResult": text = " ".join(p.get("text", "") for p in message.get("content") or [] if isinstance(p, dict)) failed = message.get("isError") or '"error"' in text out["tool_errors"] += bool(failed) command = calls.get(message.get("toolCallId"), "") if "message_board.post" in command and not failed: out["posts"] += 1 return out
def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("root", type=Path) parser.add_argument("--sessions", type=Path, help="a copy of the state bucket") args = parser.parse_args(argv) numbers = problems() rows = [json.loads(x) for x in (args.root / "rows.jsonl").read_text().splitlines()] agents = [] for r in rows: team = numbers[f"p{r['problem']:02d}"][:r["agents"]] run_dir = args.root / "runs" / r["run"] for name in sorted(r["rewards"]): session = (args.sessions / r["run"] / "agent" / name / "sessions" / f"{name}.jsonl" if args.sessions else None) agents.append({"run": r["run"], "task": r["task"], "agents": r["agents"], "team_success": bool(r["success"]), "agent": name, "reward": r["rewards"][name], "answer": answer_kind(latest_answer(run_dir, name), team), **behaviour(session)}) with (args.root / "agents.csv").open("w", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(agents[0])) writer.writeheader() writer.writerows(agents) failed = [a for a in agents if not a["team_success"]] by_n = Counter(r["agents"] for r in rows if not r["success"]) per_n = ", ".join(f"N={n}: {c}" for n, c in sorted(by_n.items())) lines = [f"Teams: {len(rows)}, failed: {sum(by_n.values())} ({per_n})", "", "Agents of failed teams, by the answer the verifier saw:", ""] lines += [f"- {k}: {c}" for k, c in Counter(a["answer"] for a in failed).most_common()] seen = [a for a in failed if a["session"]] if seen: errors, calls = sum(a["tool_errors"] for a in seen), sum(a["tool_calls"] for a in seen) erring = sum(a["tool_errors"] > 0 for a in seen) lines += ["", f"Their behaviour ({len(seen)} with an event stream):", "", f"- never posted on the board: {sum(a['posts'] == 0 for a in seen)}", f"- never reached legion-tool: {sum(not a['used_legion_tool'] for a in seen)}", f"- called util-linux `flock` instead: {sum(a['called_util_flock'] for a in seen)}", f"- had failed tool calls: {erring} ({errors} of {calls} calls)"] (args.root / "failures.md").write_text("\n".join(lines) + "\n") print("\n".join(lines)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224# /// script# requires-python = ">=3.12"# dependencies = ["matplotlib>=3.8"]# ///"""The sweep's figure, CSVs and table from sweep.py's rows (`<root>/rows.jsonl`, one per team):
uv run legion/sweep/plot.py <root> # one grid, into <root> uv run legion/sweep/plot.py --series Qwen3.5-27B=<root> \ --series Qwen3.5-2B=<root> --out <dir> # one series per model
- `scaling.png`, five panels against the swarm size N: success (%) in the style of the s³ paper's Figure 5 (information aggregation), with 95% Wilson intervals over the problems; then what the team costs: input and generated tokens per team and board posts per agent (means with 95% intervals), and wall time per team (median and interquartile range: a team in flight across a driver restart waited for it). The paper's right panel is token efficiency, which needs a token allowance our agents don't have; its Figure 10 shows tokens per team;- `teams.csv`: one row per team; `by_n.csv` and `by_n.md`: per N, the teams, success rate and interval, mean reward, tokens per team (input, cached when the server reports it, output), board posts per agent and the median wall time."""
import argparseimport csvimport jsonimport mathimport statisticsimport sysfrom pathlib import Path
SURFACE, INK, INK_2, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#e4e3df"SERIES = ["#2a78d6", "#eb6834", "#1baf7a"] # the reference palette's first slots, in order
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 team_row(r: dict) -> dict: rewards = [v for v in r["rewards"].values() if v is not None] t = r["tokens"] return {"task": r["task"], "problem": r.get("problem"), "agents": r["agents"], "success": int(bool(r["success"])), "mean_reward": statistics.fmean(rewards) if rewards else None, "input_uncached": t["input"], "cached": t["cache_read"], "output": t["output"], "posts": r["posts"], "posts_per_agent": r["posts"] / r["agents"], "wall_s": r.get("wall_s"), "duration_s": r["duration_s"], "outcome": r.get("outcome"), "reruns": r.get("reruns", 0), "incarnations": r.get("incarnations"), "missing": ";".join(r["missing"])}
def by_n(teams: list[dict]) -> list[dict]: out = [] for n in sorted({t["agents"] for t in teams}): group = [t for t in teams if t["agents"] == n] k = sum(t["success"] for t in group) low, high = wilson(k, len(group)) rewards = [t["mean_reward"] for t in group if t["mean_reward"] is not None] out.append({ "agents": n, "teams": len(group), "successes": k, "success_rate": k / len(group), "ci_low": low, "ci_high": high, "mean_reward": statistics.fmean(rewards) if rewards else math.nan, "input_uncached_per_team": statistics.fmean(t["input_uncached"] for t in group), "cached_per_team": statistics.fmean(t["cached"] for t in group), "output_per_team": statistics.fmean(t["output"] for t in group), "posts_per_agent": statistics.fmean(t["posts_per_agent"] for t in group), "wall_s": statistics.median(t["wall_s"] for t in group if t["wall_s"] is not None), "incomplete": sum(bool(t["missing"]) for t in group), "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])) writer.writeheader() writer.writerows(rows)
def table(series: list[tuple[str, list[dict], list[dict]]]) -> str: # a server that reports no cache hits (vLLM by default) gets no cached column cached = any(s["cached_per_team"] for _, _, summary in series for s in summary) tokens = "input / cached / output" if cached else "input / output" head = (f"| model | N | teams | success | 95% CI | mean reward | {tokens} tokens per team " "| posts per agent | median wall time |") lines = [head, "|---|---|---|---|---|---|---|---|---|"] for model, _, summary in series: lines += [row(model, s, cached) for s in summary] return "\n".join(lines) + "\n"
def row(model: str, s: dict, cached: bool) -> str: tokens = (f"{s['input_uncached_per_team'] / 1e3:.0f}k / " + (f"{s['cached_per_team'] / 1e3:.0f}k / " if cached else "") + f"{s['output_per_team'] / 1e3:.1f}k") return (f"| {model} | {s['agents']} | {s['teams']} | {s['successes']}/{s['teams']} " f"({100 * s['success_rate']:.0f}%) | {100 * s['ci_low']:.0f}-{100 * s['ci_high']:.0f}% " f"| {s['mean_reward']:.2f} | {tokens} | {s['posts_per_agent']:.1f} " f"| {s['wall_s'] / 60:.1f} min |")
def quartiles(values: list[float]) -> tuple[float, float, float]: q = statistics.quantiles(values, n=4) if len(values) > 1 else [values[0]] * 3 return (statistics.median(values), q[0], q[2])
def panels(teams: list[dict], summary: list[dict]) -> list[tuple]: """(label, [(middle, low, high) per N], y limits or "log") for each panel: tokens on a log scale, since two models' teams can differ by more than an order of magnitude.""" ns = [s["agents"] for s in summary] by_n = {n: [t for t in teams if t["agents"] == n] for n in ns} return [ ("Success (%)", [(100 * s["success_rate"], 100 * s["ci_low"], 100 * s["ci_high"]) for s in summary], (0, 105)), ("Input tokens per team", [mean_ci([t["input_uncached"] + t["cached"] for t in by_n[n]]) for n in ns], "log"), ("Generated tokens per team", [mean_ci([t["output"] for t in by_n[n]]) for n in ns], "log"), ("Wall time per team (min)", [tuple(v / 60 for v in quartiles([t["wall_s"] for t in by_n[n] if t["wall_s"]])) for n in ns], None), ("Board posts per agent", [mean_ci([t["posts_per_agent"] for t in by_n[n]]) for n in ns], None), ]
def tokens(value: float, _=None) -> str: """A log axis tick as a token count: 100, 10k, 1M.""" 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: list[tuple[str, list[dict], list[dict]]], title: str) -> None: import matplotlib
matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter
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, axes = plt.subplots(1, 5, figsize=(17, 3.9), facecolor=SURFACE) for k, (model, teams, summary) in enumerate(series): ns = [s["agents"] for s in summary] offset = (k - (len(series) - 1) / 2) * 0.18 # side by side, so the bars don't hide for ax, (label, points, scale) in zip(axes, panels(teams, summary), strict=True): ax.errorbar([n + offset for n in ns], [p[0] for p in points], yerr=[[max(0.0, p[0] - p[1]) for p in points], # Wilson at 0/n: 1e-15 [max(0.0, p[2] - p[0]) for p in points]], color=SERIES[k], linewidth=2, marker="o", markersize=7, capsize=3, elinewidth=1.5, label=model) ax.set_ylabel(label) ax.set_xticks(ns) for ax, (_, _, scale) in zip(axes, panels(*series[0][1:]), strict=True): # every series in if scale == "log": ax.set_yscale("log") ax.yaxis.set_major_formatter(FuncFormatter(tokens)) elif scale: ax.set_ylim(*scale) else: ax.set_ylim(bottom=0) for ax in axes: 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("Swarm size N") if len(series) > 1: axes[0].legend(frameon=False, loc="center right", fontsize=9) fig.suptitle(title, fontsize=11, color=INK, x=0.01, ha="left") fig.text(0.01, 0.01, "One attempt per problem. Success: share of teams with any agent right, " "95% Wilson intervals. Tokens (log scale) and posts: means, 95% intervals. Wall time (init " "to release): median and interquartile range.", fontsize=8, color=INK_2) fig.tight_layout(rect=(0, 0.05, 1, 0.94)) 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["problem"])) return teams, by_n(teams)
def main(argv=None) -> int: parser = argparse.ArgumentParser(description="The sweep's figure, CSVs and table.") parser.add_argument("root", nargs="?", type=Path, help="one grid; outputs go there too") parser.add_argument("--series", action="append", default=[], help="MODEL=ROOT, repeatable") parser.add_argument("--out", type=Path, help="where --series outputs go") args = parser.parse_args(argv) if args.root: # the grid's model, from one of its team specs spec = next(args.root.glob("src/*/spec.yaml"), None) model = next((x.split(": ", 1)[1].strip() for x in spec.read_text().splitlines() if x.startswith("model: ")), args.root.name) if spec else args.root.name sources, out = [(model.split("/")[-1], args.root)], args.root else: sources = [(s.split("=", 1)[0], Path(s.split("=", 1)[1])) for s in args.series] out = args.out out.mkdir(parents=True, exist_ok=True) series = [(model, *load(root)) for model, root in sources] write_csv(out / "teams.csv", [{"model": m} | t for m, teams, _ in series for t in teams]) write_csv(out / "by_n.csv", [{"model": m} | s for m, _, summary in series for s in summary]) (out / "by_n.md").write_text(table(series)) figure(out / "scaling.png", series, "s3-aggregation with legion: success and cost against " f"swarm size ({', '.join(m for m, _, _ in series)})") print(table(series)) return 0
if __name__ == "__main__": sys.exit(main())12345678910111213# podman's registries for the sweep's workers (CONTAINERS_REGISTRIES_CONF in their profile):# Docker Hub images through Google's pull-through mirror first, since each worker job pulls the# task 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"1234567891011121314151617181920212223242526272829#!/bin/bash# The sweep's model server: one vLLM on one GPU (docs/open-models.md "On the HF cluster"), in# Pyxis on hopper-b200. The agents (podman on hopper-cpu) reach it by this node's address.# sbatch -p hopper-b200 -o <dir>/vllm-%j.log legion/sweep/serve-vllm.sbatch# Its log ends with: serving <model> at http://<node address>:8000/v1#SBATCH --job-name=s3-sweep-vllm#SBATCH --gpus=1#SBATCH --cpus-per-task=16#SBATCH --mem=96G#SBATCH --time=3: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 disk# Thinking off for every request: s3 runs compare models without thinking, and the Qwen3.5 chat# templates' defaults differ (the 27B's thinks, the 2B's doesn't), so the server sets it.srun --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"wait1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Why each set-aside attempt of a grid didn't count: `uv run legion/sweep/setaside.py<root>`, from `<root>/rows-discarded.jsonl` and the attempt's own logs. A restarteddriver scores an attempt again from what it left, so one attempt can have several entries: itsreason uses them all. Writes `<root>/setaside.md`; the reasons, first that applies:
- the worker was relaunched (more than one incarnation: legion#121's case) after it ran out of memory (the worker's memory ladder rotated or preempted it), or else after a node failure;- the worker ran out of memory and was preempted or killed without a relaunch;- the worker started more than 2 min after the launch (the loop's 15 minutes count from it);- the controller's node was reclaimed (spot) mid-run;- the task image couldn't be pulled (Docker Hub's unauthenticated limit), so the Trials never started;- the verifier timed out (Harbor's 60 s) on a loaded worker;- an agent's Trial failed before its verifier ran (e.g. legion's idle probe of the container);- the run was cancelled before its Trials were graded (the driver stopped and its in-flight teams cancelled, e.g. to switch the workers to the image mirror)."""
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-")) if (row.get("incarnations") or 0) > 1: 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("worker_wait_s") or 0) > 120: # sweep.py's WAIT_LIMIT return "worker queued past 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 "toomanyrequests" in workers: return "task image not pulled (Docker Hub limit): Trials never started" if re.search(r"preempted \(memory\)|oom_kill", workers): return "worker ran out of memory (preempted or killed, not relaunched)" if any("VerifierTimeoutError" in p.read_text(errors="replace") for p in run_dir.glob("results/*/agent-*/trials/*/result.json")): return "verifier timed out (60 s) on a loaded worker" failed = [(json.loads(p.read_text()).get("exception_info") or {}).get("exception_type") for p in run_dir.glob("results/*/agent-*/trials/*/result.json")] if kinds := sorted({k for k in failed if k and k != "CancelledError"}): # cancelled: below return f"an agent's Trial failed before its verifier ran ({', '.join(kinds)})" return "cancelled before grading (driver stopped, in-flight teams cancelled)"
def main(root: Path) -> int: attempts = {} for line in (root / "rows-discarded.jsonl").read_text().splitlines(): 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) if row.get("outcome") == "controller lost": seen["outcome"] = row["outcome"] kept = [json.loads(x) for x in (root / "rows.jsonl").read_text().splitlines()] reasons = Counter(reason(r, root / "runs" / run) for run, r in attempts.items()) rerun = sum(r.get("reruns", 0) > 0 for r in kept) head = (f"Attempts set aside: {len(attempts)} (rows-discarded.jsonl); " f"teams that needed a rerun: {rerun} of {len(kept)}") lines = [head, ""] lines += [f"- {why}: {k}" for why, k in reasons.most_common()] (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])))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341"""The s3-aggregation scaling sweep on the HF cluster, one command for the whole grid, run fromLegion'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 \\ [--problems 1-32] [--agents 1,2,4,8,16] [--parallel 8] [--root .legion/s3-sweep] \\ [--bucket lewtun/s3-aggregation-sweep] [--dataset HuggingFaceSwarms/s3-aggregation-results]
Each (problem, N) team is its own legion run (`compute: slurm`, podman agents on hopper-cpu, alocal board on its one worker), from team.py's cluster spec with the sweep's model on `urls`(the same board rules, loop and limits at every N). Every team lists every server: Legion at orafter 0401df9 (legion#129) picks each agent's server from its run and its name, so concurrentteams' agents spread over the servers. Per team: `legion init` (a worker sized toN), `legion launch`, wait until its loop is done and its agents are idle, `legion stop --release`(each Trial is graded as the worker drains; the results land in the run directory), theneval/metrics.py's row plus the wall time goes to `<root>/rows.jsonl`. Until legion#121is fixed, a team must run on one worker incarnation (a relaunch or a preemption overwritesresults); and a spot reclaim may take its controller, or leave rewards unverified. A run thatdoesn't count (why_invalid) runs again as `<task>-rK` (its row: `reruns`). A team thathas a row is skipped, so the same command resumes. At the end plot.py writes the figure, CSVand table, and with --dataset each run directory (spec, results, logs; never run.env) goes tothat private dataset under `<prefix>/<task>/`.
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 server takes no key."""
import argparseimport importlib.utilimport jsonimport osimport reimport shutilimport subprocessimport sysimport threadingimport timefrom concurrent.futures import ThreadPoolExecutorfrom datetime import UTC, datetimefrom pathlib import Path
import yamlfrom huggingface_hub import HfApi, get_token
HERE = Path(__file__).resolve().parentREPO = Path.cwd() # Legion's checkoutMODEL = "Qwen/Qwen3.5-27B"SECRET = re.compile(r"hf_[A-Za-z0-9]{30,}")lock, init_lock = threading.Lock(), threading.Semaphore(4)LOST, GONE = "controller lost", "no controller left"# the loop's `until` (and the driver's team timeout) count from the launch, not from the worker's# start: a run whose worker queued longer than this (a busy or scaling partition) doesn't countWAIT_LIMIT = 120 # s
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", HERE.parents[1] / "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)
def write_experiment(src: Path, problem: 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, as swarm `name`.""" team.main(["--problem", str(problem), "--agents", str(n), "--where", "cluster", "--revision", revision, "--out", str(src)]) 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 (src / "spec.yaml").write_text( f"# {spec['task']['selector']} for the scaling sweep (sweep.py): team.py's cluster spec " f"with {model} on the sweep's servers.\n" + yaml.safe_dump(spec, sort_keys=False))
def profile(root: Path, n: int, most: int = 16) -> Path: """A worker sized to the team: a CPU per agent (at least 4), 1900 MB per CPU (hopper-cpu allows 2000); its podman pulls Docker Hub images through a mirror (registries.conf).""" cpus = max(4, min(n, most)) # `most`: a big job can queue past the loop's until path = root / "profiles" / f"n{n:02d}.env" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(f"SLURM_PARTITION=hopper-cpu\nWORKER_CPUS={cpus}\nWORKER_MEM={cpus * 1900}M\n" f"SLURM_MAX_MEM_PER_CPU_MB=2000\nVENV={REPO / '.venv'}\n" f"CONTAINERS_REGISTRIES_CONF={HERE / 'registries.conf'}\n") return path
def controller_state(name: str) -> str: """The Slurm state of the run's controller job (`legion-ctl-<run>`), '' when it has none.""" out = subprocess.run(["squeue", "-h", "-n", f"legion-ctl-{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 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 = time.monotonic() + timeout, 0 while time.monotonic() < deadline: status = legion(run_dir, "status", task, timeout=120) text = status.stdout unanswered = unanswered + 1 if status.returncode != 0 else 0 if unanswered >= 3 and controller_state(task) != "RUNNING": return LOST if re.search(r"crashloop|launch_refused", text): return "worker failed: " + " ".join(text.split())[:300] if re.search(r"^loop agent: done", text, re.MULTILINE) and re.search( rf"^agent .*\bidle:{n}\b", text, re.MULTILINE): return "done" time.sleep(20) return f"not done after {timeout:.0f} s"
def attempt(args, root: Path, secrets: Path, problem: int, n: int, name: str) -> dict | None: """One run of a team as swarm `name`: 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, or, # with its controller gone (released, cancelled or reclaimed), score what it left alive = bool(controller_state(name)) say(name, "adopting the run a previous driver launched" + ("" if alive else " (no controller left)")) return finish(args, run_dir, name, problem, 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() write_experiment(src, problem, n, name, args.urls, args.model, args.revision) log = root / "logs" / f"{name}-init.log" log.parent.mkdir(parents=True, exist_ok=True) for tries in range(3): 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, n, args.max_worker_cpus)), "--secrets", str(secrets)) log.write_text(init.stdout + init.stderr) if init.returncode == 0: break time.sleep(10 * (tries + 1)) else: failed = [x for x in init.stdout.splitlines() if x.startswith("FAIL")] say(name, "init failed 3 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, problem, n, started, "launch") return finish(args, run_dir, name, problem, n, started)
def finish(args, run_dir: Path, name: str, problem: int, n: int, started: float, why: str | None = None) -> dict: """Wait for a launched team, release it (its Trials are graded) and make its row.""" # the team's limit counts from its own start, also when a restarted driver adopts it 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) release = subprocess.CompletedProcess([], 1) elif why == GONE: # its rewards and export are on disk, or it doesn't count release = subprocess.CompletedProcess([], 1) else: say(name, "loop:", why, "- releasing") release = legion(run_dir, "stop", name, "--release") ended = time.time() return metrics.row(run_dir) | { "problem": problem, "wall_s": round(ended - started, 1), "outcome": why, "released": release.returncode == 0, # 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), "started_at": datetime.fromtimestamp(started, UTC).isoformat()}
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: started = datetime.fromisoformat(first.split(" ", 1)[0]) except ValueError: return None return round(started.timestamp() - launches[0].stat().st_mtime, 1)
def why_invalid(row: dict) -> str: """Why a team's run doesn't count ('' when it does): a model result needs the run on one worker incarnation (legion#121), its controller kept, every agent's reward and the board export. A missing reward means the verifier never ran: the infrastructure failed, not the team. And its worker started within WAIT_LIMIT of the launch, so the loop's 15 minutes were the team's.""" wait = row.get("worker_wait_s") or 0 return "; ".join(why for why, bad in ( (f"{row.get('incarnations')} worker incarnations", row.get("incarnations") != 1), (f"worker started {wait:.0f} s after the launch", wait > WAIT_LIMIT), (LOST, row.get("outcome") == LOST), (f"missing {', '.join(row['missing'])}"[:120], bool(row["missing"]))) if bad)
def valid(row: dict) -> bool: return not why_invalid(row)
def run_team(args, root: Path, secrets: Path, problem: int, n: int) -> dict | None: """A team, run again (as `<task>-rK`) until it runs on one worker incarnation (legion#121).""" task = f"{args.tag}agg-p{problem:02d}-n{n:02d}" for reruns in range(args.max_reruns + 1): row = attempt(args, root, secrets, problem, n, task if reruns == 0 else f"{task}-r{reruns}") 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") with lock, (root / "rows-discarded.jsonl").open("a") as f: f.write(json.dumps(row) + "\n") with lock, (root / "rows.jsonl").open("a") as f: f.write(json.dumps(row) + "\n") say(task, f"success={row['success']} rewards={list(row['rewards'].values())} " f"posts={row['posts']} wall={row['wall_s']} s reruns={row['reruns']} " f"incarnations={row['incarnations']} missing={row['missing']}") return row
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/**"] leaks = [str(p) for p in (root / "runs").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-aggregation 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", default=MODEL) parser.add_argument("--revision", help="the dataset revision every team pins (default: its " "head; this checkout's resources/ must be that revision's)") parser.add_argument("--problems", default="1-32") parser.add_argument("--agents", default="1,2,4,8,16") parser.add_argument("--parallel", type=int, default=8, help="teams at once") parser.add_argument("--team-timeout", type=float, default=2400, help="s until a release") parser.add_argument("--max-reruns", type=int, default=5, help="runs again of a team whose run doesn't count (why_invalid)") parser.add_argument("--root", type=Path, default=REPO / ".legion" / "s3-sweep") parser.add_argument("--bucket", default="lewtun/s3-aggregation-sweep", help="private bucket for the runs' state (a new one per root: 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", default="grid", help="folder in the dataset") parser.add_argument("--max-worker-cpus", type=int, default=16, help="cap a team's worker (a busy partition can hold a 16-CPU job past " "the loop's 15 minutes: its run then doesn't count)") parser.add_argument("--tag", default="", help="put before every run and swarm name (e.g. q2b-): two grids at once " "then never share a Slurm job name") args = parser.parse_args(argv) 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: two may share a root 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 [] 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) + "\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["problem"], r["agents"]) for r in rows if valid(r)} teams = [(p, n) for p in numbers(args.problems) for n in numbers(args.agents) if (p, n) not in done] say(f"{len(teams)} teams to run ({len(done)} done), {args.parallel} at once, on {args.urls}") try: with ThreadPoolExecutor(args.parallel) as pool: list(pool.map(lambda t: run_team(args, root, secrets, *t), teams)) finally: secrets.unlink(missing_ok=True) subprocess.run(["uv", "run", str(HERE / "plot.py"), str(root)], check=False) # matplotlib if args.dataset: upload(root, args.dataset, args.prefix) return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738394041"""How long each kept team's worker waited in the Slurm queue: `uv run legion/sweep/waits.py<root>`. The loop's `until` counts from the launch, so a worker that starts lateleaves its agents less of the 15 minutes; a run whose loop ran out before its worker started hasno rewards and was run again (sweep.py). The wait is from the controller writing the worker'slaunch file to the worker job's first log line."""
import jsonimport statisticsimport sysfrom datetime import datetimefrom pathlib import Path
def wait_s(run_dir: Path) -> float | None: 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: started = datetime.fromisoformat(first.split(" ", 1)[0]) except ValueError: return None return started.timestamp() - launches[0].stat().st_mtime
def main(root: Path) -> int: rows = [json.loads(x) for x in (root / "rows.jsonl").read_text().splitlines()] waits = [(r, wait_s(root / "runs" / r["run"])) for r in rows] known = [(r, w) for r, w in waits if w is not None] long = [(r, w) for r, w in known if w > 300] print(f"teams: {len(rows)}, worker wait known for {len(known)}: median " f"{statistics.median(w for _, w in known):.0f} s, max {max(w for _, w in known):.0f} s; " f"over 5 min: {len(long)} (succeeded: {sum(bool(r['success']) for r, _ in long)}; " f"by N: {sorted(r['agents'] for r, _ in long)})") return 0
if __name__ == "__main__": raise SystemExit(main(Path(sys.argv[1])))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Write the Legion spec for one s3-aggregation team, from Legion's checkout (it needs Legion):
uv run python <this dataset>/legion/team.py --problem 7 --agents 4 [--where docker|sandbox|cluster]
writes `out/agg-p07-n04/spec.yaml` next to this script (or `--out DIR`) from spec.template.yaml:the team `agg-p07-n04` at `--revision` (default: the dataset's head on the Hub), its 4 agents(agent-001 .. agent-004, one worker and board) on the selector `agg-p07-n04-s*`, so that agent Kruns slot K's task, the one that states its number. `--where` picks the template's `where:`block: local docker, HF Sandboxes with a Space board, or the HF cluster with a local board. Thedataset is private for now: HF_TOKEN must read it."""
import argparseimport copyimport sysfrom pathlib import Path
import yamlfrom huggingface_hub import HfApi
from legion.models import load_spec_yaml
HERE = Path(__file__).resolve().parentDATASET = "HuggingFaceSwarms/s3-aggregation"PROBLEMS, SIZES = range(1, 33), (1, 2, 4, 8, 16)
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 team_spec(template: dict, problem: int, agents: int, where: str, revision: str) -> tuple[str, dict]: """(the task's name, the team's spec) from the template.""" template = copy.deepcopy(template) places = template.pop("where") task = f"agg-p{problem:02d}-n{agents:02d}" spec = fill(merge(template, places[where]), {"TEAM": task, "REVISION": revision}) spec["agents"] = {"count": agents} spec["workers"]["agents_per_worker"] = agents return task, 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-aggregation team's Legion spec.") parser.add_argument("--problem", type=int, required=True, choices=PROBLEMS) parser.add_argument("--agents", type=int, required=True, choices=SIZES) parser.add_argument("--where", choices=("docker", "sandbox", "cluster"), default="sandbox") parser.add_argument("--revision", help="the dataset revision to pin (default: its head)") parser.add_argument("--out", type=Path, help="default: out/<task> next to this script") args = parser.parse_args(argv) template = load_spec_yaml((HERE / "spec.template.yaml").read_text()) task, spec = team_spec(template, args.problem, args.agents, args.where, pinned(args.revision)) out = args.out or HERE / "out" / task out.mkdir(parents=True, exist_ok=True) header = (f"# {task} ({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())README.md+17-143
check.py+3-333
eval/metrics.pyDeleted-329
generate.py+3-4
legion/spec.template.yamlDeleted-72
legion/sweep/README.mdDeleted-86
legion/sweep/failures.pyDeleted-134
legion/sweep/plot.pyDeleted-224
legion/sweep/registries.confDeleted-13
legion/sweep/serve-vllm.sbatchDeleted-29
legion/sweep/setaside.pyDeleted-74
legion/sweep/sweep.pyDeleted-341
legion/sweep/waits.pyDeleted-41
legion/team.pyDeleted-85