Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
s3-maze / generate.py
Agent Manager
Rename flock integration to legion
3421ea2
Raw History Blame Contribute Delete
9.67 kB
"""Regenerate s3-maze from its seed: `python generate.py` (Python 3.10+, no dependencies).
Writes `tasks/` next to this file, replacing what is there: 32 trees from SEED, one task each
(`maze-t01` .. `maze-t32`), built as in s3 (arXiv 2611.08615): from the start room, corridors
of CORRIDOR rooms lead to junctions with BRANCHING onward doors, DEPTH levels deep. That is 391
rooms and 27 dead ends at the far ends of the deepest corridors, one of them the exit, chosen
uniformly; the shortest path is 30 moves and a full depth-first search 780. Room labels are
random numbers with a fixed number of digits (`R4821`), and each room's door order is shuffled
once, here, the same for every agent and every visit.
Each task is a compose stack (environment/): the agent's container (`main`, with the `maze`
command) and its own maze service, which alone holds the tree (environment/maze/tree.json). The
service's files, the agent's and the grader's are template/'s, copied as they are; the tree,
the grader's expected.json, the oracle's path, the instruction and the image tags are per tree.
check.py checks that this reproduces the committed files byte for byte.
"""
import hashlib
import json
import random
import shutil
from pathlib import Path
SEED = 115 # huggingface/legion#115
TREES = 32 # the paper's held-out set size
BRANCHING, CORRIDOR, DEPTH = 3, 10, 3
DIGITS = 4 # room labels R1000 .. R9999
BUDGET = 210 # moves per agent: budget.py's table, README.md "The move budget"
ROOMS = 1 + CORRIDOR * sum(BRANCHING ** k for k in range(1, DEPTH + 1)) # 391
HERE = Path(__file__).resolve().parent
TEMPLATE = HERE / "template"
def task_name(tree: int) -> str:
"""`tree` counts from 1."""
return f"maze-t{tree:02d}"
def tree(rng: random.Random, budget: int = BUDGET) -> dict:
"""One tree: `{"start", "exit", "budget", "doors": {room: [door, ...]}}`, built level by
level from the start room (room 0)."""
labels = [f"R{n}" for n in rng.sample(range(10 ** (DIGITS - 1), 10 ** DIGITS), ROOMS)]
doors: list[list[int]] = [[] for _ in range(ROOMS)]
frontier, made = [0], 1
for _ in range(DEPTH):
reached = []
for junction in frontier:
for _ in range(BRANCHING):
previous = junction
for _ in range(CORRIDOR):
doors[previous].append(made)
doors[made].append(previous)
previous, made = made, made + 1
reached.append(previous)
frontier = reached
exit_room = rng.choice(frontier) # one of the dead ends, uniformly
for room in doors:
rng.shuffle(room)
return {"start": labels[0], "exit": labels[exit_room], "budget": budget,
"doors": {labels[i]: [labels[j] for j in doors[i]] for i in range(ROOMS)}}
def trees(seed: int = SEED, budget: int = BUDGET) -> list[dict]:
rng = random.Random(seed)
return [tree(rng, budget) for _ in range(TREES)]
def shortest_path(t: dict) -> list[str]:
"""The rooms from the start to the exit, the start excluded."""
parent, queue = {t["start"]: None}, [t["start"]]
for room in queue:
for door in t["doors"][room]:
if door not in parent:
parent[door] = room
queue.append(door)
path, room = [], t["exit"]
while room != t["start"]:
path.append(room)
room = parent[room]
return path[::-1]
def instruction(budget: int) -> str:
return f"""# Find the exit of the maze
You are exploring a maze of rooms connected by doors to find the exit. The maze is a tree: from
the start room, corridors of rooms lead to junctions where the way divides, and the exit is one
of the dead ends at the far ends of the corridors. Every agent on your team starts in the same
room, in its own copy of the same maze: the same rooms, with the same doors listed in the same
order. Your position is your own: moving never moves a teammate.
Explore with the `maze` command in your shell:
- `maze look` describes your current room again, without moving;
- `maze move ROOM` walks through a door of your current room into the named adjacent room.
Each prints JSON: the room you are in (`room`), its doors (`doors`), whether it is the exit
(`exit`), the room you arrived from (`arrived_from`) and how many moves you have left
(`moves_left`), with a `notice` at a dead end. Only the doors listed for your current room are
reachable in one move; to go back, move to the room you arrived from. Room names carry no
information about where the exit is.
You can make at most {budget} moves. Looking is free, and a refused move (into a room that is not
one of your doors) costs nothing.
Reaching the exit solves the task for the whole team and ends the run. If you have teammates
(your instructions name them), they are searching the same maze: what one of you learns about it
holds for everyone. Use the message board to share what you find and to read what they find.
Once you reach the exit, post that you have, then stop.
"""
def task_toml(t: int, budget: int, seed: int) -> str:
return f"""schema_version = "1.4"
# The maze service's own record of the walk, exported by its collect hook below once the agent
# is done: the grader's only input besides tests/expected.json.
[[artifacts]]
source = "/evidence/final.json"
service = "maze"
[[artifacts]]
source = "/evidence/moves.jsonl"
service = "maze"
[task]
name = "HuggingFaceSwarms/{task_name(t)}"
version = "0.1.0"
description = "s3-maze: agents search their own copies of one maze; the first one out wins."
keywords = ["multi-agent", "message-board", "s3", "maze", "exploration"]
[metadata]
tree = {t}
seed = {seed}
branching = {BRANCHING}
corridor = {CORRIDOR}
depth = {DEPTH}
rooms = {ROOMS}
dead_ends = {BRANCHING ** DEPTH}
shortest_path = {CORRIDOR * DEPTH}
full_search = {2 * (ROOMS - 1)}
move_budget = {budget}
[agent]
timeout_sec = 3600
[environment]
build_timeout_sec = 900
cpus = 1
memory_mb = 1024
[verifier]
# The grader runs in its own container (tests/Dockerfile) after the agent's has stopped, on
# what the maze service exported: nothing the agent's container holds reaches it.
environment_mode = "separate"
timeout_sec = 120
[[verifier.collect]]
service = "maze"
command = "python3 -I -S /app/export.py"
timeout_sec = 30
"""
def compose(task: str, agent_tag: str, maze_tag: str) -> str:
return f"""# {task}: the agent's container (main) and its own maze service. The service holds
# the tree and answers only `maze look` and `maze move ROOM`, on a network only main reaches.
services:
main:
image: s3-maze-agent:{agent_tag}
build:
context: ./agent
networks: [default, maze]
security_opt: [no-new-privileges:true]
depends_on: [maze]
maze:
image: s3-maze-service:{task}-{maze_tag}
build:
context: ./maze
networks: [maze]
environment:
MAZE_AGENT: ${{COMPOSE_PROJECT_NAME:-}} # the Trial, for the move log
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
pids_limit: 64
mem_limit: 256m
networks:
default: {{}} # main's way out (Flock replaces it with the agent's own network)
maze:
internal: true
"""
def solve_sh(path: list[str]) -> str:
rooms = " ".join(path)
return f"""#!/bin/bash
# Oracle: walk the shortest path to the exit with `maze move`, from its own copy of the path.
set -e
for room in {rooms}; do
maze move "$room" > /dev/null
done
maze look
"""
def write(path: Path, data: str | bytes, mode: int = 0o644) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
if isinstance(data, str):
data = data.encode("utf-8")
path.write_bytes(data)
path.chmod(mode)
def digest(files: dict[str, bytes]) -> str:
h = hashlib.sha256()
for name in sorted(files):
h.update(name.encode() + b"\0" + files[name] + b"\0")
return h.hexdigest()[:12]
def template(folder: str) -> dict[str, bytes]:
root = TEMPLATE / folder
return {str(p.relative_to(root)): p.read_bytes() for p in sorted(root.rglob("*"))
if p.is_file() and "__pycache__" not in p.parts}
def generate(root: Path = HERE, seed: int = SEED, budget: int = BUDGET) -> None:
shutil.rmtree(root / "tasks", ignore_errors=True)
agent, maze, tests = (template(f) for f in ("environment/agent", "environment/maze", "tests"))
for t, layout in enumerate(trees(seed, budget), 1):
task = root / "tasks" / task_name(t)
tree_json = json.dumps(layout, indent=1).encode() + b"\n"
own_maze = maze | {"tree.json": tree_json}
write(task / "instruction.md", instruction(budget))
write(task / "task.toml", task_toml(t, budget, seed))
write(task / "environment" / "docker-compose.yaml",
compose(task_name(t), digest(agent), digest(own_maze)))
for name, data in agent.items():
write(task / "environment" / "agent" / name, data, 0o755 if name == "maze" else 0o644)
for name, data in own_maze.items():
write(task / "environment" / "maze" / name, data)
for name, data in tests.items():
write(task / "tests" / name, data, 0o755 if name.endswith(".sh") else 0o644)
expected = {"start": layout["start"], "exit": layout["exit"], "budget": budget,
"tree_sha256": hashlib.sha256(tree_json).hexdigest()}
write(task / "tests" / "expected.json", json.dumps(expected, indent=1) + "\n")
write(task / "solution" / "solve.sh", solve_sh(shortest_path(layout)), 0o755)
if __name__ == "__main__":
generate()
print(f"{TREES} trees of {ROOMS} rooms, one task each, move budget {BUDGET} (seed {SEED})")