Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 9,673 Bytes
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3421ea2
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a43f73c
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a43f73c
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a43f73c
161a2d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""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})")