shortlist / code /scripts /ladder.py
JagritGumber's picture
Add episodes, verdicts, census, fixes, code, training analysis and dataset card
a2b0c04 verified
Raw History Blame Contribute Delete
7.86 kB
"""Play the capability ladder on environments and save every episode.
dotenvx run -- python scripts/ladder.py --suites maze_env,rg:leg_counting --tiers null,random,beam-low
python scripts/ladder.py --suites maze_env --tiers null,random # no key needed
Writes runs/<run>/<suite>.jsonl (one episode per line) and prints a line per episode.
"""
from __future__ import annotations
import argparse
import json
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from pathlib import Path
import requests
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from shortlist import beam # noqa: E402
from shortlist.policies import Beam, Null, Random, Small, SmallPlain, action_tool, random_supported # noqa: E402
from shortlist.rollout import run_episode # noqa: E402
from shortlist.serve import ROOT, serve # noqa: E402
from contextlib import nullcontext # noqa: E402
from shortlist.suite import SUITES, Suite, community, openspiel, reasoning_gym # noqa: E402
ATTEMPTS = {"null": 1, "random": 3, "small": 3, "beam-low": 3, "beam-medium": 2, "beam-high": 2, "beam-xhigh": 1, "beam-max": 1}
def resolve(name: str) -> tuple[str, Suite]:
if name.startswith("rg:"):
family = name[3:]
return f"rg-{family}", reasoning_gym(family)
if name.startswith("os:"):
return f"os-{name[3:]}", openspiel(name[3:])
if name.startswith("hub:"):
space = name[4:]
return "hub-" + space.replace("/", "__"), community(space)
return name, SUITES[name]
def env_docs(env: str, limit: int = 6000, space: str | None = None) -> str:
"""The environment's own README (front matter removed): what a person would read before playing."""
if space:
r = requests.get(f"https://huggingface.co/spaces/{space}/raw/main/README.md", timeout=30)
text = r.text if r.ok else ""
else:
path = ROOT / "vendor" / "OpenEnv" / "envs" / env / "README.md"
if not path.exists():
return ""
text = path.read_text()
if text.startswith("---"):
text = text.split("---", 2)[-1]
text = text.strip()
return text[:limit] + (" …(truncated)" if len(text) > limit else "")
def make_policy(tier: str, suite: Suite, seed: int, docs: str = ""):
if tier == "null":
return Null()
if tier == "random":
return Random(seed)
extra_small = "\n\n".join(x for x in (f"Environment documentation (its README):\n{docs}" if docs else "", suite.beam_hint) if x)
if tier == "small":
return SmallPlain(*suite.plain_question) if suite.plain_question else Small(extra_small)
extra = "\n\n".join(x for x in (f"Environment documentation (its README):\n{docs}" if docs else "", suite.beam_hint) if x)
return Beam(tier.split("-", 1)[1], extra)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--suites", required=True)
parser.add_argument("--tiers", default="null,random,beam-low")
parser.add_argument("--run", default=datetime.now(timezone.utc).strftime("%Y%m%d-%H%M"))
parser.add_argument("--parallel", type=int, default=4)
parser.add_argument("--attempts", default="", help="override, e.g. beam-low=2,beam-high=1")
parser.add_argument("--suite-parallel", type=int, default=3, help="environments played at the same time")
parser.add_argument("--envs-dir", default=None, help="folder with patched environment copies (searched first)")
args = parser.parse_args()
attempts = dict(ATTEMPTS)
for part in filter(None, args.attempts.split(",")):
k, v = part.split("=")
attempts[k] = int(v)
out_dir = ROOT / "runs" / args.run
out_dir.mkdir(parents=True, exist_ok=True)
tiers = args.tiers.split(",")
stop = threading.Event()
def run_suite(name: str) -> None:
if stop.is_set():
return
suite_id, suite = resolve(name)
path = out_dir / f"{suite_id}.jsonl"
done_keys = set()
if path.exists(): # resume: skip episodes already recorded
from shortlist.checks import harness_error
for line in path.read_text().splitlines():
r = json.loads(line)
if not harness_error(r): # our own failures are played again
done_keys.add((r["policy"], r["task"], r["attempt"]))
lock = threading.Lock()
try:
envs_dir = args.envs_dir or suite.envs_dir
if suite.space:
from openenv.core.utils import hf_space_subdomain
server = nullcontext(suite.remote_url or f"https://{hf_space_subdomain(suite.space)}.hf.space")
else:
server = serve(suite.env, extra_env=suite.server_env or None, envs_dir=(ROOT / envs_dir).resolve() if envs_dir else None)
with server as url:
schema = requests.get(f"{url}/schema", timeout=30).json()
tool = action_tool(schema["action"])
docs = env_docs(suite.env, space=suite.space)
if "random" in tiers:
from openenv.core.generic_client import GenericEnvClient
with GenericEnvClient(base_url=url).sync() as probe_env:
first = probe_env.reset(**suite.tasks[0]).observation or {}
if not random_supported(tool, first):
print(f" {suite_id:26s} random play skipped: no legal-move list or bounded action fields")
done_keys.update(("random", t, a) for t in range(len(suite.tasks)) for a in range(attempts["random"]))
jobs = [(tier, t, a) for tier in tiers for t in range(len(suite.tasks)) for a in range(attempts[tier])
if (make_policy(tier, suite, 0).name, t, a) not in done_keys]
def work(job):
tier, t, a = job
policy = make_policy(tier, suite, seed=t * 100 + a, docs=docs)
record = run_episode(url, tool, policy, suite.tasks[t], suite.max_steps)
record.update({"suite": suite_id, "env": suite.env, "task": t, "attempt": a,
"score_mode": suite.score, "solved_at": suite.solved_at, "notes": suite.notes, **suite.extra})
with lock:
with path.open("a") as f:
f.write(json.dumps(record, default=str) + "\n")
score = record["return"] if suite.score == "return" else record["mean_step_reward"]
flag = "ERR " if record["error"] else " "
print(f"{flag}{suite_id:26s} {record['policy']:12s} task {t} try {a} score {score:8.3f} steps {record['n_steps']:3d} "
f"out-tokens {record['tokens']['completion']:6d} {record['seconds']:6.1f}s {(record['error'] or '')[:90]}", flush=True)
with ThreadPoolExecutor(max_workers=min(args.parallel, suite.parallel)) as pool:
list(pool.map(work, jobs))
except beam.DailyLimitReached:
stop.set()
print("Daily Beam allowance used up; resume after 00:00 UTC with the same --run.")
except Exception as error: # noqa: BLE001
print(f"SUITE FAILED {suite_id}: {type(error).__name__}: {error}")
with path.with_suffix(".failed.txt").open("w") as f:
f.write(f"{type(error).__name__}: {error}\n")
with ThreadPoolExecutor(max_workers=args.suite_parallel) as suites_pool:
list(suites_pool.map(run_suite, args.suites.split(",")))
print(json.dumps({"beam_usage": beam.USAGE.summary()}))
(out_dir / f"usage-{int(time.time())}.json").write_text(json.dumps(beam.USAGE.summary()))
if __name__ == "__main__":
main()