lewtun's picture
lewtun HF Staff
maze.py: pre-first-move restore before visibility check; sibling commits under room container
3392096 verified
Raw History Blame Contribute Delete
15.3 kB
"""C.2 Branchability: Hidden Maze.
Task (paper, verbatim protocol): a randomly generated rooted tree of maximum
depth D; BFS generation samples 0..N children per room at depth < D; trees that
reach depth D are retained; the treasure sits at a uniformly sampled deepest
leaf. Room/exit IDs are opaque. A worker sees only its current room, its
visible exits, the exit back to the preceding room, and dead-end/treasure
flags. Every move through a visible exit costs one step, including retraces.
Treatments (previous memory read-only in all):
flat - memory/paths.jsonl logs all earlier moves; no saved state is
restorable; every worker starts at the entrance.
unstructured - memory/nodes/ stores one endpoint file per completed
trajectory; a worker can copy one to current_state.json but
its prompt does not mention this possibility.
branch_native - memory/ is a tree of checkpoint directories beneath the
endpoint they resumed; the prompt explicitly instructs the
worker to inspect the tree, select an endpoint and restore
its checkpoint.json before continuing. Restoring an endpoint
with existing children creates a sibling branch.
A checkpoint can be copied to current_state.json only BEFORE the worker's
first move; afterwards it follows one continuous trajectory. The harness
validates every restore and commits the final state after the episode.
Metrics: treasure discovery, steps to treasure, checkpoint restorations,
repeated-move fraction (steps whose directed room-exit pair was traversed by
an earlier step, across the whole run).
Sweeps (paper): depth sweep N=4, D in {4,6,8,10}, (B,k) = (2,6),(3,9),(4,12),
(4,15); branching sweep D=6, N in {2,4,6,8}, (B,k)=(3,9). k > D everywhere.
"""
import json
import os
import random
import shutil
import subprocess
from agent import run_worker_episode
def generate_maze(seed, D, N):
"""Random rooted tree, BFS generation, 0..N children, must reach depth D."""
rng = random.Random(seed)
while True:
rooms = {}
root = "room000"
rooms[root] = {"parent": None, "children": [], "depth": 0}
frontier = [root]
deepest = []
while frontier:
cur = frontier.pop(0)
d = rooms[cur]["depth"]
if d < D:
n = rng.randint(0, N)
if n == 0 and d < D and not any(
rooms[o]["children"] for o in frontier):
n = 1 # keep the tree alive so it can reach depth D
for _ in range(n):
rid = f"room{len(rooms):03d}_{rng.randrange(100, 999)}"
rooms[rid] = {"parent": cur, "children": [], "depth": d + 1}
rooms[cur]["children"].append(rid)
frontier.append(rid)
if d == D:
deepest.append(cur)
if deepest: # retained only if it reaches depth D
break
treasure = rng.choice(deepest)
rooms[treasure]["treasure"] = True
# opaque exit ids: one per directed edge (room -> child), plus back-exits
exits = {}
def _new_eid():
while True:
eid = f"exit{rng.randrange(10000, 99999)}"
if eid not in exits:
return eid
for rid, r in rooms.items():
r["exits"] = {}
for child in r["children"]:
eid = _new_eid()
exits[eid] = {"from": rid, "to": child, "back": False}
r["exits"][eid] = child
if r["parent"] is not None:
eid = _new_eid()
exits[eid] = {"from": rid, "to": r["parent"], "back": True}
r["exits"][eid] = r["parent"]
return {"rooms": rooms, "exits": exits, "root": root,
"treasure": treasure, "D": D, "N": N}
def room_state(maze, rid):
r = maze["rooms"][rid]
dead_end = not r["children"] and rid != maze["treasure"]
return {
"current_room": rid,
"visible_exits": sorted(r["exits"].keys()),
"treasure_here": rid == maze["treasure"],
"dead_end": dead_end,
}
def save_state_json(path, maze, rid):
with open(path, "w") as f:
json.dump(room_state(maze, rid), f, indent=2)
def system_prompt(treatment, k, memory_note):
restore_txt = ""
if treatment == "branch_native":
restore_txt = """
CHECKPOINT RESTORATION (important): memory/ holds a TREE of checkpoints from
earlier workers. Each endpoint directory contains checkpoint.json -- the exact
room state a previous worker stopped at. Inspect the tree (ls -R memory/),
select an endpoint, and copy its checkpoint.json over your current_state.json
BEFORE you make your first move. Restoring a leaf endpoint continues that
branch; restoring an endpoint that already has children starts a sibling
branch. After your first move you follow one continuous trajectory and cannot
restore again. Previous memory is read-only."""
elif treatment == "unstructured":
restore_txt = """
MEMORY: memory/nodes/ contains files saved by earlier workers, one per
endpoint where a previous worker stopped. This directory is read-only."""
return f"""You are an exploration worker in a hidden maze.
THE MAZE: a tree of rooms with opaque IDs. You see only your current room
(state in current_state.json): its visible exits, the exit back to the
preceding room, and whether the room is a dead end or contains the treasure.
A treasure is hidden at a deep leaf. Moving through any exit costs one step,
including moves that retrace previously explored routes.
TOOLS (reply with exactly one JSON object per turn):
{{"tool": "move", "args": {{"exit_id": "<id>", "rationale": "<why>"}}}}
- Moves through a visible exit; costs one step; updates current_state.json.
{{"tool": "bash", "args": {{"command": "<shell command>"}}}}
- Runs a shell command in your working directory (for notes and reading
read-only memory). Costs nothing.
{{"tool": "yield_worker", "args": {{"summary": "<what you found>"}}}}
- Ends your episode; your final state is committed for later workers.
MOVE BUDGET: exactly {k} moves.
{memory_note}{restore_txt}
"""
def treatment_memory_note(treatment):
if treatment == "flat":
return ("MEMORY: memory/paths.jsonl records every move made by "
"earlier workers on this maze (room, exit, resulting room) "
"and is read-only. You always start at the entrance; no "
"saved position can be resumed, so reaching a known region "
"means physically retracing the route there.")
if treatment == "unstructured":
return ("MEMORY: memory/nodes/ contains files saved by earlier "
"workers (read-only).")
if treatment == "branch_native":
return ("MEMORY: memory/ holds the checkpoint tree of all earlier "
"workers (read-only).")
raise ValueError(treatment)
def run_worker(client, maze, worker_dir, treatment, k, seed, usage,
global_steps, valid_restore_rooms):
os.makedirs(worker_dir, exist_ok=True)
cur_path = os.path.join(worker_dir, "current_state.json")
save_state_json(cur_path, maze, maze["root"])
state = {"room": maze["root"], "moves": 0, "steps_this_worker": [],
"found_at": None, "restored": False, "moved": False}
def validate_restore(room_id):
# a restore is legal only to an endpoint a previous worker actually
# committed; workers cannot fabricate states
return room_id in valid_restore_rooms
def move(args):
eid = str(args.get("exit_id", ""))
if state["moves"] >= k:
return "ERROR: move budget exhausted. Call yield_worker now.", False
if state["moved"] is False:
# apply and validate any pre-first-move restore BEFORE exit
# visibility is checked, so a restored worker moves from its
# restored room, not from the entrance
try:
with open(cur_path) as f:
st = json.load(f)
rid = st.get("current_room")
if rid != state["room"]:
if not validate_restore(rid):
save_state_json(cur_path, maze, state["room"])
return ("ERROR: invalid restored state; reset to "
"entrance."), False
state["restored"] = True
state["resume_room"] = rid
state["room"] = rid
except Exception:
save_state_json(cur_path, maze, state["room"])
ex = maze["exits"].get(eid)
if ex is None or ex["from"] != state["room"]:
return (f"ERROR: exit '{eid}' is not visible from your current "
"room."), False
state["moved"] = True
state["moves"] += 1
pair = (state["room"], eid)
rep = pair in global_steps
global_steps.add(pair)
state["room"] = ex["to"]
save_state_json(cur_path, maze, state["room"])
if state["room"] == maze["treasure"] and state["found_at"] is None:
state["found_at"] = state["moves"]
state["steps_this_worker"].append(
{"room": pair[0], "exit": eid, "to": state["room"],
"repeated": rep})
note = " (you already traversed this pair earlier)" if rep else ""
if state["room"] == maze["treasure"]:
return json.dumps({"moved_to": state["room"],
"treasure_found": True}) + note, False
return json.dumps({"moved_to": state["room"]}) + note, False
def bash(args):
p = subprocess.run(["bash", "-lc", str(args.get("command", ""))],
cwd=worker_dir, capture_output=True, text=True,
timeout=20)
return (p.stdout + p.stderr)[:8000] or "(no output)", False
def yield_worker(args):
state["summary"] = args.get("summary", "")
return "Episode committed.", True
tools = {"move": move, "bash": bash, "yield_worker": yield_worker}
prompt = system_prompt(treatment, k, treatment_memory_note(treatment))
done = run_worker_episode(prompt, tools, usage=usage, client=client)
return state
def prepare_memory(run_dir, maze, treatment):
mem = os.path.join(run_dir, "memory")
if treatment == "flat":
os.makedirs(mem, exist_ok=True)
open(os.path.join(mem, "paths.jsonl"), "a").close()
elif treatment == "unstructured":
os.makedirs(os.path.join(mem, "nodes"), exist_ok=True)
elif treatment == "branch_native":
os.makedirs(os.path.join(mem, "tree", maze["root"]), exist_ok=True)
return mem
def commit_state(run_dir, maze, treatment, worker_dir, state, worker_i):
"""Harness commits the worker's final state into the shared memory."""
mem = os.path.join(run_dir, "memory")
if treatment == "flat":
with open(os.path.join(mem, "paths.jsonl"), "a") as f:
for s in state["steps_this_worker"]:
f.write(json.dumps(s) + "\n")
return
rid = state["room"]
if treatment == "unstructured":
d = os.path.join(mem, "nodes")
shutil.copytree(worker_dir, os.path.join(d, f"endpoint_{worker_i}_{rid}"))
else: # branch_native: checkpoint as a child of the endpoint it resumed
# find the checkpoint dir whose room matches the resume point, else root
tree = os.path.join(mem, "tree")
parent_dir = _find_endpoint_dir(tree, state.get("resume_room",
maze["root"]))
d = os.path.join(parent_dir, f"branch_{worker_i}_{rid}")
os.makedirs(d, exist_ok=True)
shutil.copytree(worker_dir, d, ignore=shutil.ignore_patterns("memory"),
dirs_exist_ok=True)
with open(os.path.join(d, "checkpoint.json"), "w") as f:
json.dump(room_state(maze, rid), f)
with open(os.path.join(d, "path.json"), "w") as f:
json.dump({"room": rid, "steps": len(state["steps_this_worker"]),
"resume_room": state.get("resume_room", maze["root"])}, f)
def _find_endpoint_dir(tree, rid):
"""Locate the checkpoint directory for room rid (BFS), else tree root."""
# a room-named container dir (tree/<rid>) wins if it exists: commits
# resuming a room with no committed checkpoint yet are siblings there
cand = os.path.join(tree, rid)
if os.path.isdir(cand):
return cand
for dirpath, dirnames, _ in os.walk(tree):
pf = os.path.join(dirpath, "path.json")
if os.path.exists(pf):
with open(pf) as f:
if json.load(f).get("room") == rid:
return dirpath
# no checkpoint dir for rid yet: create its room container so sibling
# commits on the same fresh endpoint land side by side
os.makedirs(cand, exist_ok=True)
return cand
def run_condition(client, out_root, seed, D, N, B, k, treatment, usage=None):
maze = generate_maze(seed, D, N)
run_dir = os.path.join(out_root,
f"maze_D{D}_N{N}_{treatment}_seed{seed}")
os.makedirs(run_dir, exist_ok=True)
with open(os.path.join(run_dir, "maze.json"), "w") as f:
json.dump({"rooms": {r: {"parent": v["parent"], "children": v["children"],
"depth": v["depth"],
"treasure": v.get("treasure", False)}
for r, v in maze["rooms"].items()},
"exits": maze["exits"], "root": maze["root"],
"treasure": maze["treasure"], "D": D, "N": N}, f)
prepare_memory(run_dir, maze, treatment)
global_steps = set()
discovered_at = None
restorations = 0
total_steps = 0
repeated_steps = 0
valid_restore_rooms = set()
for i in range(B):
wdir = os.path.join(run_dir, f"worker_{i}")
state = run_worker(client, maze, wdir, treatment, k, seed * 100 + i,
usage, global_steps, valid_restore_rooms)
total_steps += len(state["steps_this_worker"])
repeated_steps += sum(1 for s in state["steps_this_worker"] if s["repeated"])
restorations += int(state["restored"])
if state["found_at"] is not None and discovered_at is None:
discovered_at = total_steps
if treatment != "flat":
valid_restore_rooms.add(state["room"])
commit_state(run_dir, maze, treatment, wdir, state, i)
if treatment != "flat": # previous memory is read-only for later workers
subprocess.run(["chmod", "-R", "a-w",
os.path.join(run_dir, "memory")], check=False)
return {"task": "maze", "seed": seed, "D": D, "N": N, "B": B, "k": k,
"treatment": treatment,
"discovered": discovered_at is not None,
"steps_to_treasure": discovered_at,
"total_steps": total_steps,
"repeated_fraction": (repeated_steps / total_steps
if total_steps else 0.0),
"checkpoint_restorations": restorations,
"run_dir": run_dir}