Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
s3-maze / budget.py
Agent Manager
Rename flock integration to legion
3421ea2
Raw History Blame Contribute Delete
8.66 kB
"""The move budget (huggingface/legion#115, section 6): `python budget.py [--draws 200]`
(Python 3.10+, no dependencies).
Simulates searches on the 32 trees in tasks/ with the maze service's own engine
(template/environment/maze/engine.py: every move goes through engine.Walk, which refuses what
the service refuses), without Legion or containers, and prints the success rate of each strategy
by team size N and per-agent move budget, as the Markdown table in README.md:
- (a) one agent, depth-first: it takes the first door it hasn't been through, in the order the
room lists them, and goes back when it has none left;
- (b) best-of-N: N agents search independently, each depth-first as in (a), but taking the
first listed unexplored door only half the time and a random one otherwise (each agent its
own habit); the team succeeds if any one gets out. Agents that always follow the shared door
order all walk (a)'s path, so then best-of-N is (a) at every N (`--habit 1`); `--habit 0` is
N searches in independent random orders;
- (c) a perfect split: the 27 dead ends, in (a)'s order, are cut into N runs as equal as
possible, and each agent searches only the branches that lead to its own run (it knows the
tree's shape, which no real agent does), depth-first as in (a).
A success needs the exit reached within the budget by at least one agent. (b) is averaged
over `--draws` draws of the agents' habits per tree.
"""
import argparse
import json
import random
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.dont_write_bytecode = True # nothing new in template/
sys.path.insert(0, str(HERE / "template" / "environment" / "maze"))
from engine import Maze, Walk # noqa: E402
SIZES = (1, 2, 4, 8)
BUDGETS = (30, 60, 90, 120, 150, 180, 210, 240, 300, 360, 450, 600, 750)
NEVER = 10 ** 9
def load_trees() -> list[dict]:
paths = sorted(HERE.glob("tasks/maze-t*/environment/maze/tree.json"))
if not paths:
raise SystemExit("no tasks/: run generate.py first")
return [json.loads(p.read_text()) for p in paths]
def search(maze: Maze, choose, allowed: set[str] | None = None) -> int:
"""Moves until the exit, depth-first through `engine.Walk`: `choose(room, unexplored)` picks
the next door among those not yet visited (in listed order, and in `allowed` if given);
with none left, go back the way it came."""
walk = Walk(maze)
seen, path = {walk.room}, [walk.room]
while not walk.reached:
here = walk.look()
unexplored = [d for d in here["doors"]
if d not in seen and (allowed is None or d in allowed)]
if unexplored:
target = choose(walk.room, unexplored)
path.append(target)
elif len(path) > 1:
path.pop()
target = path[-1]
else:
return NEVER # searched everything it may enter
_, why = walk.move(target)
if why is not None:
raise RuntimeError(f"the engine refused a search move: {why}")
seen.add(target)
return walk.moves
def first(room, unexplored):
return unexplored[0]
def habit(rng: random.Random, q: float):
def choose(room, unexplored):
return unexplored[0] if rng.random() < q else rng.choice(unexplored)
return choose
def dead_ends_in_order(maze: Maze) -> list[str]:
"""The dead ends in the order (a) reaches them."""
order, seen = [], {maze.start}
def visit(room):
if len(maze.doors[room]) == 1 and room != maze.start:
order.append(room)
for door in maze.doors[room]:
if door not in seen:
seen.add(door)
visit(door)
visit(maze.start)
return order
def toward(maze: Maze, targets: set[str]) -> set[str]:
"""The rooms on a path from the start to any of `targets`."""
parent, queue = {maze.start: None}, [maze.start]
for room in queue:
for door in maze.doors[room]:
if door not in parent:
parent[door] = room
queue.append(door)
keep = set()
for room in targets:
while room is not None and room not in keep:
keep.add(room)
room = parent[room]
return keep
def split_search(maze: Maze, n: int) -> int:
"""(c): moves until the exit for the agent whose run of dead ends holds it, searching
depth-first only the rooms on its way to its own dead ends."""
ends = dead_ends_in_order(maze)
size, extra = divmod(len(ends), n)
start = 0
for k in range(n):
share = ends[start:start + size + (k < extra)]
start += len(share)
if maze.exit in share:
allowed = toward(maze, set(share))
return search(maze, first, allowed)
raise RuntimeError("the exit is in no agent's share")
def rates(trees: list[dict], draws: int, q: float, seed: int) -> dict:
"""Success rates by strategy, N and budget."""
rng = random.Random(seed)
a, b, c = [], {n: [] for n in SIZES}, {n: [] for n in SIZES}
for tree in trees:
maze = Maze({**tree, "budget": NEVER})
a.append(search(maze, first))
singles = [search(maze, habit(rng, q)) for _ in range(draws * max(SIZES))]
for n in SIZES:
b[n].append([min(singles[i * n:(i + 1) * n]) for i in range(draws)])
c[n].append(split_search(maze, n))
out = {"a": {}, "b": {n: {} for n in SIZES}, "c": {n: {} for n in SIZES},
"a_moves": sorted(a)}
for budget in BUDGETS:
out["a"][budget] = sum(m <= budget for m in a) / len(trees)
for n in SIZES:
out["b"][n][budget] = sum(sum(m <= budget for m in draw) / draws
for draw in b[n]) / len(trees)
out["c"][n][budget] = sum(m <= budget for m in c[n]) / len(trees)
return out
def exact(tree: dict) -> dict:
"""(a) and (c) for an exit chosen uniformly: every tree has the same shape (only the labels,
the door order and the exit differ), so the exit on each of one tree's 27 dead ends in turn
gives the exact rates."""
ends = dead_ends_in_order(Maze(tree))
moves = {"a": [], **{n: [] for n in SIZES}}
for end in ends:
maze = Maze({**tree, "exit": end, "budget": NEVER})
moves["a"].append(search(maze, first))
for n in SIZES:
moves[n].append(split_search(maze, n))
return {"a": {budget: sum(m <= budget for m in moves["a"]) / len(ends) for budget in BUDGETS},
"c": {n: {budget: sum(m <= budget for m in moves[n]) / len(ends)
for budget in BUDGETS} for n in SIZES}}
def table(r: dict, b: bool = True) -> str:
sizes = [n for n in SIZES if n > 1]
head = (["budget", "(a) N=1"] + [f"(b) N={n}" for n in sizes] * b
+ [f"(c) N={n}" for n in sizes])
lines = ["| " + " | ".join(head) + " |", "|" + "---:|" * len(head)]
for budget in BUDGETS:
cells = [str(budget), f"{r['a'][budget]:.0%}"]
if b:
cells += [f"{r['b'][n][budget]:.0%}" for n in sizes]
cells += [f"{r['c'][n][budget]:.0%}" for n in sizes]
lines.append("| " + " | ".join(cells) + " |")
return "\n".join(lines)
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--draws", type=int, default=200, help="(b)'s draws per tree")
parser.add_argument("--habit", type=float, default=0.5,
help="(b): how often an agent takes the first listed unexplored door")
parser.add_argument("--seed", type=int, default=0, help="(b)'s draws")
parser.add_argument("--json", action="store_true", help="the rates as JSON instead")
parser.add_argument("--exact", action="store_true",
help="(a) and (c) for a uniformly chosen exit instead of the 32 trees'")
args = parser.parse_args(argv)
trees = load_trees()
if args.exact:
r = exact(trees[0])
title = "(a) and (c) for an exit chosen uniformly among the 27 dead ends"
print(json.dumps(r) if args.json else title + "\n" + table(r, b=False))
return 0
r = rates(trees, args.draws, args.habit, args.seed)
if r["c"][1] != r["a"]: # one agent's split is the whole tree
raise SystemExit("(c) at N = 1 is not (a)")
if args.json:
print(json.dumps(r))
else:
print(f"{len(trees)} trees, (b) with habit {args.habit} over {args.draws} draws per tree")
print(table(r))
print("(a)'s moves to the exit, by tree:", r["a_moves"])
return 0
if __name__ == "__main__":
sys.exit(main())