diff --git a/tasks/hicard-latent-encoder/task.toml b/tasks/hicard-latent-encoder/task.toml index a7559405f8881cb038ce1b642b0a62b1580c383b..e3005ed40c81da0749d8286b268d904fd39cc0a4 100644 --- a/tasks/hicard-latent-encoder/task.toml +++ b/tasks/hicard-latent-encoder/task.toml @@ -1,57 +1,71 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/hicard-latent-encoder" -version = "1.0.0" +version = "1.1.0" description = "" -keywords = [ "autoresearch", "machine-learning", "benchmark",] -[[task.authors]] -name = "Bespoke Labs" +keywords = [ + "autoresearch", + "machine-learning", + "benchmark", +] +authors = [ + { name = "Bespoke Labs" }, +] [metadata] category = "Machine Learning and AI" subcategory = "Feature engineering" -task_objective = [ "Implement", "Optimize",] -artifact_type = [ "Single script or program",] +task_objective = [ + "Implement", + "Optimize", +] +artifact_type = [ + "Single script or program", +] expert_time_estimate_hours = 4.0 +are_version = "1.1" +budget_seconds = 86400 [verifier] -timeout_sec = 1800.0 +timeout_sec = 600.0 environment_mode = "separate" -collect = [] -[verifier.env] +[[verifier.collect]] +service = "grader" +command = "/opt/are/venv/bin/python /opt/are/drain.py" +timeout_sec = 3600.0 [verifier.environment] network_mode = "no-network" -build_timeout_sec = 3600.0 -os = "linux" -cpus = 8 -memory_mb = 14336 -storage_mb = 153600 +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 gpus = 0 -mcp_servers = [] - -[verifier.environment.env] [agent] network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] -timeout_sec = 14400.0 +allowed_hosts = [ + "api.openai.com", + "api.anthropic.com", + "grader", +] +timeout_sec = 86400.0 user = "agent" [environment] -network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] +network_mode = "public" build_timeout_sec = 3600.0 os = "linux" cpus = 8 memory_mb = 14336 storage_mb = 153600 gpus = 0 -mcp_servers = [] +mcp_servers = [ + { name = "are", transport = "streamable-http", url = "http://grader:8000/mcp" }, +] [environment.env] - -[solution.env] diff --git a/tasks/hicard-latent-encoder/tests/Dockerfile b/tasks/hicard-latent-encoder/tests/Dockerfile index 359c13232518c381925d72e7f87e9a42cd233db6..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/hicard-latent-encoder/tests/Dockerfile +++ b/tasks/hicard-latent-encoder/tests/Dockerfile @@ -1,35 +1,2 @@ -FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb - -ENTRYPOINT [] -ENV PYTHONPATH= -ENV PYTHONSAFEPATH=1 -ENV DEBIAN_FRONTEND=noninteractive \ - PYTHONHASHSEED=0 \ - PIP_NO_CACHE_DIR=1 \ - PIP_DISABLE_PIP_VERSION_CHECK=1 \ - OMP_NUM_THREADS=1 \ - OPENBLAS_NUM_THREADS=1 \ - MKL_NUM_THREADS=1 - -RUN useradd --create-home --uid 1001 agent - -COPY ./requirements.txt /tmp/requirements.txt -COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt -RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ - -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ - && rm /tmp/requirements.txt /tmp/requirements-verifier.txt - -RUN mkdir -p /app/output /logs/verifier - -COPY . /tests - -RUN mkdir -p /opt/harness \ - && cp /tests/candidate_runner.py /opt/harness/candidate_runner.py \ - && chown -R root:root /opt/harness /tests \ - && chmod 755 /opt/harness \ - && chmod 644 /opt/harness/candidate_runner.py \ - && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ - && chmod +x /tests/test.sh /tests/intermediate.sh \ - && find /tests /opt/harness -exec touch -d @1700000000 {} + - -WORKDIR /tests +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/hicard-latent-encoder/tests/finalize.py b/tasks/hicard-latent-encoder/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/hicard-latent-encoder/tests/finalize.py @@ -0,0 +1,59 @@ +"""Final verifier: score the run from the grader ledger. + +reward hidden test score of the submission with the best validation score + (ties go to the earlier submission); 0 if nothing was submitted. +auarc area under the curve of that same quantity over the wall-clock budget, + using the time each validation score became available, divided by the + budget. 0 before the first graded submission. +""" + +import json +from pathlib import Path + +STATE = Path("/var/lib/are") +OUT = Path("/logs/verifier") +OUT.mkdir(parents=True, exist_ok=True) + +meta = json.loads((STATE / "meta.json").read_text()) if (STATE / "meta.json").exists() else {} +budget = float(meta.get("budget_seconds") or 1.0) + +subs: dict[int, dict] = {} +ledger = STATE / "ledger.jsonl" +for line in (ledger.read_text().splitlines() if ledger.exists() else []): + ev = json.loads(line) + s = subs.setdefault(ev["id"], {"id": ev["id"]}) + if ev["event"] == "submitted": + s["submitted_t"] = ev["t"] + elif ev["event"] == "val": + s["val"] = ev["score"] + s["val_t"] = ev["t"] + elif ev["event"] == "test": + s["test"] = ev["score"] + +graded = sorted((s for s in subs.values() if "val" in s), key=lambda s: s["val_t"]) + +# Step function of the hidden score of the best-validation pick over time. +auc, best, last_t, cur = 0.0, None, 0.0, 0.0 +timeline = [] +for s in graded: + t = min(s["val_t"], budget) + auc += cur * (t - last_t) + last_t = t + if best is None or s["val"] > best["val"] or (s["val"] == best["val"] and s["id"] < best["id"]): + best = s + cur = float(best.get("test") or 0.0) + timeline.append({"t": s["val_t"], "id": s["id"], "val": s["val"], "test": s.get("test"), + "pick": best["id"]}) +auc += cur * (budget - last_t) if last_t < budget else 0.0 + +reward = { + "reward": float(best.get("test") or 0.0) if best else 0.0, + "auarc": auc / budget, + "best_val": float(best["val"]) if best else 0.0, + "n_submissions": float(len(subs)), + "n_test_graded": float(sum(s.get("test") is not None for s in subs.values())), +} +(OUT / "reward.json").write_text(json.dumps(reward)) +(OUT / "timeline.json").write_text(json.dumps({"budget": budget, "selected": best and best["id"], + "submissions": timeline}, indent=1)) +print(json.dumps(reward, indent=1)) diff --git a/tasks/hicard-latent-encoder/tests/test.sh b/tasks/hicard-latent-encoder/tests/test.sh index 9391c4c58b74a1639e054101abff351ac1a18e4b..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/hicard-latent-encoder/tests/test.sh +++ b/tasks/hicard-latent-encoder/tests/test.sh @@ -1,19 +1,2 @@ #!/bin/bash -set -u - -mkdir -p /logs/verifier -chown root:root /logs/verifier 2>/dev/null || true -chmod 755 /logs/verifier 2>/dev/null || true -rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json - -trap 'if [ ! -s /logs/verifier/reward.txt ]; then echo 0 > /logs/verifier/reward.txt; fi' EXIT TERM INT - -chmod -R go-rwx /tests - -export GRADER_SPLIT=final - -cd /tests -/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA -/usr/local/bin/python3 /tests/compute_reward.py - -exit 0 +python3 /tests/finalize.py diff --git a/tasks/label-efficient-risk-estimator/environment/.dockerignore b/tasks/label-efficient-risk-estimator/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/Dockerfile b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9e76d946f050135140319a5b3b347150a25c2aa2 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,34 @@ +FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONHASHSEED=0 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements.txt /tmp/requirements.txt +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ + -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements.txt /tmp/requirements-verifier.txt + +RUN mkdir -p /app/output /logs/verifier /grade_run + +COPY . /tests + +RUN chown -R root:root /tests \ + && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/Dockerfile.are b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..1f84197fd33ef5328b46f7c9feff7daac3b6638e --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,52 @@ +FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONHASHSEED=0 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements.txt /tmp/requirements.txt +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ + -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements.txt /tmp/requirements-verifier.txt + +RUN mkdir -p /app/output /logs/verifier /grade_run + +COPY . /tests + +RUN chown -R root:root /tests \ + && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 + + +# ---- ARE 1.1 grader layer (appended to the task's own verifier Dockerfile) ---- +ARG ARE_ROLE +# python.org images ship /usr/local/bin/python3; distro-python bases (kaggle GPU) lack +# ensurepip, so fall back to a pip-less venv filled by the base interpreter's pip. +RUN PY=$(command -v /usr/local/bin/python3 || command -v python3) \ + && if "$PY" -m venv /opt/are/venv; then \ + /opt/are/venv/bin/pip install --no-cache-dir "fastmcp==2.14.7"; \ + else rm -rf /opt/are/venv && "$PY" -m venv --without-pip /opt/are/venv \ + && "$PY" -m pip --python /opt/are/venv/bin/python install --no-cache-dir "fastmcp==2.14.7"; fi +COPY are/ /opt/are/ +# The val grader, whose output reaches the agent, never holds the private grader or its +# data. The test grader keeps everything; nothing from it reaches the agent. +RUN rm -rf /tests/are /tests/Dockerfile.are \ + && if [ "$ARE_ROLE" = "val" ]; then rm -rf /tests/test.sh /tests/hidden_data/final; fi +ENV ARE_ROLE=$ARE_ROLE +CMD ["/opt/are/venv/bin/python", "/opt/are/server.py"] diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/are/drain.py b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/are/drain.py @@ -0,0 +1,25 @@ +"""Verifier collect hook, run after the agent stops. + +Grades the final workspace as one last submission (unless it equals the last one), +then waits until every submission has both grades recorded. +""" + +import json +import time +import urllib.request +from pathlib import Path + +TOKEN = Path("/run/are-secret/token").read_text().strip() +H = {"x-are-token": TOKEN} + +req = urllib.request.Request("http://localhost:8000/final", method="POST", headers=H) +with urllib.request.urlopen(req, timeout=120) as resp: + print("final:", json.loads(resp.read()), flush=True) + +while True: + with urllib.request.urlopen(urllib.request.Request("http://localhost:8000/drain", headers=H), timeout=30) as resp: + state = json.loads(resp.read()) + print(state, flush=True) + if state["val_pending"] == 0 and state["test_pending"] == 0: + break + time.sleep(5) diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/are/server.py b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/are/server.py @@ -0,0 +1,538 @@ +"""ARE 1.1 grader sidecar. + +One image, two roles: + +- ARE_ROLE=val ("grader" service). Reachable from the agent. Serves MCP tools and a + REST fallback. On submit it snapshots the shared deliverable volume, grades the + snapshot with the task's public grader (intermediate.sh), and returns only that + score. Every snapshot is also sent to the test grader; the hidden score goes to a + root-only ledger and never back to the agent. +- ARE_ROLE=test ("test-grader" service). On a private network that only the val + grader can reach. Grades snapshots with the task's private grader (test.sh). +""" + +from __future__ import annotations + +import asyncio +import gzip +import hashlib +import io +import secrets +import json +import os +import queue +import shutil +import subprocess +import tarfile +import threading +import time +import urllib.request +from pathlib import Path + +from fastmcp import FastMCP +from starlette.requests import Request +from starlette.responses import JSONResponse, Response + +ROLE = os.environ.get("ARE_ROLE", "val") +PORT = int(os.environ.get("ARE_PORT", "8000")) +STATE = Path(os.environ.get("ARE_STATE_DIR", "/var/lib/are")) +ARTIFACT_PATHS = [p for p in os.environ.get("ARE_ARTIFACT_PATHS", "/app/output").split(":") if p] +# The shared deliverable volume. Its parent is root-only, so submitted code (which every +# task grader runs as the unprivileged agent user) cannot reach it to write back to the agent. +SUBMISSION_ROOT = Path(os.environ.get("ARE_SUBMISSION_ROOT", "/run/are-deliverable")) +AGENT_UID = int(os.environ.get("ARE_AGENT_UID", "1001")) +BUDGET_SEC = float(os.environ.get("ARE_BUDGET_SEC", "14400")) +GRADE_TIMEOUT_SEC = float(os.environ.get("ARE_GRADE_TIMEOUT_SEC", "1800")) +TEST_GRADER_URL = os.environ.get("ARE_TEST_GRADER_URL", "http://test-grader:8001") +FEEDBACK_TAIL = int(os.environ.get("ARE_FEEDBACK_TAIL_CHARS", "8192")) +SCRIPT = "/tests/intermediate.sh" if ROLE == "val" else "/tests/test.sh" +# Shared only by the two graders (a volume the agent's container never mounts). The test +# grader writes a fresh token at startup; every internal request must carry it, so the +# agent cannot reach the test grader or the internal endpoints even on a shared network. +TOKEN_FILE = Path(os.environ.get("ARE_TOKEN_FILE", "/run/are-secret/token")) +TOKEN = "" + + +def _authorized(request: Request) -> bool: + """Internal endpoints need the graders' token; an unset token never matches.""" + return bool(TOKEN) and secrets.compare_digest(request.headers.get("x-are-token", ""), TOKEN) + + +def _net_isolation_available() -> bool: + try: + return subprocess.run(["unshare", "-n", "true"], capture_output=True, timeout=10).returncode == 0 + except Exception: + return False + + +NET_ISOLATED = False # set at startup: grader scripts run in an empty network namespace + +T0 = time.time() +_lock = threading.Lock() + + +def _elapsed() -> float: + return round(time.time() - T0, 1) + + +def _ledger(event: dict) -> None: + event = {"t": _elapsed(), "wall": time.time(), **event} + for attempt in range(3): + try: + with _lock, open(STATE / "ledger.jsonl", "a") as fh: + fh.write(json.dumps(event) + "\n") + return + except OSError: + if attempt == 2: + raise + time.sleep(1) + + +def _kill_grading_processes(proc: subprocess.Popen) -> None: + """Kill everything a timed-out grade started, including processes that left its group.""" + try: + os.killpg(proc.pid, 9) + except ProcessLookupError: + pass + _kill_other_processes() + + +def _kill_other_processes() -> None: + """Kill every process run by the agent user. Every task grader runs submitted code as + that user, so this stops all graded code (detached or not) and nothing else: the grader + server, the task's own grader and Harbor's hooks run as root.""" + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + if entry.stat().st_uid == AGENT_UID: + os.kill(int(entry.name), 9) + except (ProcessLookupError, PermissionError, FileNotFoundError): + pass + + +# Places the agent user (who runs submitted code inside every task grader) can write. +_BASELINE: set[str] = set() # every path that existed when the grader started (its image) + + +def _walk_one_fs(base: Path): + """Every path under base on base's own filesystem (skips /proc, /sys and other mounts).""" + dev = base.stat().st_dev + for root, dirs, files in os.walk(base): + dirs[:] = [d for d in dirs if os.lstat(os.path.join(root, d)).st_dev == dev] + for name in dirs + files: + yield Path(root) / name + + +def _all_paths() -> set[str]: + out = set() + for base in (Path("/"), Path("/dev/shm")): + if base.is_dir(): + out.update(str(q) for q in _walk_one_fs(base)) + return out + + +def _protected(path: str) -> bool: + keep = [str(STATE), "/opt/are", str(TOKEN_FILE.parent)] + return any(path == k or path.startswith(k + "/") for k in keep) + + +def _fresh_state() -> None: + """Start every grade from the grader image's own files, as ARE 1.0's fresh verifier + container did. The grader container lives for the whole run, so before each grade + stop anything an earlier grade left running and delete every file it created, + whoever wrote it. The deliverable volume and the token are separate mounts and are + never walked; the grader's own state is kept.""" + _kill_other_processes() + # System V shared memory, semaphores and queues outlive processes; this server uses none. + subprocess.run(["ipcrm", "--all"], capture_output=True) + for path in sorted(_all_paths() - _BASELINE, key=lambda q: q.count("/"), reverse=True): + if _protected(path): + continue + try: + q = Path(path) + if q.is_dir() and not q.is_symlink(): + shutil.rmtree(q, ignore_errors=True) + else: + q.unlink() + except OSError: + pass + + +def grade_snapshot(tar_bytes: bytes, tag: str) -> dict: + """Extract a snapshot over the artifact paths and run this role's grader script.""" + _fresh_state() + for path in ARTIFACT_PATHS: + p = Path(path) + if p.exists(): + shutil.rmtree(p) + p.mkdir(parents=True) + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:gz") as tf: + tf.extractall("/", filter="tar") + logs = Path("/logs/verifier") + if logs.exists(): + shutil.rmtree(logs) + logs.mkdir(parents=True) + started = time.time() + # Submitted code runs with no network, as in ARE 1.0's verifier. + cmd = (["unshare", "-n"] if NET_ISOLATED else []) + ["bash", SCRIPT] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + cwd="/tests", start_new_session=True) + try: + out, err = proc.communicate(timeout=GRADE_TIMEOUT_SEC) + error = None + except subprocess.TimeoutExpired: + _kill_grading_processes(proc) + out, err = proc.communicate() + error = f"grader timed out after {GRADE_TIMEOUT_SEC:.0f}s" + output = (out or "") + (err or "") + # Nothing a grade started may keep running after it, not even detached processes. + _kill_other_processes() + score = 0.0 + reward_file = logs / "reward.txt" + if reward_file.exists(): + try: + score = float(reward_file.read_text().strip() or 0) + except ValueError: + error = error or "unparseable reward" + metric = None + if (logs / "metric.json").exists(): + try: + metric = json.loads((logs / "metric.json").read_text()) + except ValueError: + pass + (STATE / "logs").mkdir(exist_ok=True) + (STATE / "logs" / f"{tag}.log").write_text(output) + return { + "score": score, + "metric": metric, + "error": error, + "net_isolated": NET_ISOLATED, + "seconds": round(time.time() - started, 1), + # What the agent sees, as in ARE 1.0: the grader's stdout tail (not stderr). + "output_tail": (out or "")[-FEEDBACK_TAIL:], + } + + +mcp = FastMCP("are") + + +# ---------------------------------------------------------------- test role + + +_grade_lock = threading.Lock() + + +def _grade_one_at_a_time(tar_bytes: bytes, tag: str) -> dict: + # A request that timed out on the caller's side may still be grading; the next one + # waits for it rather than sharing /app/output and /logs/verifier with it. + with _grade_lock: + return grade_snapshot(tar_bytes, tag) + + +if ROLE == "test": + + @mcp.custom_route("/grade", methods=["POST"]) + async def http_grade(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + tag = request.query_params.get("tag", "x") + body = await request.body() + result = await asyncio.to_thread(_grade_one_at_a_time, body, f"{tag}-test") + return JSONResponse(result) + + +# ----------------------------------------------------------------- val role + + +class Board: + """Submissions and their grading state. Hidden scores are never stored here.""" + + def __init__(self) -> None: + self.subs: dict[int, dict] = {} + self.val_q: queue.Queue[int] = queue.Queue() + self.next_id = 1 + self.test_pending = 0 + self.last_digest: str | None = None + + def public(self, sid: int) -> dict: + s = self.subs[sid] + out = {k: s[k] for k in ("id", "note", "submitted_at_s", "status")} + if s["status"] == "graded": + v = s["val"] + out.update( + validation_score=v["score"], + error=v["error"], + grading_seconds=v["seconds"], + grader_output_tail=v["output_tail"], + ) + return out + + def best(self) -> dict | None: + graded = [s for s in self.subs.values() if s["status"] == "graded"] + if not graded: + return None + b = max(graded, key=lambda s: (s["val"]["score"], -s["id"])) + return {"id": b["id"], "validation_score": b["val"]["score"]} + + +board = Board() + + +def snapshot() -> bytes: + """Deterministic tar.gz of the deliverable: same content, same bytes (gzip mtime 0).""" + raw = io.BytesIO() + with tarfile.open(fileobj=raw, mode="w") as tf: + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + tf.add(str(src), arcname=path.lstrip("/")) + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as gz: + gz.write(raw.getvalue()) + return out.getvalue() + + +def do_submit(note: str, final: bool = False) -> dict: + with _lock: + pending = [s["id"] for s in board.subs.values() if s["status"] != "graded"] + if pending and not final: + return { + "error": f"Submission {pending[0]} is still being graded. One submission is " + f"graded at a time: check result({pending[0]}) and submit again " + "once it has its score.", + "pending_id": pending[0], + } + sid = board.next_id + board.next_id += 1 + board.subs[sid] = {"id": sid, "note": note[:500], "submitted_at_s": _elapsed(), + "status": "queued"} + try: + data = snapshot() + digest = hashlib.sha256(data).hexdigest() + (STATE / "snapshots" / f"{sid:04d}.tar.gz").write_bytes(data) + _ledger({"event": "submitted", "id": sid, "note": note[:500], "bytes": len(data), + "sha256": digest, "final": final}) + except Exception as exc: + with _lock: + board.subs.pop(sid, None) # release the slot; the id is not reused + return {"error": f"Could not snapshot the deliverable ({exc}). Nothing was submitted. " + "Make sure nothing is writing to it, then submit again."} + board.last_digest = digest + with _lock: + board.test_pending += 1 + board.val_q.put(sid) + return {"id": sid, "status": "queued", + "hint": "Grading has started. Check result(id) for the validation score."} + + +def final_submit() -> dict: + """After the agent stops: grade the final workspace unless it was already submitted.""" + try: + data = snapshot() + except Exception as exc: + return {"error": f"final snapshot failed: {exc}"} + if board.subs and hashlib.sha256(data).hexdigest() == board.last_digest: + return {"skipped": "final workspace equals the last submission"} + return do_submit("final workspace (automatic)", final=True) + + +def grade_worker() -> None: + """Grade each submission on val, then on test, one submission at a time. + + The val score is published as soon as it is ready. The next submission's val grade + waits until this test grade is done, so the two graders never run at the same time. + """ + while True: + sid = board.val_q.get() + board.subs[sid]["status"] = "grading" + data = b"" + try: + data = (STATE / "snapshots" / f"{sid:04d}.tar.gz").read_bytes() + res = grade_snapshot(data, f"{sid:04d}-val") + except Exception as exc: + res = {"score": 0.0, "metric": None, "error": f"grader failed: {exc}", + "net_isolated": NET_ISOLATED, "seconds": 0.0, "output_tail": ""} + board.subs[sid]["val"] = res + board.subs[sid]["status"] = "graded" + try: + _ledger({"event": "val", "id": sid, **{k: res[k] for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + test_grade(sid, data) + + +def test_grade(sid: int, data: bytes) -> None: + try: + _test_grade(sid, data) + finally: + with _lock: + board.test_pending -= 1 + + +def _test_grade(sid: int, data: bytes) -> None: + """Send one snapshot to the test grader. A failed request is retried (the same snapshot + is graded again, so a retry can only recover the honest score); a request that ran + past its timeout is not, since the grade itself already took the full time.""" + started = time.time() + for attempt in range(3): + try: + req = urllib.request.Request( + f"{TEST_GRADER_URL}/grade?tag={sid:04d}", data=data, method="POST", + headers={"x-are-token": TOKEN}, + ) + with urllib.request.urlopen(req, timeout=2 * GRADE_TIMEOUT_SEC + 300) as resp: + res = json.loads(resp.read()) + break + except Exception as exc: # recorded, never shown to the agent + res = {"score": None, "metric": None, "error": f"test grader: {exc}", + "seconds": round(time.time() - started, 1)} + if attempt == 2 or isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError): + break + time.sleep(5) + try: + _ledger({"event": "test", "id": sid, **{k: res.get(k) for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + + +def with_time(out: dict) -> dict: + """Wall-clock accounting on every reply, as the v1 harness gave each phase.""" + out["total_budget_seconds"] = BUDGET_SEC + out["time_remaining_seconds"] = round(max(0.0, BUDGET_SEC - _elapsed()), 1) + return out + + +def status_dict() -> dict: + return { + "submissions": len(board.subs), + "queued_or_grading": sum(s["status"] != "graded" for s in board.subs.values()), + "best": board.best(), + } + + +def current_result(sid: int) -> dict: + return board.public(sid) + + +if ROLE == "val": + + @mcp.tool + async def submit(note: str = "") -> dict: + """Submit the current deliverable for grading. + + Snapshots the deliverable directory right now (later edits do not affect this + submission) and starts grading it on the public validation split. Returns at + once with a submission id. One submission is graded at a time: check `result` + and submit again once the previous submission has its score. `note` is a short + description of what changed. + """ + return with_time(await asyncio.to_thread(do_submit, note)) + + @mcp.tool + async def result(id: int) -> dict: + """The current state of a submission: queued, grading, or graded with its + validation score and grader output. Returns immediately.""" + if id not in board.subs: + return {"error": f"unknown submission id {id}"} + return with_time(current_result(id)) + + @mcp.tool + async def status() -> dict: + """Submission count, whether one is being graded, the best validation score, + and the time budget and time remaining.""" + return with_time(status_dict()) + + @mcp.custom_route("/submit", methods=["POST"]) + async def http_submit(request: Request) -> Response: + note = request.query_params.get("note", "") + return JSONResponse(with_time(await asyncio.to_thread(do_submit, note))) + + @mcp.custom_route("/result/{sid}", methods=["GET"]) + async def http_result(request: Request) -> Response: + sid = int(request.path_params["sid"]) + if sid not in board.subs: + return JSONResponse({"error": f"unknown submission id {sid}"}, status_code=404) + return JSONResponse(with_time(current_result(sid))) + + @mcp.custom_route("/status", methods=["GET"]) + async def http_status(request: Request) -> Response: + return JSONResponse(with_time(status_dict())) + + @mcp.custom_route("/final", methods=["POST"]) + async def http_final(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Collect hook, after the agent has stopped. + return JSONResponse(await asyncio.to_thread(final_submit)) + + @mcp.custom_route("/drain", methods=["GET"]) + async def http_drain(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Used by the verifier collect hook after the agent has stopped. + pending = sum(s["status"] != "graded" for s in board.subs.values()) + return JSONResponse({"val_pending": pending, "test_pending": board.test_pending}) + + +def _gpus() -> list[str]: + try: + out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=20) + return [l for l in out.stdout.splitlines() if l.strip()] + except Exception: + return [] + + +@mcp.custom_route("/health", methods=["GET"]) +async def health(request: Request) -> Response: + return JSONResponse({"ok": True, "role": ROLE, "gpus": await asyncio.to_thread(_gpus)}) + + +def _setup_token() -> None: + global TOKEN + if ROLE == "test": + TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True) + os.chmod(TOKEN_FILE.parent, 0o700) + TOKEN = secrets.token_hex(32) + TOKEN_FILE.write_text(TOKEN) + os.chmod(TOKEN_FILE, 0o600) + else: + for _ in range(300): # the test grader is healthy before this one starts + if TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip(): + break + time.sleep(1) + TOKEN = TOKEN_FILE.read_text().strip() + if not TOKEN: + raise SystemExit("ARE: empty internal token; refusing to start") + + +def main() -> None: + global NET_ISOLATED + NET_ISOLATED = _net_isolation_available() + if not NET_ISOLATED: + # Graded code must never have a network path (for example back through /submit). + raise SystemExit("ARE grader: cannot run grades without network access " + "(needs `unshare -n`, i.e. CAP_SYS_ADMIN); refusing to start") + STATE.mkdir(parents=True, exist_ok=True) + _BASELINE.update(_all_paths()) + _setup_token() + STATE.mkdir(parents=True, exist_ok=True) + os.chmod(STATE, 0o700) + (STATE / "snapshots").mkdir(exist_ok=True) + if ROLE == "val": + # The deliverable volume starts empty and root-owned; hand it to the agent user. + SUBMISSION_ROOT.mkdir(parents=True, exist_ok=True) + os.chmod(SUBMISSION_ROOT, 0o700) + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + src.mkdir(parents=True, exist_ok=True) + os.chown(src, AGENT_UID, AGENT_UID) + (STATE / "meta.json").write_text(json.dumps( + {"t0_wall": T0, "budget_seconds": BUDGET_SEC, "artifact_paths": ARTIFACT_PATHS} + )) + threading.Thread(target=grade_worker, daemon=True).start() + mcp.run(transport="http", host="0.0.0.0", port=PORT, show_banner=False, + uvicorn_config={"timeout_keep_alive": 86400}) + + +if __name__ == "__main__": + main() diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/candidate_runner.py b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/candidate_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..bd67896422319f44cc0f69fa1285c32ba474a93a --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/candidate_runner.py @@ -0,0 +1,142 @@ +import argparse +import os +import signal +import socket +import struct +import sys +import time +import types + +import numpy as np + +_HDR = struct.Struct(" deadline: + for sig in (signal.SIGKILL,): + try: + os.killpg(pid, sig) + except OSError: + try: + os.kill(pid, sig) + except OSError: + pass + os.waitpid(pid, 0) + status = -1 + break + time.sleep(0.0005) + if status != 0: + _sendall(sock, _HDR.pack(b"F") + _I32.pack(seed)) + _recv_exact(sock, 1) + _sendall(sock, _HDR.pack(b"Q") + _I32.pack(0)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/compute_reward.py b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..ca7be10f88d65f727c0e62b8b5c5b389c4a732bf --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,20 @@ +import json +import math +from pathlib import Path + +REWARD_PATH = Path("/logs/verifier/reward.txt") + +try: + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + payload = json.loads(Path("/logs/verifier/metric.json").read_text()) + if not payload.get("valid", False): + raise ValueError(f"invalid submission: {payload.get('reason')}") + value = float(payload["reward"]) + if not math.isfinite(value): + raise ValueError("non-finite reward") + reward = f"{min(1.0, max(0.0, value)):.12g}" + REWARD_PATH.write_text(reward + "\n") + print(f"reward={reward}") +except Exception as exc: + REWARD_PATH.write_text("0\n") + print(f"reward=0 (fallback: {exc})") diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/grader_core.py b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..271ec8a8cee58fe2b20c7c6a937f457c6a3c3ce9 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,79 @@ +import hashlib +import math + +import numpy as np + +BUDGETS = (50, 100, 200, 400) +N_SEEDS = 4000 +PER_SEED_TIMEOUT_S = 5.0 +PER_CELL_TIMEOUT_S = 900.0 +SE_CAP = 100.0 +RATIO_CAP = 1.0e4 + +M0 = 1.0 +BASELINE_SCORE = 0.68 +HIGHER_IS_BETTER = False + +_SALT = "2508-09093/label-efficient-risk-estimator/v1" + + +def cell_seed(instance_id: str, budget: int) -> int: + """Deterministic per-cell seed. Identical on both sides of the socket.""" + h = hashlib.sha256(f"{_SALT}|{instance_id}|{budget}".encode()).digest() + return int.from_bytes(h[:8], "big") + + +def seed_permutation(cseed: int, seed: int, n_pool: int) -> np.ndarray: + """Row order the candidate sees for this (cell, seed). Defeats any {row -> label} cache.""" + return np.random.default_rng([cseed, seed, 0x5EED]).permutation(n_pool) + + +def exact_risk(target_probs: np.ndarray, labels: np.ndarray) -> float: + """R = (1/N) sum_i -log target_probs[i, y_i] over the WHOLE pool.""" + p = target_probs[np.arange(labels.shape[0]), labels] + return float(np.mean(-np.log(np.clip(p, 1e-300, None)))) + + +def reference_squared_errors(target_probs, labels, budget, cseed, seeds): + """Uniform-random acquisition + plain sample mean, on the same seeds and the same + permuted view the candidate is given. This is the metric's denominator.""" + n_pool = labels.shape[0] + risk = exact_risk(target_probs, labels) + nll = -np.log(np.clip(target_probs[np.arange(n_pool), labels], 1e-300, None)) + out = np.empty(len(seeds), dtype=np.float64) + for k, s in enumerate(seeds): + perm = seed_permutation(cseed, s, n_pool) + nll_perm = nll[perm] + rng = np.random.default_rng([cseed, s]) + idx = rng.choice(n_pool, size=budget, replace=False) + out[k] = (float(np.mean(nll_perm[idx])) - risk) ** 2 + return out + + +def cell_ratio(agent_se: np.ndarray, ref_se: np.ndarray) -> float: + """median-over-seeds squared error of the candidate, divided by the reference's.""" + num = float(np.median(agent_se)) + den = float(np.median(ref_se)) + if not math.isfinite(den) or den <= 0.0: + den = 1e-12 + return float(min(RATIO_CAP, num / den)) + + +def aggregate(cell_ratios) -> float: + """The graded metric: the median of the per-cell ratios.""" + vals = np.asarray(list(cell_ratios), dtype=np.float64) + if vals.size == 0 or not np.all(np.isfinite(vals)): + return float(RATIO_CAP) + return float(np.median(vals)) + + +def graded_reward(metric: float, valid: bool) -> float: + """rational_squash on two task-derived anchors. Clamped again in compute_reward.py.""" + if not valid or metric is None or not math.isfinite(metric): + return 0.0 + sigma = 1.0 if HIGHER_IS_BETTER else -1.0 + x = sigma * (metric - M0) + x_ref = sigma * (BASELINE_SCORE - M0) + assert x_ref > 0, "malformed task: the anchor does not beat the trivial baseline" + u = max(0.0, x) / x_ref + return u / (1.0 + u) diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/labels.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..a426b0b7e49219475f9635d71b6c1611e38a0423 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a8dff3df8f6fe7a9e7ff5ed5edb178a2b98ec1f126a5e8917b611ed281e8a8a +size 16128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/meta.json b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/meta.json new file mode 100644 index 0000000000000000000000000000000000000000..18c2d321faccc6765b10c0a2982563b228d68c84 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/meta.json @@ -0,0 +1 @@ +{"pool_id": "pool01", "n_pool": 2000, "n_classes": 2} \ No newline at end of file diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/surrogate_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/surrogate_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..9acf8aefaf7dd3058173318897476653861b4e08 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/surrogate_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ae14107d3dbcec2ed1b2f953dffb0d865ee719797e690a97fff5cac5948f9d7 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/target_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/target_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..3e240d4cdc789e9ecb9188c7fb7017c155a77f10 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/target_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0420c93f9d48642ab0d63708c1ec50be496c832757735d4894bd9d617d51bac0 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/labels.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..081889738d15d77cac3765e57270d2b7358f178d --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc6cabb575d3c13c53555ce23580a7b761ab0c86011249ef6f9a11df9e20df1b +size 16128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/meta.json b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/meta.json new file mode 100644 index 0000000000000000000000000000000000000000..a279a2cc0bcfd366920f41344810c556f0a5494a --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/meta.json @@ -0,0 +1 @@ +{"pool_id": "pool02", "n_pool": 2000, "n_classes": 2} \ No newline at end of file diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/surrogate_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/surrogate_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..9fe97b17305896c7f57f30e1fe2be0f59260b38c --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/surrogate_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a649eb72f08691a25e469f81971a99b75e5ad778ec183c5daec53d4e7d66421a +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/target_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/target_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..d4946c4fd76296f14d78681ec1e3b879b2693399 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/target_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:044c8ff01b0a345c21dcf267104a55659c059165d3aba899bc2757589a482643 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/labels.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..dabc752ed758967d372432cfb4d2719db68f02d3 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:acb1e8f224bed55336d0a2b34fb52dbf358fee6756cb8da1c433338b47e52cc7 +size 16128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/meta.json b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/meta.json new file mode 100644 index 0000000000000000000000000000000000000000..3f64d3fd46d52863735a485b14b5f814c8c2013b --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/meta.json @@ -0,0 +1 @@ +{"pool_id": "pool04", "n_pool": 2000, "n_classes": 2} \ No newline at end of file diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/surrogate_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/surrogate_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..ace6da02a8afde588fe9d4faa1a935bc0316740d --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/surrogate_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:793c086283dafeabc146cf930f6d9ebcf81f87bc61dff174c0be7a544ea82015 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/target_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/target_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..630a9a1f5207fc8d688edb84bdf74b65c4e8f64d --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/target_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9f11869708df4edc13bd2cdaf01f556317d6552e835ee7fcffb27dddc440e65 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/labels.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..a426b0b7e49219475f9635d71b6c1611e38a0423 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a8dff3df8f6fe7a9e7ff5ed5edb178a2b98ec1f126a5e8917b611ed281e8a8a +size 16128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/meta.json b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/meta.json new file mode 100644 index 0000000000000000000000000000000000000000..18e5f76a2f739a021a727f520236cb0a4bd8d719 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/meta.json @@ -0,0 +1 @@ +{"pool_id": "pool07", "n_pool": 2000, "n_classes": 2} \ No newline at end of file diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/surrogate_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/surrogate_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..9acf8aefaf7dd3058173318897476653861b4e08 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/surrogate_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ae14107d3dbcec2ed1b2f953dffb0d865ee719797e690a97fff5cac5948f9d7 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/target_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/target_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..84d3c59f46bd6b4c6cbaa470038b6b4519cf9a4e --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/target_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d821ed4c955b7e246292f3d6f22f9657f12c3c4b4fe3bb81e9c57c10d56e6740 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/labels.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..857e71e7323183562eb03d28e1f960a40251ea45 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:179ab42ad9ed2a7fcb4f0cdafb076bcfc35ce161a8687715c753770448744700 +size 16128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/meta.json b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/meta.json new file mode 100644 index 0000000000000000000000000000000000000000..199f489ebfb19dec50ff004beed49f621189ded7 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/meta.json @@ -0,0 +1 @@ +{"pool_id": "pool00", "n_pool": 2000, "n_classes": 2} \ No newline at end of file diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/surrogate_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/surrogate_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..c07d591840d8172132c79128d424e555da740bd2 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/surrogate_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:994d602d6b276632b059555ac14fc91bb549225b8c91e85fd2d7b78e96eb2d56 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/target_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/target_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..56df5980f1601d268036969f37190b2004c974d0 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/target_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5fb01211123bf70da5cf0b5109e51643c38e7f7b34de104178a61c94e3ef3579 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/labels.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..eb65a4779e327344710307d1dfc1dae6e437f270 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19110f7553e90eab5a2aff29615133dca46655ccb270a67e0a8e6a0d56ee7f9b +size 16128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/meta.json b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/meta.json new file mode 100644 index 0000000000000000000000000000000000000000..ab85a1c38952b255e1a8da29b149cc6f71e1acb6 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/meta.json @@ -0,0 +1 @@ +{"pool_id": "pool03", "n_pool": 2000, "n_classes": 2} \ No newline at end of file diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/surrogate_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/surrogate_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..328b9c0e8866a3cffe6c8bbc416b1bc94ef0a3d5 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/surrogate_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88f687bdcaf414d53554563a8b084f696a00ecfb6f047aab86631c760ace8d39 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/target_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/target_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..c0e1d570be3b843f997f70d7d57dfd7553c3db8c --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/target_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00002ad5d2699c949ae50b950559145c79dd92db9025b1c0b2ee27ae8de53b7e +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/labels.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..857e71e7323183562eb03d28e1f960a40251ea45 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:179ab42ad9ed2a7fcb4f0cdafb076bcfc35ce161a8687715c753770448744700 +size 16128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/meta.json b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/meta.json new file mode 100644 index 0000000000000000000000000000000000000000..a9c33d1eedbbe5de80db0aa717d7a5c7726a55a9 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/meta.json @@ -0,0 +1 @@ +{"pool_id": "pool05", "n_pool": 2000, "n_classes": 2} \ No newline at end of file diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/surrogate_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/surrogate_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..c07d591840d8172132c79128d424e555da740bd2 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/surrogate_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:994d602d6b276632b059555ac14fc91bb549225b8c91e85fd2d7b78e96eb2d56 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/target_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/target_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..477c31bfb9fb9bde5983568872037e062f6ccf1b --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/target_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f90902a1c70205718cb080ae1fe17c44426a71ce6d751e09b52e795e229f546b +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/labels.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..857e71e7323183562eb03d28e1f960a40251ea45 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:179ab42ad9ed2a7fcb4f0cdafb076bcfc35ce161a8687715c753770448744700 +size 16128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/meta.json b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/meta.json new file mode 100644 index 0000000000000000000000000000000000000000..1740887d08a6455582614b6dc49f9b5a9b08357b --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/meta.json @@ -0,0 +1 @@ +{"pool_id": "pool06", "n_pool": 2000, "n_classes": 2} \ No newline at end of file diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/surrogate_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/surrogate_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..c07d591840d8172132c79128d424e555da740bd2 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/surrogate_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:994d602d6b276632b059555ac14fc91bb549225b8c91e85fd2d7b78e96eb2d56 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/target_probs.npy b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/target_probs.npy new file mode 100644 index 0000000000000000000000000000000000000000..43d5cff477aac3934fd8d4a8c2d5ff2d1f15f40d --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/target_probs.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89f71218e7112cf1949f2777fa0a6f8686cf48347ac7f9ac374011a65cd2c291 +size 32128 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/intermediate.sh b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..579e3de95bbb51d22da83458bf93204b3e5ca476 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +printf '0\n' > /logs/verifier/reward.txt +trap '[ -s /logs/verifier/reward.txt ] || printf "0\n" > /logs/verifier/reward.txt' EXIT + +chmod -R go-rwx /tests + +cd /tests +export GRADE_SPLIT=intermediate +/usr/local/bin/python3 -m pytest \ + --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +/usr/local/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/requirements-verifier.txt b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..04676c89520bf969f2cb861ad1811f46d8370700 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/requirements-verifier.txt @@ -0,0 +1,2 @@ +pytest==8.3.5 +pytest-json-ctrf==0.3.5 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/requirements.txt b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..7f2a0d4123a6443051ec64e916557b9244bfad8c --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,2 @@ +numpy==2.3.2 +scipy==1.16.1 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test.sh b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c506c2fe714c7b7890c83c00f1b8cff2dc2ffeb4 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +printf '0\n' > /logs/verifier/reward.txt +trap '[ -s /logs/verifier/reward.txt ] || printf "0\n" > /logs/verifier/reward.txt' EXIT + +chmod -R go-rwx /tests + +cd /tests +export GRADE_SPLIT=final +/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json \ + /tests/test_state.py -rA +/usr/local/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test_state.py b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..b55c939cd49bf0143ac7321761a93d605dd732c8 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test_state.py @@ -0,0 +1,319 @@ +import json +import os +import shutil +import socket +import struct +import subprocess +import sys +import tempfile +import time +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import grader_core as GC + +PY = "/usr/local/bin/python3" +TESTS_DIR = Path(__file__).resolve().parent +RUNNER_SRC = TESTS_DIR / "candidate_runner.py" +DELIVERABLE_DIR = Path("/app/output") +ENTRY_NAME = "estimator.py" +STAGE = Path("/grade_run") +LOGS = Path("/logs/verifier") +AGENT_UID, AGENT_GID = 1001, 1001 +MAX_SUBMISSION_BYTES = 256 * 1024 * 1024 +MAX_SUBMISSION_FILES = 2000 + +_HDR = struct.Struct(" 1: + return None, f"hard link in the deliverable tree: {p}" + if p.is_file(): + total += st.st_size + count += 1 + elif not p.is_dir(): + return None, f"not a regular file or directory: {p}" + if count == 0: + return None, "the deliverable directory is empty" + if total > MAX_SUBMISSION_BYTES or count > MAX_SUBMISSION_FILES: + return None, f"deliverable too large: {count} files, {total} bytes" + shutil.copytree(DELIVERABLE_DIR, dest, symlinks=True) + for root, dirs, files in os.walk(dest): + os.chmod(root, 0o755) + for name in files: + os.chmod(Path(root) / name, 0o644) + entry = dest / ENTRY_NAME + if entry.is_symlink() or not entry.is_file() or entry.stat().st_size == 0: + return None, f"missing or empty entry point {DELIVERABLE_DIR / ENTRY_NAME}" + return dest, None + + +def seal_filesystem(): + """Leave uid 1001 no writable directory, so no candidate state can survive a seed.""" + for path in ("/tmp", "/var/tmp", "/dev/shm", "/home/agent", "/app", "/app/output"): + try: + os.chown(path, 0, 0) + os.chmod(path, 0o755) + except OSError: + pass + + +def _launch_runner(cell_dir, submission_dir, budget, cseed, n_seeds, seed0, child_fd): + argv = [PY, "-I", str(cell_dir / "candidate_runner.py"), + "--pool", str(cell_dir / "pool.npz"), + "--submission-dir", str(submission_dir), + "--entry", str(Path(submission_dir) / ENTRY_NAME), + "--budget", str(budget), "--seeds", str(n_seeds), + "--seed-start", str(seed0), + "--cell-seed", str(cseed), + "--per-seed-timeout", str(GC.PER_SEED_TIMEOUT_S), + "--sock-fd", str(child_fd)] + env = {"PATH": "/usr/local/bin:/usr/bin:/bin", "HOME": "/home/agent", + "TMPDIR": "/nonexistent", "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONSAFEPATH": "1", "PYTHONHASHSEED": "0", "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", "LC_ALL": "C"} + err = subprocess.DEVNULL + if os.environ.get("GRADE_DEBUG"): + err = open(Path(cell_dir) / "candidate_stderr.log", "wb") + prefix = [] + for cand, args in (("/usr/sbin/runuser", ["-u", "agent", "--"]), + ("/usr/bin/setpriv", [f"--reuid={AGENT_UID}", + f"--regid={AGENT_GID}", "--clear-groups", "--"])): + if os.path.exists(cand): + prefix = [cand] + args + break + kwargs = {} + if not prefix: + kwargs = {"user": AGENT_UID, "group": AGENT_GID, "extra_groups": []} + return subprocess.Popen(prefix + argv, env=env, start_new_session=True, + pass_fds=(child_fd,), stdout=subprocess.DEVNULL, + stderr=err, cwd=str(cell_dir), **kwargs) + + +def _serve(sock, labels, budget, cseed, seeds, deadline): + """Label oracle. Enforces the budget and the one-shot, in-order seed protocol.""" + n_pool = labels.shape[0] + estimates, used, answered, perm = {}, 0, True, None + expected = list(seeds) + pos, current = 0, None + violation = None + try: + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + violation = "cell wall-clock budget exhausted" + break + sock.settimeout(remaining) + head = sock.recv(1) + if not head: + break + if head == b"S": + s = _I32.unpack(_recv_exact(sock, 4))[0] + if pos >= len(expected) or s != expected[pos]: + violation = f"out-of-order seed handshake: {s} after {current}" + break + current, used, answered = s, 0, False + pos += 1 + perm = GC.seed_permutation(cseed, s, n_pool) + sock.sendall(b"\x01") + elif head == b"L": + j = _I32.unpack(_recv_exact(sock, 4))[0] + if answered or used >= budget or not (0 <= j < n_pool): + sock.sendall(_I32.pack(-1)) + else: + used += 1 + sock.sendall(_I32.pack(int(labels[perm[j]]))) + elif head == b"R": + s = _I32.unpack(_recv_exact(sock, 4))[0] + v = _F64.unpack(_recv_exact(sock, 8))[0] + if s != current or answered: + violation = f"duplicate or stray result for seed {s}" + sock.sendall(b"\x01") + break + estimates[s], answered = v, True + sock.sendall(b"\x01") + elif head == b"F": + _recv_exact(sock, 4) + answered = True + sock.sendall(b"\x01") + elif head == b"Q": + _recv_exact(sock, 4) + break + else: + violation = f"unknown opcode {head!r}" + break + except (socket.timeout, ConnectionError, OSError, struct.error) as exc: + if violation is None and len(estimates) < len(expected): + violation = f"label channel ended early ({type(exc).__name__})" + return estimates, violation + + +def _recv_exact(sock, n): + buf = b"" + while len(buf) < n: + chunk = sock.recv(n - len(buf)) + if not chunk: + raise ConnectionError("candidate closed the label channel") + buf += chunk + return buf + + +def grade_cell(job): + """Runs in a root worker process. Returns the cell's ratio and diagnostics. + + Any failure inside this worker is reported as a worst-case cell rather than being + allowed to abort the grade, so the reward path always reaches compute_reward.py. + """ + try: + return _grade_cell(job) + except Exception as exc: + return {"instance": job[1], "budget": job[2], "risk": None, + "ratio": GC.RATIO_CAP, "n_ok": 0, "n_seeds": job[4], + "violation": f"scorer error: {type(exc).__name__}: {exc}"} + + +def _grade_cell(job): + inst_dir, instance_id, budget, submission_dir, n_seeds, seed0 = job + inst_dir = Path(inst_dir) + target = np.load(inst_dir / "target_probs.npy").astype(np.float64) + surrogate = np.load(inst_dir / "surrogate_probs.npy").astype(np.float64) + labels = np.load(inst_dir / "labels.npy").astype(np.int64) + cseed = GC.cell_seed(instance_id, budget) + risk = GC.exact_risk(target, labels) + seeds = list(range(seed0, seed0 + n_seeds)) + ref_se = GC.reference_squared_errors(target, labels, budget, cseed, seeds) + + cell_dir = Path(tempfile.mkdtemp(prefix=f"cell_{instance_id}_{budget}_", dir=str(STAGE))) + os.chmod(cell_dir, 0o755) + np.savez(cell_dir / "pool.npz", target_probs=target, surrogate_probs=surrogate) + shutil.copy2(RUNNER_SRC, cell_dir / "candidate_runner.py") + os.chmod(cell_dir / "pool.npz", 0o644) + os.chmod(cell_dir / "candidate_runner.py", 0o644) + + parent_sock, child_sock = socket.socketpair() + proc = None + try: + proc = _launch_runner(cell_dir, submission_dir, budget, cseed, n_seeds, seed0, + child_sock.fileno()) + child_sock.close() + estimates, violation = _serve(parent_sock, labels, budget, cseed, seeds, + time.monotonic() + GC.PER_CELL_TIMEOUT_S) + finally: + if os.environ.get("GRADE_DEBUG"): + try: + tail = (cell_dir / "candidate_stderr.log").read_bytes()[-4000:] + if tail: + print(f"[stderr {instance_id} M={budget}]\n{tail.decode(errors='replace')}") + except OSError: + pass + try: + parent_sock.close() + except OSError: + pass + if proc is not None: + try: + os.killpg(os.getpgid(proc.pid), 9) + except OSError: + pass + try: + proc.wait(timeout=30) + except Exception: + pass + shutil.rmtree(cell_dir, ignore_errors=True) + + agent_se = np.full(n_seeds, GC.SE_CAP, dtype=np.float64) + if violation is None: + for s, v in estimates.items(): + k = s - seed0 + if 0 <= k < n_seeds and np.isfinite(v): + agent_se[k] = min(GC.SE_CAP, (float(v) - risk) ** 2) + n_ok = int(np.sum(agent_se < GC.SE_CAP)) + return {"instance": instance_id, "budget": budget, "risk": risk, + "ratio": GC.cell_ratio(agent_se, ref_se), "n_ok": n_ok, + "n_seeds": n_seeds, "violation": violation} + + +def _write_metric(payload): + LOGS.mkdir(parents=True, exist_ok=True) + (LOGS / "metric.json").write_text(json.dumps(payload, indent=2, sort_keys=True)) + + +def test_reward(): + """Execute the candidate estimator over every sealed cell and write metric.json. + + WHAT: drives the candidate's /app/output/estimator.py through the full adaptive + acquisition protocol on the sealed pools, computes the median relative + risk-estimation error against the verifier's own uniform-random reference, and maps + it to the graded reward. + WHY: the reward has to come from EXECUTING candidate code on inputs that were never + in the agent image, never from reading a file the candidate wrote. + """ + split = os.environ.get("GRADE_SPLIT", "final") + hidden = TESTS_DIR / "hidden_data" / split + n_seeds = int(os.environ.get("GRADE_SEEDS", GC.N_SEEDS)) + seed0 = int(os.environ.get("GRADE_SEED_OFFSET", 0)) + STAGE.mkdir(parents=True, exist_ok=True) + os.chmod(STAGE, 0o755) + + submission_dir, reason = harvest_submission() + if submission_dir is None: + _write_metric({"valid": False, "reason": reason, "reward": 0.0, + "metric": None, "split": split}) + print(f"INVALID SUBMISSION: {reason}") + assert False, reason + + seal_filesystem() + instances = sorted(p for p in hidden.iterdir() if p.is_dir()) + assert instances, f"no sealed instances under {hidden}" + jobs = [(str(p), p.name, b, str(submission_dir), n_seeds, seed0) + for p in instances for b in GC.BUDGETS] + + workers = min(8, len(jobs)) + with ProcessPoolExecutor(max_workers=workers) as pool: + cells = list(pool.map(grade_cell, jobs)) + + metric = GC.aggregate(c["ratio"] for c in cells) + reward = GC.graded_reward(metric, valid=True) + _write_metric({"valid": True, "split": split, "metric": metric, "reward": reward, + "n_seeds": n_seeds, "seed_offset": seed0, + "cells": cells}) + if split != "intermediate": + for c in sorted(cells, key=lambda c: (c["instance"], c["budget"])): + print(f" {c['instance']:>16s} M={c['budget']:>3d} " + f"relative_error={c['ratio']:.4f} seeds_ok={c['n_ok']}/{c['n_seeds']}" + + (f" [{c['violation']}]" if c["violation"] else "")) + print(f"median relative risk-estimation error = {metric:.4f} " + f"over {len(cells)} cells") + assert np.isfinite(metric) + + +if __name__ == "__main__": + test_reward() diff --git a/tasks/label-efficient-risk-estimator/environment/docker-compose.yaml b/tasks/label-efficient-risk-estimator/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..90f3fa61e89f74d452904b6a982a245f66104fd5 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/environment/docker-compose.yaml @@ -0,0 +1,76 @@ +# ARE 1.1: grading lives in sidecars. Harbor configures `main` (build, limits, network). +services: + main: + depends_on: + grader: + condition: service_healthy + volumes: + - are-deliverable-0:/app/output + + grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: val + platform: linux/amd64 + environment: + ARE_ROLE: val + ARE_PORT: "8000" + ARE_BUDGET_SEC: "86400" + ARE_ARTIFACT_PATHS: "/app/output" + ARE_AGENT_UID: "1001" + ARE_GRADE_TIMEOUT_SEC: "2700" + volumes: + - are-deliverable-0:/run/are-deliverable/app/output + - are-secret:/run/are-secret + expose: + - "8000" + cap_add: [SYS_ADMIN] + networks: [default, are-private] + cpus: 8 + mem_limit: 14336m + depends_on: + test-grader: + condition: service_healthy + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + + test-grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: test + platform: linux/amd64 + environment: + ARE_ROLE: test + ARE_PORT: "8001" + ARE_ARTIFACT_PATHS: "/app/output" + ARE_GRADE_TIMEOUT_SEC: "2700" + expose: + - "8001" + volumes: + - are-secret:/run/are-secret + cap_add: [SYS_ADMIN] + networks: [are-private] + cpus: 8 + mem_limit: 14336m + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8001/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + +volumes: + are-deliverable-0: {} + are-secret: {} + +networks: + are-private: + internal: true diff --git a/tasks/label-efficient-risk-estimator/task.toml b/tasks/label-efficient-risk-estimator/task.toml index f03fcd98040a5f8ca85a0f27ae474f9ec1c1f248..e6a33eef036b7f6e83ab4f52c83906b1643e7aa6 100644 --- a/tasks/label-efficient-risk-estimator/task.toml +++ b/tasks/label-efficient-risk-estimator/task.toml @@ -1,56 +1,70 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/label-efficient-risk-estimator" -version = "1.0.0" +version = "1.1.0" description = "" -keywords = [ "autoresearch", "machine-learning", "benchmark",] -[[task.authors]] -name = "Bespoke Labs" +keywords = [ + "autoresearch", + "machine-learning", + "benchmark", +] +authors = [ + { name = "Bespoke Labs" }, +] [metadata] category = "Machine Learning and AI" subcategory = "Evaluation, Calibration, and Robustness" -task_objective = [ "Implement", "Optimize",] -artifact_type = [ "Single script or program",] +task_objective = [ + "Implement", + "Optimize", +] +artifact_type = [ + "Single script or program", +] expert_time_estimate_hours = 4.0 +are_version = "1.1" +budget_seconds = 86400 [verifier] -timeout_sec = 2700.0 +timeout_sec = 600.0 environment_mode = "separate" -collect = [] -[verifier.env] +[[verifier.collect]] +service = "grader" +command = "/opt/are/venv/bin/python /opt/are/drain.py" +timeout_sec = 5400.0 [verifier.environment] network_mode = "no-network" -build_timeout_sec = 3600.0 -os = "linux" -cpus = 8 -memory_mb = 14336 -storage_mb = 153600 +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 gpus = 0 -mcp_servers = [] - -[verifier.environment.env] [agent] network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] -timeout_sec = 14400.0 +allowed_hosts = [ + "api.openai.com", + "api.anthropic.com", + "grader", +] +timeout_sec = 86400.0 [environment] -network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] +network_mode = "public" build_timeout_sec = 3600.0 os = "linux" cpus = 8 memory_mb = 14336 storage_mb = 153600 gpus = 0 -mcp_servers = [] +mcp_servers = [ + { name = "are", transport = "streamable-http", url = "http://grader:8000/mcp" }, +] [environment.env] - -[solution.env] diff --git a/tasks/label-efficient-risk-estimator/tests/Dockerfile b/tasks/label-efficient-risk-estimator/tests/Dockerfile index 9e76d946f050135140319a5b3b347150a25c2aa2..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/label-efficient-risk-estimator/tests/Dockerfile +++ b/tasks/label-efficient-risk-estimator/tests/Dockerfile @@ -1,34 +1,2 @@ -FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb - -ENTRYPOINT [] -ENV PYTHONPATH= -ENV PYTHONSAFEPATH=1 -ENV DEBIAN_FRONTEND=noninteractive \ - PYTHONHASHSEED=0 \ - PIP_NO_CACHE_DIR=1 \ - PIP_DISABLE_PIP_VERSION_CHECK=1 \ - OMP_NUM_THREADS=1 \ - MKL_NUM_THREADS=1 \ - OPENBLAS_NUM_THREADS=1 - -RUN useradd --create-home --uid 1001 agent - -COPY ./requirements.txt /tmp/requirements.txt -COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt -RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ - -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ - && rm /tmp/requirements.txt /tmp/requirements-verifier.txt - -RUN mkdir -p /app/output /logs/verifier /grade_run - -COPY . /tests - -RUN chown -R root:root /tests \ - && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ - && chmod +x /tests/test.sh /tests/intermediate.sh \ - && find /tests -exec touch -d @1700000000 {} + - -WORKDIR /tests - -ENV HF_HUB_OFFLINE=1 -ENV TRANSFORMERS_OFFLINE=1 +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/label-efficient-risk-estimator/tests/finalize.py b/tasks/label-efficient-risk-estimator/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/label-efficient-risk-estimator/tests/finalize.py @@ -0,0 +1,59 @@ +"""Final verifier: score the run from the grader ledger. + +reward hidden test score of the submission with the best validation score + (ties go to the earlier submission); 0 if nothing was submitted. +auarc area under the curve of that same quantity over the wall-clock budget, + using the time each validation score became available, divided by the + budget. 0 before the first graded submission. +""" + +import json +from pathlib import Path + +STATE = Path("/var/lib/are") +OUT = Path("/logs/verifier") +OUT.mkdir(parents=True, exist_ok=True) + +meta = json.loads((STATE / "meta.json").read_text()) if (STATE / "meta.json").exists() else {} +budget = float(meta.get("budget_seconds") or 1.0) + +subs: dict[int, dict] = {} +ledger = STATE / "ledger.jsonl" +for line in (ledger.read_text().splitlines() if ledger.exists() else []): + ev = json.loads(line) + s = subs.setdefault(ev["id"], {"id": ev["id"]}) + if ev["event"] == "submitted": + s["submitted_t"] = ev["t"] + elif ev["event"] == "val": + s["val"] = ev["score"] + s["val_t"] = ev["t"] + elif ev["event"] == "test": + s["test"] = ev["score"] + +graded = sorted((s for s in subs.values() if "val" in s), key=lambda s: s["val_t"]) + +# Step function of the hidden score of the best-validation pick over time. +auc, best, last_t, cur = 0.0, None, 0.0, 0.0 +timeline = [] +for s in graded: + t = min(s["val_t"], budget) + auc += cur * (t - last_t) + last_t = t + if best is None or s["val"] > best["val"] or (s["val"] == best["val"] and s["id"] < best["id"]): + best = s + cur = float(best.get("test") or 0.0) + timeline.append({"t": s["val_t"], "id": s["id"], "val": s["val"], "test": s.get("test"), + "pick": best["id"]}) +auc += cur * (budget - last_t) if last_t < budget else 0.0 + +reward = { + "reward": float(best.get("test") or 0.0) if best else 0.0, + "auarc": auc / budget, + "best_val": float(best["val"]) if best else 0.0, + "n_submissions": float(len(subs)), + "n_test_graded": float(sum(s.get("test") is not None for s in subs.values())), +} +(OUT / "reward.json").write_text(json.dumps(reward)) +(OUT / "timeline.json").write_text(json.dumps({"budget": budget, "selected": best and best["id"], + "submissions": timeline}, indent=1)) +print(json.dumps(reward, indent=1)) diff --git a/tasks/label-efficient-risk-estimator/tests/test.sh b/tasks/label-efficient-risk-estimator/tests/test.sh index c506c2fe714c7b7890c83c00f1b8cff2dc2ffeb4..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/label-efficient-risk-estimator/tests/test.sh +++ b/tasks/label-efficient-risk-estimator/tests/test.sh @@ -1,20 +1,2 @@ #!/bin/bash -set -u - -mkdir -p /logs/verifier -chown root:root /logs/verifier 2>/dev/null || true -chmod 755 /logs/verifier 2>/dev/null || true -rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json - -printf '0\n' > /logs/verifier/reward.txt -trap '[ -s /logs/verifier/reward.txt ] || printf "0\n" > /logs/verifier/reward.txt' EXIT - -chmod -R go-rwx /tests - -cd /tests -export GRADE_SPLIT=final -/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json \ - /tests/test_state.py -rA -/usr/local/bin/python3 /tests/compute_reward.py - -exit 0 +python3 /tests/finalize.py diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/.dockerignore b/tasks/less-is-more-pretrain-token-budget-selector/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/Dockerfile b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..54dfbc537d7eaabee396d24dbb1d8b1bf4a357d5 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,65 @@ +FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV PYTHONHASHSEED=0 \ + PYTHONDONTWRITEBYTECODE=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 \ + NUMEXPR_NUM_THREADS=1 \ + CUBLAS_WORKSPACE_CONFIG=:4096:8 \ + HF_HUB_DISABLE_PROGRESS_BARS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements-verifier.txt + +RUN /usr/bin/python3 -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='openai-community/gpt2', revision='607a30d783dfa663caf39e06633721c8d4cfcd7e', local_dir='/opt/assets/gpt2', allow_patterns=['config.json','generation_config.json','merges.txt','vocab.json','tokenizer.json','model.safetensors']); snapshot_download(repo_id='EleutherAI/pythia-160m', revision='50f5173d932e8e61f858120bcb800b97af589f46', local_dir='/opt/assets/pythia-160m', allow_patterns=['config.json','generation_config.json','tokenizer.json','tokenizer_config.json','special_tokens_map.json','model.safetensors'])" && rm -rf /opt/assets/gpt2/.cache /opt/assets/pythia-160m/.cache + +COPY . /tests + +RUN set -eux; \ + REV=1588ec454efa1a09f29cd18ddd04fe05fc8653a2; \ + B="https://huggingface.co/datasets/allenai/c4/resolve/$REV"; \ + TK=/opt/assets/gpt2/tokenizer.json; \ + mkdir -p /tmp/corpus /tests/hidden_data; \ + curl -sSL -o /tmp/corpus/valF.json.gz "$B/en/c4-validation.00003-of-00008.json.gz"; \ + curl -sSL -o /tmp/corpus/valI.json.gz "$B/en/c4-validation.00005-of-00008.json.gz"; \ + curl -sSL -o /tmp/corpus/trF0.json.gz "$B/en/c4-train.00777-of-01024.json.gz"; \ + curl -sSL -o /tmp/corpus/trF1.json.gz "$B/en/c4-train.00778-of-01024.json.gz"; \ + curl -sSL -o /tmp/corpus/ncF.json.gz "$B/en.noclean/c4-train.00777-of-07168.json.gz"; \ + curl -sSL -o /tmp/corpus/trI0.json.gz "$B/en/c4-train.00888-of-01024.json.gz"; \ + curl -sSL -o /tmp/corpus/trI1.json.gz "$B/en/c4-train.00889-of-01024.json.gz"; \ + curl -sSL -o /tmp/corpus/ncI.json.gz "$B/en.noclean/c4-train.00888-of-07168.json.gz"; \ + export TOKENIZERS_PARALLELISM=true; \ + /usr/bin/python3 /tests/build_data.py eval --shards /tmp/corpus/valF.json.gz \ + --out /tests/hidden_data/final/eval --tokenizer $TK --target-tokens 2000000; \ + /usr/bin/python3 /tests/build_data.py pool --shards /tmp/corpus/trF0.json.gz /tmp/corpus/trF1.json.gz \ + --shards-b /tmp/corpus/ncF.json.gz --target-tokens 250000000 --target-tokens-b 62500000 \ + --out /tests/hidden_data/final/pool --tokenizer $TK \ + --guard /tests/hidden_data/final/eval/guard.json; \ + /usr/bin/python3 /tests/build_data.py eval --shards /tmp/corpus/valI.json.gz \ + --out /tests/hidden_data/intermediate/eval --tokenizer $TK --target-tokens 2000000; \ + /usr/bin/python3 /tests/build_data.py pool --shards /tmp/corpus/trI0.json.gz /tmp/corpus/trI1.json.gz \ + --shards-b /tmp/corpus/ncI.json.gz --target-tokens 250000000 --target-tokens-b 62500000 \ + --out /tests/hidden_data/intermediate/pool --tokenizer $TK \ + --guard /tests/hidden_data/intermediate/eval/guard.json; \ + rm -rf /tmp/corpus + +RUN mkdir -p /app/output /logs/verifier + +RUN chown -R root:root /tests \ + && chmod 700 /tests/hidden_data \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/Dockerfile.are b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..f008e683c58edaa55f35e5e2bb432b1329218dfa --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,83 @@ +FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV PYTHONHASHSEED=0 \ + PYTHONDONTWRITEBYTECODE=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 \ + NUMEXPR_NUM_THREADS=1 \ + CUBLAS_WORKSPACE_CONFIG=:4096:8 \ + HF_HUB_DISABLE_PROGRESS_BARS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements-verifier.txt + +RUN /usr/bin/python3 -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='openai-community/gpt2', revision='607a30d783dfa663caf39e06633721c8d4cfcd7e', local_dir='/opt/assets/gpt2', allow_patterns=['config.json','generation_config.json','merges.txt','vocab.json','tokenizer.json','model.safetensors']); snapshot_download(repo_id='EleutherAI/pythia-160m', revision='50f5173d932e8e61f858120bcb800b97af589f46', local_dir='/opt/assets/pythia-160m', allow_patterns=['config.json','generation_config.json','tokenizer.json','tokenizer_config.json','special_tokens_map.json','model.safetensors'])" && rm -rf /opt/assets/gpt2/.cache /opt/assets/pythia-160m/.cache + +COPY . /tests + +RUN set -eux; \ + REV=1588ec454efa1a09f29cd18ddd04fe05fc8653a2; \ + B="https://huggingface.co/datasets/allenai/c4/resolve/$REV"; \ + TK=/opt/assets/gpt2/tokenizer.json; \ + mkdir -p /tmp/corpus /tests/hidden_data; \ + curl -sSL -o /tmp/corpus/valF.json.gz "$B/en/c4-validation.00003-of-00008.json.gz"; \ + curl -sSL -o /tmp/corpus/valI.json.gz "$B/en/c4-validation.00005-of-00008.json.gz"; \ + curl -sSL -o /tmp/corpus/trF0.json.gz "$B/en/c4-train.00777-of-01024.json.gz"; \ + curl -sSL -o /tmp/corpus/trF1.json.gz "$B/en/c4-train.00778-of-01024.json.gz"; \ + curl -sSL -o /tmp/corpus/ncF.json.gz "$B/en.noclean/c4-train.00777-of-07168.json.gz"; \ + curl -sSL -o /tmp/corpus/trI0.json.gz "$B/en/c4-train.00888-of-01024.json.gz"; \ + curl -sSL -o /tmp/corpus/trI1.json.gz "$B/en/c4-train.00889-of-01024.json.gz"; \ + curl -sSL -o /tmp/corpus/ncI.json.gz "$B/en.noclean/c4-train.00888-of-07168.json.gz"; \ + export TOKENIZERS_PARALLELISM=true; \ + /usr/bin/python3 /tests/build_data.py eval --shards /tmp/corpus/valF.json.gz \ + --out /tests/hidden_data/final/eval --tokenizer $TK --target-tokens 2000000; \ + /usr/bin/python3 /tests/build_data.py pool --shards /tmp/corpus/trF0.json.gz /tmp/corpus/trF1.json.gz \ + --shards-b /tmp/corpus/ncF.json.gz --target-tokens 250000000 --target-tokens-b 62500000 \ + --out /tests/hidden_data/final/pool --tokenizer $TK \ + --guard /tests/hidden_data/final/eval/guard.json; \ + /usr/bin/python3 /tests/build_data.py eval --shards /tmp/corpus/valI.json.gz \ + --out /tests/hidden_data/intermediate/eval --tokenizer $TK --target-tokens 2000000; \ + /usr/bin/python3 /tests/build_data.py pool --shards /tmp/corpus/trI0.json.gz /tmp/corpus/trI1.json.gz \ + --shards-b /tmp/corpus/ncI.json.gz --target-tokens 250000000 --target-tokens-b 62500000 \ + --out /tests/hidden_data/intermediate/pool --tokenizer $TK \ + --guard /tests/hidden_data/intermediate/eval/guard.json; \ + rm -rf /tmp/corpus + +RUN mkdir -p /app/output /logs/verifier + +RUN chown -R root:root /tests \ + && chmod 700 /tests/hidden_data \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 + + +# ---- ARE 1.1 grader layer (appended to the task's own verifier Dockerfile) ---- +ARG ARE_ROLE +# python.org images ship /usr/local/bin/python3; distro-python bases (kaggle GPU) lack +# ensurepip, so fall back to a pip-less venv filled by the base interpreter's pip. +RUN PY=$(command -v /usr/local/bin/python3 || command -v python3) \ + && if "$PY" -m venv /opt/are/venv; then \ + /opt/are/venv/bin/pip install --no-cache-dir "fastmcp==2.14.7"; \ + else rm -rf /opt/are/venv && "$PY" -m venv --without-pip /opt/are/venv \ + && "$PY" -m pip --python /opt/are/venv/bin/python install --no-cache-dir "fastmcp==2.14.7"; fi +COPY are/ /opt/are/ +# The val grader, whose output reaches the agent, never holds the private grader or its +# data. The test grader keeps everything; nothing from it reaches the agent. +RUN rm -rf /tests/are /tests/Dockerfile.are \ + && if [ "$ARE_ROLE" = "val" ]; then rm -rf /tests/test.sh /tests/hidden_data/final; fi +ENV ARE_ROLE=$ARE_ROLE +CMD ["/opt/are/venv/bin/python", "/opt/are/server.py"] diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/are/drain.py b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/are/drain.py @@ -0,0 +1,25 @@ +"""Verifier collect hook, run after the agent stops. + +Grades the final workspace as one last submission (unless it equals the last one), +then waits until every submission has both grades recorded. +""" + +import json +import time +import urllib.request +from pathlib import Path + +TOKEN = Path("/run/are-secret/token").read_text().strip() +H = {"x-are-token": TOKEN} + +req = urllib.request.Request("http://localhost:8000/final", method="POST", headers=H) +with urllib.request.urlopen(req, timeout=120) as resp: + print("final:", json.loads(resp.read()), flush=True) + +while True: + with urllib.request.urlopen(urllib.request.Request("http://localhost:8000/drain", headers=H), timeout=30) as resp: + state = json.loads(resp.read()) + print(state, flush=True) + if state["val_pending"] == 0 and state["test_pending"] == 0: + break + time.sleep(5) diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/are/server.py b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/are/server.py @@ -0,0 +1,538 @@ +"""ARE 1.1 grader sidecar. + +One image, two roles: + +- ARE_ROLE=val ("grader" service). Reachable from the agent. Serves MCP tools and a + REST fallback. On submit it snapshots the shared deliverable volume, grades the + snapshot with the task's public grader (intermediate.sh), and returns only that + score. Every snapshot is also sent to the test grader; the hidden score goes to a + root-only ledger and never back to the agent. +- ARE_ROLE=test ("test-grader" service). On a private network that only the val + grader can reach. Grades snapshots with the task's private grader (test.sh). +""" + +from __future__ import annotations + +import asyncio +import gzip +import hashlib +import io +import secrets +import json +import os +import queue +import shutil +import subprocess +import tarfile +import threading +import time +import urllib.request +from pathlib import Path + +from fastmcp import FastMCP +from starlette.requests import Request +from starlette.responses import JSONResponse, Response + +ROLE = os.environ.get("ARE_ROLE", "val") +PORT = int(os.environ.get("ARE_PORT", "8000")) +STATE = Path(os.environ.get("ARE_STATE_DIR", "/var/lib/are")) +ARTIFACT_PATHS = [p for p in os.environ.get("ARE_ARTIFACT_PATHS", "/app/output").split(":") if p] +# The shared deliverable volume. Its parent is root-only, so submitted code (which every +# task grader runs as the unprivileged agent user) cannot reach it to write back to the agent. +SUBMISSION_ROOT = Path(os.environ.get("ARE_SUBMISSION_ROOT", "/run/are-deliverable")) +AGENT_UID = int(os.environ.get("ARE_AGENT_UID", "1001")) +BUDGET_SEC = float(os.environ.get("ARE_BUDGET_SEC", "14400")) +GRADE_TIMEOUT_SEC = float(os.environ.get("ARE_GRADE_TIMEOUT_SEC", "1800")) +TEST_GRADER_URL = os.environ.get("ARE_TEST_GRADER_URL", "http://test-grader:8001") +FEEDBACK_TAIL = int(os.environ.get("ARE_FEEDBACK_TAIL_CHARS", "8192")) +SCRIPT = "/tests/intermediate.sh" if ROLE == "val" else "/tests/test.sh" +# Shared only by the two graders (a volume the agent's container never mounts). The test +# grader writes a fresh token at startup; every internal request must carry it, so the +# agent cannot reach the test grader or the internal endpoints even on a shared network. +TOKEN_FILE = Path(os.environ.get("ARE_TOKEN_FILE", "/run/are-secret/token")) +TOKEN = "" + + +def _authorized(request: Request) -> bool: + """Internal endpoints need the graders' token; an unset token never matches.""" + return bool(TOKEN) and secrets.compare_digest(request.headers.get("x-are-token", ""), TOKEN) + + +def _net_isolation_available() -> bool: + try: + return subprocess.run(["unshare", "-n", "true"], capture_output=True, timeout=10).returncode == 0 + except Exception: + return False + + +NET_ISOLATED = False # set at startup: grader scripts run in an empty network namespace + +T0 = time.time() +_lock = threading.Lock() + + +def _elapsed() -> float: + return round(time.time() - T0, 1) + + +def _ledger(event: dict) -> None: + event = {"t": _elapsed(), "wall": time.time(), **event} + for attempt in range(3): + try: + with _lock, open(STATE / "ledger.jsonl", "a") as fh: + fh.write(json.dumps(event) + "\n") + return + except OSError: + if attempt == 2: + raise + time.sleep(1) + + +def _kill_grading_processes(proc: subprocess.Popen) -> None: + """Kill everything a timed-out grade started, including processes that left its group.""" + try: + os.killpg(proc.pid, 9) + except ProcessLookupError: + pass + _kill_other_processes() + + +def _kill_other_processes() -> None: + """Kill every process run by the agent user. Every task grader runs submitted code as + that user, so this stops all graded code (detached or not) and nothing else: the grader + server, the task's own grader and Harbor's hooks run as root.""" + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + if entry.stat().st_uid == AGENT_UID: + os.kill(int(entry.name), 9) + except (ProcessLookupError, PermissionError, FileNotFoundError): + pass + + +# Places the agent user (who runs submitted code inside every task grader) can write. +_BASELINE: set[str] = set() # every path that existed when the grader started (its image) + + +def _walk_one_fs(base: Path): + """Every path under base on base's own filesystem (skips /proc, /sys and other mounts).""" + dev = base.stat().st_dev + for root, dirs, files in os.walk(base): + dirs[:] = [d for d in dirs if os.lstat(os.path.join(root, d)).st_dev == dev] + for name in dirs + files: + yield Path(root) / name + + +def _all_paths() -> set[str]: + out = set() + for base in (Path("/"), Path("/dev/shm")): + if base.is_dir(): + out.update(str(q) for q in _walk_one_fs(base)) + return out + + +def _protected(path: str) -> bool: + keep = [str(STATE), "/opt/are", str(TOKEN_FILE.parent)] + return any(path == k or path.startswith(k + "/") for k in keep) + + +def _fresh_state() -> None: + """Start every grade from the grader image's own files, as ARE 1.0's fresh verifier + container did. The grader container lives for the whole run, so before each grade + stop anything an earlier grade left running and delete every file it created, + whoever wrote it. The deliverable volume and the token are separate mounts and are + never walked; the grader's own state is kept.""" + _kill_other_processes() + # System V shared memory, semaphores and queues outlive processes; this server uses none. + subprocess.run(["ipcrm", "--all"], capture_output=True) + for path in sorted(_all_paths() - _BASELINE, key=lambda q: q.count("/"), reverse=True): + if _protected(path): + continue + try: + q = Path(path) + if q.is_dir() and not q.is_symlink(): + shutil.rmtree(q, ignore_errors=True) + else: + q.unlink() + except OSError: + pass + + +def grade_snapshot(tar_bytes: bytes, tag: str) -> dict: + """Extract a snapshot over the artifact paths and run this role's grader script.""" + _fresh_state() + for path in ARTIFACT_PATHS: + p = Path(path) + if p.exists(): + shutil.rmtree(p) + p.mkdir(parents=True) + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:gz") as tf: + tf.extractall("/", filter="tar") + logs = Path("/logs/verifier") + if logs.exists(): + shutil.rmtree(logs) + logs.mkdir(parents=True) + started = time.time() + # Submitted code runs with no network, as in ARE 1.0's verifier. + cmd = (["unshare", "-n"] if NET_ISOLATED else []) + ["bash", SCRIPT] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + cwd="/tests", start_new_session=True) + try: + out, err = proc.communicate(timeout=GRADE_TIMEOUT_SEC) + error = None + except subprocess.TimeoutExpired: + _kill_grading_processes(proc) + out, err = proc.communicate() + error = f"grader timed out after {GRADE_TIMEOUT_SEC:.0f}s" + output = (out or "") + (err or "") + # Nothing a grade started may keep running after it, not even detached processes. + _kill_other_processes() + score = 0.0 + reward_file = logs / "reward.txt" + if reward_file.exists(): + try: + score = float(reward_file.read_text().strip() or 0) + except ValueError: + error = error or "unparseable reward" + metric = None + if (logs / "metric.json").exists(): + try: + metric = json.loads((logs / "metric.json").read_text()) + except ValueError: + pass + (STATE / "logs").mkdir(exist_ok=True) + (STATE / "logs" / f"{tag}.log").write_text(output) + return { + "score": score, + "metric": metric, + "error": error, + "net_isolated": NET_ISOLATED, + "seconds": round(time.time() - started, 1), + # What the agent sees, as in ARE 1.0: the grader's stdout tail (not stderr). + "output_tail": (out or "")[-FEEDBACK_TAIL:], + } + + +mcp = FastMCP("are") + + +# ---------------------------------------------------------------- test role + + +_grade_lock = threading.Lock() + + +def _grade_one_at_a_time(tar_bytes: bytes, tag: str) -> dict: + # A request that timed out on the caller's side may still be grading; the next one + # waits for it rather than sharing /app/output and /logs/verifier with it. + with _grade_lock: + return grade_snapshot(tar_bytes, tag) + + +if ROLE == "test": + + @mcp.custom_route("/grade", methods=["POST"]) + async def http_grade(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + tag = request.query_params.get("tag", "x") + body = await request.body() + result = await asyncio.to_thread(_grade_one_at_a_time, body, f"{tag}-test") + return JSONResponse(result) + + +# ----------------------------------------------------------------- val role + + +class Board: + """Submissions and their grading state. Hidden scores are never stored here.""" + + def __init__(self) -> None: + self.subs: dict[int, dict] = {} + self.val_q: queue.Queue[int] = queue.Queue() + self.next_id = 1 + self.test_pending = 0 + self.last_digest: str | None = None + + def public(self, sid: int) -> dict: + s = self.subs[sid] + out = {k: s[k] for k in ("id", "note", "submitted_at_s", "status")} + if s["status"] == "graded": + v = s["val"] + out.update( + validation_score=v["score"], + error=v["error"], + grading_seconds=v["seconds"], + grader_output_tail=v["output_tail"], + ) + return out + + def best(self) -> dict | None: + graded = [s for s in self.subs.values() if s["status"] == "graded"] + if not graded: + return None + b = max(graded, key=lambda s: (s["val"]["score"], -s["id"])) + return {"id": b["id"], "validation_score": b["val"]["score"]} + + +board = Board() + + +def snapshot() -> bytes: + """Deterministic tar.gz of the deliverable: same content, same bytes (gzip mtime 0).""" + raw = io.BytesIO() + with tarfile.open(fileobj=raw, mode="w") as tf: + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + tf.add(str(src), arcname=path.lstrip("/")) + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as gz: + gz.write(raw.getvalue()) + return out.getvalue() + + +def do_submit(note: str, final: bool = False) -> dict: + with _lock: + pending = [s["id"] for s in board.subs.values() if s["status"] != "graded"] + if pending and not final: + return { + "error": f"Submission {pending[0]} is still being graded. One submission is " + f"graded at a time: check result({pending[0]}) and submit again " + "once it has its score.", + "pending_id": pending[0], + } + sid = board.next_id + board.next_id += 1 + board.subs[sid] = {"id": sid, "note": note[:500], "submitted_at_s": _elapsed(), + "status": "queued"} + try: + data = snapshot() + digest = hashlib.sha256(data).hexdigest() + (STATE / "snapshots" / f"{sid:04d}.tar.gz").write_bytes(data) + _ledger({"event": "submitted", "id": sid, "note": note[:500], "bytes": len(data), + "sha256": digest, "final": final}) + except Exception as exc: + with _lock: + board.subs.pop(sid, None) # release the slot; the id is not reused + return {"error": f"Could not snapshot the deliverable ({exc}). Nothing was submitted. " + "Make sure nothing is writing to it, then submit again."} + board.last_digest = digest + with _lock: + board.test_pending += 1 + board.val_q.put(sid) + return {"id": sid, "status": "queued", + "hint": "Grading has started. Check result(id) for the validation score."} + + +def final_submit() -> dict: + """After the agent stops: grade the final workspace unless it was already submitted.""" + try: + data = snapshot() + except Exception as exc: + return {"error": f"final snapshot failed: {exc}"} + if board.subs and hashlib.sha256(data).hexdigest() == board.last_digest: + return {"skipped": "final workspace equals the last submission"} + return do_submit("final workspace (automatic)", final=True) + + +def grade_worker() -> None: + """Grade each submission on val, then on test, one submission at a time. + + The val score is published as soon as it is ready. The next submission's val grade + waits until this test grade is done, so the two graders never run at the same time. + """ + while True: + sid = board.val_q.get() + board.subs[sid]["status"] = "grading" + data = b"" + try: + data = (STATE / "snapshots" / f"{sid:04d}.tar.gz").read_bytes() + res = grade_snapshot(data, f"{sid:04d}-val") + except Exception as exc: + res = {"score": 0.0, "metric": None, "error": f"grader failed: {exc}", + "net_isolated": NET_ISOLATED, "seconds": 0.0, "output_tail": ""} + board.subs[sid]["val"] = res + board.subs[sid]["status"] = "graded" + try: + _ledger({"event": "val", "id": sid, **{k: res[k] for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + test_grade(sid, data) + + +def test_grade(sid: int, data: bytes) -> None: + try: + _test_grade(sid, data) + finally: + with _lock: + board.test_pending -= 1 + + +def _test_grade(sid: int, data: bytes) -> None: + """Send one snapshot to the test grader. A failed request is retried (the same snapshot + is graded again, so a retry can only recover the honest score); a request that ran + past its timeout is not, since the grade itself already took the full time.""" + started = time.time() + for attempt in range(3): + try: + req = urllib.request.Request( + f"{TEST_GRADER_URL}/grade?tag={sid:04d}", data=data, method="POST", + headers={"x-are-token": TOKEN}, + ) + with urllib.request.urlopen(req, timeout=2 * GRADE_TIMEOUT_SEC + 300) as resp: + res = json.loads(resp.read()) + break + except Exception as exc: # recorded, never shown to the agent + res = {"score": None, "metric": None, "error": f"test grader: {exc}", + "seconds": round(time.time() - started, 1)} + if attempt == 2 or isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError): + break + time.sleep(5) + try: + _ledger({"event": "test", "id": sid, **{k: res.get(k) for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + + +def with_time(out: dict) -> dict: + """Wall-clock accounting on every reply, as the v1 harness gave each phase.""" + out["total_budget_seconds"] = BUDGET_SEC + out["time_remaining_seconds"] = round(max(0.0, BUDGET_SEC - _elapsed()), 1) + return out + + +def status_dict() -> dict: + return { + "submissions": len(board.subs), + "queued_or_grading": sum(s["status"] != "graded" for s in board.subs.values()), + "best": board.best(), + } + + +def current_result(sid: int) -> dict: + return board.public(sid) + + +if ROLE == "val": + + @mcp.tool + async def submit(note: str = "") -> dict: + """Submit the current deliverable for grading. + + Snapshots the deliverable directory right now (later edits do not affect this + submission) and starts grading it on the public validation split. Returns at + once with a submission id. One submission is graded at a time: check `result` + and submit again once the previous submission has its score. `note` is a short + description of what changed. + """ + return with_time(await asyncio.to_thread(do_submit, note)) + + @mcp.tool + async def result(id: int) -> dict: + """The current state of a submission: queued, grading, or graded with its + validation score and grader output. Returns immediately.""" + if id not in board.subs: + return {"error": f"unknown submission id {id}"} + return with_time(current_result(id)) + + @mcp.tool + async def status() -> dict: + """Submission count, whether one is being graded, the best validation score, + and the time budget and time remaining.""" + return with_time(status_dict()) + + @mcp.custom_route("/submit", methods=["POST"]) + async def http_submit(request: Request) -> Response: + note = request.query_params.get("note", "") + return JSONResponse(with_time(await asyncio.to_thread(do_submit, note))) + + @mcp.custom_route("/result/{sid}", methods=["GET"]) + async def http_result(request: Request) -> Response: + sid = int(request.path_params["sid"]) + if sid not in board.subs: + return JSONResponse({"error": f"unknown submission id {sid}"}, status_code=404) + return JSONResponse(with_time(current_result(sid))) + + @mcp.custom_route("/status", methods=["GET"]) + async def http_status(request: Request) -> Response: + return JSONResponse(with_time(status_dict())) + + @mcp.custom_route("/final", methods=["POST"]) + async def http_final(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Collect hook, after the agent has stopped. + return JSONResponse(await asyncio.to_thread(final_submit)) + + @mcp.custom_route("/drain", methods=["GET"]) + async def http_drain(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Used by the verifier collect hook after the agent has stopped. + pending = sum(s["status"] != "graded" for s in board.subs.values()) + return JSONResponse({"val_pending": pending, "test_pending": board.test_pending}) + + +def _gpus() -> list[str]: + try: + out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=20) + return [l for l in out.stdout.splitlines() if l.strip()] + except Exception: + return [] + + +@mcp.custom_route("/health", methods=["GET"]) +async def health(request: Request) -> Response: + return JSONResponse({"ok": True, "role": ROLE, "gpus": await asyncio.to_thread(_gpus)}) + + +def _setup_token() -> None: + global TOKEN + if ROLE == "test": + TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True) + os.chmod(TOKEN_FILE.parent, 0o700) + TOKEN = secrets.token_hex(32) + TOKEN_FILE.write_text(TOKEN) + os.chmod(TOKEN_FILE, 0o600) + else: + for _ in range(300): # the test grader is healthy before this one starts + if TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip(): + break + time.sleep(1) + TOKEN = TOKEN_FILE.read_text().strip() + if not TOKEN: + raise SystemExit("ARE: empty internal token; refusing to start") + + +def main() -> None: + global NET_ISOLATED + NET_ISOLATED = _net_isolation_available() + if not NET_ISOLATED: + # Graded code must never have a network path (for example back through /submit). + raise SystemExit("ARE grader: cannot run grades without network access " + "(needs `unshare -n`, i.e. CAP_SYS_ADMIN); refusing to start") + STATE.mkdir(parents=True, exist_ok=True) + _BASELINE.update(_all_paths()) + _setup_token() + STATE.mkdir(parents=True, exist_ok=True) + os.chmod(STATE, 0o700) + (STATE / "snapshots").mkdir(exist_ok=True) + if ROLE == "val": + # The deliverable volume starts empty and root-owned; hand it to the agent user. + SUBMISSION_ROOT.mkdir(parents=True, exist_ok=True) + os.chmod(SUBMISSION_ROOT, 0o700) + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + src.mkdir(parents=True, exist_ok=True) + os.chown(src, AGENT_UID, AGENT_UID) + (STATE / "meta.json").write_text(json.dumps( + {"t0_wall": T0, "budget_seconds": BUDGET_SEC, "artifact_paths": ARTIFACT_PATHS} + )) + threading.Thread(target=grade_worker, daemon=True).start() + mcp.run(transport="http", host="0.0.0.0", port=PORT, show_banner=False, + uvicorn_config={"timeout_keep_alive": 86400}) + + +if __name__ == "__main__": + main() diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/build_data.py b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/build_data.py new file mode 100644 index 0000000000000000000000000000000000000000..4f019289465883a1cc93ed2b97fe28d86ac42865 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/build_data.py @@ -0,0 +1,222 @@ +from __future__ import annotations + +import argparse +import gzip +import hashlib +import json +import re +import sys +from pathlib import Path + +import numpy as np +from tokenizers import Tokenizer + +EOT_TOKEN = 50256 +_WS = re.compile(r"\s+") + + +def norm_hash(text: str) -> str: + return hashlib.sha256(_WS.sub(" ", text).strip().lower().encode("utf-8")).hexdigest()[:32] + + +def host_of(url: str) -> str: + u = url.split("://", 1)[-1] + host = u.split("/", 1)[0].split("?", 1)[0].split("@")[-1].split(":")[0].lower() + if host.startswith("www."): + host = host[4:] + return host or "unknown" + + +def read_docs(paths, skip_docs: int = 0): + seen = 0 + for path in paths: + with gzip.open(path, "rt", encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + seen += 1 + if seen <= skip_docs: + continue + yield json.loads(line) + + +def encode_stream(tokenizer_json: str, docs_iter, batch: int = 2000): + tok = Tokenizer.from_file(tokenizer_json) + buf = [] + for rec in docs_iter: + buf.append(rec) + if len(buf) == batch: + for rec, enc in zip(buf, tok.encode_batch([r["text"] for r in buf])): + yield rec, enc.ids + buf = [] + if buf: + for rec, enc in zip(buf, tok.encode_batch([r["text"] for r in buf])): + yield rec, enc.ids + + +def build_eval(args): + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + chunks, hashes, urls = [], [], [] + total = 0 + n_docs = 0 + for rec, ids in encode_stream(args.tokenizer, read_docs(args.shards, args.skip_docs)): + ids = ids + [EOT_TOKEN] + chunks.append(np.asarray(ids, dtype=np.uint16)) + hashes.append(norm_hash(rec["text"])) + urls.append(rec.get("url", "")) + total += len(ids) + n_docs += 1 + if total >= args.target_tokens: + break + flat = np.concatenate(chunks)[: args.target_tokens] + np.save(out / "tokens.npy", flat) + meta = {"kind": "eval", "n_docs": n_docs, "n_tokens": int(flat.shape[0]), + "shards": [Path(s).name for s in args.shards]} + (out / "meta.json").write_text(json.dumps(meta, indent=2, sort_keys=True)) + (out / "guard.json").write_text(json.dumps( + {"hashes": sorted(set(hashes)), "urls": sorted(set(urls))})) + print(f"[eval] {meta}", flush=True) + + +def _merged_stream(args): + """Read the pool's corpus files. + + A pool may be drawn from two corpus variants of the same crawl -- a filtered one and + a minimally-filtered one -- in which case documents are interleaved deterministically + in proportion to their token targets, before any grouping or ordering happens. + """ + a = encode_stream(args.tokenizer, read_docs(args.shards, args.skip_docs)) + if not args.shards_b: + yield from a + return + b = encode_stream(args.tokenizer, read_docs(args.shards_b, args.skip_docs_b)) + want_a = args.target_tokens - args.target_tokens_b + want_b = args.target_tokens_b + got_a = got_b = 0 + a_done = b_done = False + while not (a_done and b_done): + take_b = (not b_done) and (b_done or a_done or + got_b * max(1, want_a) <= got_a * max(1, want_b)) + if take_b: + try: + rec, ids = next(b) + got_b += len(ids) + 1 + yield rec, ids + continue + except StopIteration: + b_done = True + continue + try: + rec, ids = next(a) + got_a += len(ids) + 1 + yield rec, ids + except StopIteration: + a_done = True + + +def build_pool(args): + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + guard_hashes, guard_urls = set(), set() + for g in args.guard or []: + blob = json.loads(Path(g).read_text()) + guard_hashes.update(blob["hashes"]) + guard_urls.update(blob["urls"]) + + kept, seen, seen_urls = [], set(), set() + total = 0 + n_seen = n_guard_hash = n_guard_url = n_dup = n_empty = n_dup_url = 0 + for rec, ids in _merged_stream(args): + n_seen += 1 + text = rec["text"] + if not ids: + n_empty += 1 + continue + h = norm_hash(text) + url = rec.get("url", "") + if h in guard_hashes: + n_guard_hash += 1 + continue + if url and url in guard_urls: + n_guard_url += 1 + continue + if h in seen: + n_dup += 1 + continue + if url and url in seen_urls: + n_dup_url += 1 + continue + seen.add(h) + if url: + seen_urls.add(url) + ids = ids + [EOT_TOKEN] + kept.append((url, text, np.asarray(ids, dtype=np.uint16))) + total += len(ids) + if total >= args.target_tokens: + break + + by_host: dict[str, list[int]] = {} + host_tokens: dict[str, int] = {} + for i, (url, _text, ids) in enumerate(kept): + host = host_of(url) + by_host.setdefault(host, []).append(i) + host_tokens[host] = host_tokens.get(host, 0) + int(ids.shape[0]) + order: list[int] = [] + for host in sorted(host_tokens, key=lambda h: (-host_tokens[h], h)): + order.extend(by_host[host]) + + offsets = np.zeros(len(order) + 1, dtype=np.int64) + with open(out / "docs.jsonl", "w", encoding="utf-8") as fh: + for new_id, old in enumerate(order): + url, text, ids = kept[old] + offsets[new_id + 1] = offsets[new_id] + int(ids.shape[0]) + fh.write(json.dumps({"id": new_id, "text": text, "url": url, + "ntokens": int(ids.shape[0])}, ensure_ascii=False) + "\n") + flat = np.empty(int(offsets[-1]), dtype=np.uint16) + for new_id, old in enumerate(order): + flat[offsets[new_id]:offsets[new_id + 1]] = kept[old][2] + np.save(out / "tokens.npy", flat) + np.save(out / "offsets.npy", offsets) + + meta = {"kind": "pool", "n_docs": len(order), "n_tokens": int(offsets[-1]), + "n_hosts": len(host_tokens), "n_seen": n_seen, + "dropped_eval_hash": n_guard_hash, "dropped_eval_url": n_guard_url, + "dropped_internal_dup": n_dup, "dropped_internal_dup_url": n_dup_url, + "dropped_empty": n_empty, + "shards": [Path(s).name for s in args.shards], "skip_docs": args.skip_docs} + (out / "meta.json").write_text(json.dumps(meta, indent=2, sort_keys=True)) + (out / "guard.json").write_text(json.dumps( + {"hashes": sorted(seen), "urls": sorted(u for u in seen_urls if u)})) + print(f"[pool] {meta}", flush=True) + + pool_hashes = seen + assert not (pool_hashes & guard_hashes), "pool/eval text-hash overlap survived the guard" + print(f"[pool] split integrity OK: {len(pool_hashes)} pool hashes, " + f"{len(guard_hashes)} eval hashes, intersection 0", flush=True) + + +def main(argv=None): + ap = argparse.ArgumentParser() + ap.add_argument("kind", choices=["eval", "pool"]) + ap.add_argument("--shards", nargs="+", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--tokenizer", required=True, help="path to a HF tokenizer.json") + ap.add_argument("--target-tokens", type=int, required=True) + ap.add_argument("--shards-b", nargs="*", default=None, + help="second corpus variant to interleave into the pool") + ap.add_argument("--target-tokens-b", type=int, default=0, + help="how many of --target-tokens come from --shards-b") + ap.add_argument("--skip-docs-b", type=int, default=0) + ap.add_argument("--skip-docs", type=int, default=0, + help="skip this many leading documents of the shard list (disjoint draws)") + ap.add_argument("--guard", nargs="*", default=None, + help="eval guard.json files whose documents must not enter the pool") + args = ap.parse_args(argv) + (build_eval if args.kind == "eval" else build_pool)(args) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/candidate_runner.py b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/candidate_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..c569b2c4fe5827a34c2af181038fc4d6a5092ed9 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/candidate_runner.py @@ -0,0 +1,62 @@ +import importlib.util +import json +import random +import sys +import traceback + +import numpy as np +import torch + + +def _transport(item): + """ints travel as ints; anything else travels as a marker the grader drops.""" + if isinstance(item, bool): + return {"__bad__": "bool"} + if isinstance(item, int): + return int(item) + typ = type(item).__name__ + try: + return int(item.__index__()) + except Exception: + return {"__bad__": typ} + + +def main() -> int: + deliverable_dir, pool_dir, budget_s, workdir, out_path = sys.argv[1:6] + result = {"ok": False, "error": None, "value": None, "value_type": None} + try: + spec = importlib.util.spec_from_file_location( + "candidate_select", f"{deliverable_dir}/select.py") + if spec is None or spec.loader is None: + raise ImportError("select.py is not importable") + random.seed(0) + np.random.seed(0) + torch.manual_seed(0) + torch.cuda.manual_seed_all(0) + module = importlib.util.module_from_spec(spec) + sys.modules["candidate_select"] = module + sys.path.insert(0, deliverable_dir) + spec.loader.exec_module(module) + fn = getattr(module, "select", None) + if fn is None or not callable(fn): + raise AttributeError("select.py defines no callable named 'select'") + value = fn(pool_dir, int(budget_s), workdir) + result["value_type"] = type(value).__name__ + if isinstance(value, tuple): + value = list(value) + if not isinstance(value, list): + raise TypeError(f"select() returned {type(value).__name__}, expected list") + result["value"] = [_transport(v) for v in value] + result["ok"] = True + except BaseException: + result["error"] = traceback.format_exc()[-4000:] + try: + with open(out_path, "w", encoding="utf-8") as fh: + json.dump(result, fh) + except Exception: + return 4 + return 0 if result["ok"] else 3 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/compute_reward.py b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..1d11005efea80cd7edb4ae8d0b5fd61fa6a00727 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,134 @@ +import json +import math +import os +import tempfile +from pathlib import Path + +REWARD_PATH = Path("/logs/verifier/reward.txt") +METRIC_PATH = Path("/logs/verifier/metric.json") + + +def clamp_unit(value) -> float: + """Map ANY object to a finite float in the closed interval [0, 1]. + + The comparisons are written so that NaN cannot slip through either end: NaN fails + `math.isfinite` before it reaches them, and the `<= 0.0` branch also normalises -0.0 + to 0.0 so no rendered reward can ever carry a minus sign. + """ + try: + x = float(value) + except Exception: + return 0.0 + if not math.isfinite(x): + return 0.0 + if x <= 0.0: + return 0.0 + if x >= 1.0: + return 1.0 + return x + + +def render(x: float) -> str: + """Render the clamped value, then read it back: only a string that parses to a finite + number inside [0, 1] is ever handed to the writer. Anything else degrades to "0".""" + try: + text = f"{x:.12g}" + back = float(text) + except Exception: + return "0" + if not math.isfinite(back) or back < 0.0 or back > 1.0: + return "0" + return text + + +def emit(text: str) -> bool: + """Write reward.txt. Never raises; returns whether the bytes landed. + + The write goes through a temp file in the same directory and one os.replace, so a + reader can only ever see the whole value or no file -- a crash partway through a + direct write could otherwise leave a truncated, unparseable reward.txt behind. + """ + payload = text + "\n" + try: + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + except Exception: + pass + tmp = None + try: + fd, tmp = tempfile.mkstemp(dir=str(REWARD_PATH.parent), prefix=".reward-") + with os.fdopen(fd, "w") as fh: + fh.write(payload) + fh.flush() + os.fsync(fh.fileno()) + os.chmod(tmp, 0o644) + os.replace(tmp, REWARD_PATH) + return True + except Exception: + if tmp is not None: + try: + os.unlink(tmp) + except Exception: + pass + try: + REWARD_PATH.write_text(payload) + return True + except Exception: + return False + + +def in_range(value) -> bool: + """Whether `value` is a finite number inside [0, 1].""" + try: + x = float(value) + except Exception: + return False + return math.isfinite(x) and 0.0 <= x <= 1.0 + + +def already_bounded() -> bool: + """Whether reward.txt on disk already holds a finite value inside [0, 1]. + + The last-resort handler consults this so that a failure AFTER a good reward was + written -- a closed stdout, a signal during the diagnostic print -- cannot replace a + valid submission's score with 0. + """ + try: + return in_range(REWARD_PATH.read_text().strip()) + except Exception: + return False + + +def say(message: str) -> None: + """Diagnostics must never be the reason this script fails.""" + try: + print(message) + except Exception: + pass + + +def main() -> None: + error = None + try: + value = json.loads(METRIC_PATH.read_text())["reward"] + except Exception as exc: + value, error = None, f"{type(exc).__name__}: {exc}" + reward = render(clamp_unit(value)) + wrote = emit(reward) + if error is None and not in_range(value): + error = f"clamped from {value!r}" + notes = [n for n in (error, None if wrote else "reward.txt is unwritable") if n] + say(f"reward={reward}" + (f" ({'; '.join(notes)})" if notes else "")) + + +if __name__ == "__main__": + try: + main() + except BaseException as exc: + kept = already_bounded() + if not kept: + emit("0") + try: + detail = f"{type(exc).__name__}: {exc}" + except Exception: + detail = "unprintable exception" + say(("reward.txt kept" if kept else "reward=0") + f" (fallback: {detail})") diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/grader_core.py b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..dd1bc8ed8cd1bdc896797e57ac499972e6a19f7b --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,476 @@ +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import signal +import subprocess +import sys +import time +import traceback +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import numpy as np + +import pretrain_harness as H + +BUDGET_TOKENS = 125_000_000 +SELECT_TIMEOUT_SEC = 2400 +DELIVERABLE_DIR = "/app/output" +ENTRY_POINT = "select.py" +CANDIDATE_UID = 1001 +CANDIDATE_GID = 1001 + +WRITABLE_SURFACE_ROOT = DELIVERABLE_DIR +AGENT_TREES_NEVER_READ = ("/app/harness", "/app/data", "/app/scratch") + + +def writable_surface_violations(config_path=None) -> list: + """Every way this grader would read agent-editable state outside the writable surface. + + Empty is the only acceptable result at grade time, and test_state.py asserts exactly that. + It is reported rather than raised from grade() so that the build-time baseline sweep, which + grades stub selectors against its own scratch pools and its own config copy, can drive the + same code path without tripping a check that only describes the graded image. + """ + sealed = Path(__file__).resolve().parent + bad = [] + for label, module_file in (("grader_core", __file__), ("pretrain_harness", H.__file__)): + path = Path(module_file).resolve() + if sealed not in path.parents: + bad.append(f"{label} is loaded from {path}, outside the sealed tree {sealed}") + if config_path is not None: + cfg = Path(config_path).resolve() + if sealed not in cfg.parents: + bad.append(f"the training config is read from {cfg}, outside {sealed}") + for tree in AGENT_TREES_NEVER_READ: + if Path(tree).exists(): + bad.append(f"{tree} reached the verifier and could shadow the sealed copy") + app = Path("/app") + for entry in sys.path: + if not entry: + continue + path = Path(entry).resolve() + if path == app or app in path.parents: + bad.append(f"an agent-writable path is on the grader's sys.path: {entry}") + return bad + + +DEGENERATE_REWARD = 0.10 +M_FLOOR = -4.01125 +M0 = 0.25515 +BASELINE_SCORE = 4.4 + + +def graded_reward(metric: float, valid: bool) -> float: + """rational_squash, higher-is-better, with the linear band below the trivial baseline.""" + if not valid: + return 0.0 + x = metric - M0 + x_ref = BASELINE_SCORE - M0 + assert x_ref > 0, "malformed task: the anchor does not beat the trivial baseline" + g = M0 - M_FLOOR + if g <= 0: + u = max(0.0, x) / x_ref + return u / (1.0 + u) + if x < 0: + return DEGENERATE_REWARD * (max(0.0, metric - M_FLOOR) / g) + u = x / x_ref + return DEGENERATE_REWARD + (1.0 - DEGENERATE_REWARD) * (u / (1.0 + u)) + + +class SubmissionRejected(Exception): + pass + + +def scan_submission(src: Path) -> None: + """Reject symlinks and hard links anywhere in the submitted tree, at any depth. + + A read-only bind mount does not remove hard links already in the submission, and a + no-dereference copy does not make a directory symlink's contents safe -- so the tree + is scanned and rejected BEFORE anything is copied. + """ + if not src.is_dir() or src.is_symlink(): + raise SubmissionRejected(f"{src} is not a real directory") + stack = [src] + n_files = 0 + while stack: + cur = stack.pop() + with os.scandir(cur) as it: + for entry in it: + st = os.lstat(entry.path) + if os.path.islink(entry.path): + raise SubmissionRejected(f"symlink in submission: {entry.path}") + if entry.is_dir(follow_symlinks=False): + stack.append(Path(entry.path)) + continue + if st.st_nlink != 1: + raise SubmissionRejected( + f"hard link in submission (st_nlink={st.st_nlink}): {entry.path}") + n_files += 1 + if n_files > 200_000: + raise SubmissionRejected("submission contains too many files") + + +def stage_submission(src: Path, dst: Path) -> None: + """Copy the scanned tree without following links, then hand it to the candidate uid.""" + scan_submission(src) + if dst.exists(): + shutil.rmtree(dst) + shutil.copytree(src, dst, symlinks=True) + for root, dirs, files in os.walk(dst): + os.lchown(root, CANDIDATE_UID, CANDIDATE_GID) + for name in dirs + files: + os.lchown(os.path.join(root, name), CANDIDATE_UID, CANDIDATE_GID) + os.lchown(dst, CANDIDATE_UID, CANDIDATE_GID) + + +POOL_FILES_FOR_CANDIDATE = ("docs.jsonl", "tokens.npy", "offsets.npy") + + +def stage_pool(pool_dir: Path, session: Path) -> Path: + """Publish the pool to the candidate uid without opening the sealed tree. + + /tests is 0700 root at grade time, so a uid-1001 subprocess cannot traverse it -- and + it must not, because the evaluation shard and this file live there. The three files + instruction.md documents are copied into a traversable parent as root-owned 0444, so + the candidate can read exactly the pool and cannot mutate the bytes the grader scores + from; the grader keeps reading the originals under /tests. meta.json and guard.json + are deliberately NOT copied -- guard.json carries the evaluation shard's document + hashes and URLs. + """ + dst = session / "pool" + if dst.exists(): + shutil.rmtree(dst) + dst.mkdir(parents=True) + os.chmod(dst, 0o755) + for name in POOL_FILES_FOR_CANDIDATE: + src = Path(pool_dir) / name + if not src.is_file(): + raise FileNotFoundError(f"the graded pool is missing {name}") + shutil.copyfile(src, dst / name) + os.chown(dst / name, 0, 0) + os.chmod(dst / name, 0o444) + return dst + + +def stage_runner(session: Path) -> Path: + """Copy candidate_runner.py out of the sealed tree into a traversable parent, keeping + it root-owned and read-only so the candidate can execute but never modify it.""" + session.mkdir(parents=True, exist_ok=True) + os.chmod(session, 0o755) + dst = session / "candidate_runner.py" + shutil.copyfile(Path(__file__).resolve().parent / "candidate_runner.py", dst) + os.chown(dst, 0, 0) + os.chmod(dst, 0o444) + return dst + + +def candidate_environment() -> dict: + """The explicit environment the candidate subprocess runs under. + + The NVIDIA visibility variables are deliberately NOT narrowed -- hiding the device + from the deliverable while the root grader still sees it is the hardest version of + this bug to read from a rollout log. + """ + env = { + "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "HOME": "/home/agent", + "LANG": "C.UTF-8", + "TMPDIR": "/tmp", + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONSAFEPATH": "1", + "PYTHONHASHSEED": "0", + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", + "TOKENIZERS_PARALLELISM": "false", + "CUBLAS_WORKSPACE_CONFIG": ":4096:8", + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + "HF_HOME": "/opt/assets/hf-home", + } + for key in ("NVIDIA_VISIBLE_DEVICES", "NVIDIA_DRIVER_CAPABILITIES", "LD_LIBRARY_PATH"): + if key in os.environ: + env[key] = os.environ[key] + return env + + +def run_selector(deliverable_src: Path, pool_dir: Path, session: Path, log=print) -> dict: + """Stage, launch and collect the submission. Never raises for a candidate failure.""" + out = {"ok": False, "error": None, "raw": None, "elapsed_sec": None, + "returncode": None, "stderr_tail": None} + staged = session / "submission" + workdir = session / "workdir" + result_path = workdir / "selection.json" + try: + stage_submission(deliverable_src, staged) + except SubmissionRejected as exc: + out["error"] = f"submission rejected: {exc}" + return out + except Exception as exc: + out["error"] = f"submission could not be staged: {type(exc).__name__}: {exc}" + return out + + entry = staged / ENTRY_POINT + if not entry.is_file(): + out["error"] = f"missing entry point {DELIVERABLE_DIR}/{ENTRY_POINT}" + return out + + workdir.mkdir(parents=True, exist_ok=True) + os.chmod(workdir, 0o755) + os.chown(workdir, CANDIDATE_UID, CANDIDATE_GID) + if result_path.exists(): + result_path.unlink() + runner = stage_runner(session) + try: + candidate_pool = stage_pool(pool_dir, session) + except Exception as exc: + out["error"] = f"the pool could not be staged for the candidate: {exc}" + return out + + cmd = ["runuser", "-u", "agent", "--", "/usr/bin/python3", str(runner), + str(staged), str(candidate_pool), str(BUDGET_TOKENS), str(workdir), str(result_path)] + log(f"[select] launching: {' '.join(cmd)}") + started = time.monotonic() + proc = None + try: + proc = subprocess.Popen( + cmd, env=candidate_environment(), cwd=str(workdir), + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True, + ) + except Exception as exc: + out["elapsed_sec"] = time.monotonic() - started + out["error"] = f"could not launch the submission: {type(exc).__name__}: {exc}" + _reap(None) + return out + try: + stdout, _ = proc.communicate(timeout=SELECT_TIMEOUT_SEC) + out["returncode"] = proc.returncode + out["stderr_tail"] = (stdout or b"").decode("utf-8", "replace")[-4000:] + except subprocess.TimeoutExpired: + _reap(proc) + try: + stdout, _ = proc.communicate(timeout=60) + except Exception: + stdout = b"" + out["elapsed_sec"] = time.monotonic() - started + out["error"] = f"select() exceeded its {SELECT_TIMEOUT_SEC}-second budget" + out["stderr_tail"] = (stdout or b"").decode("utf-8", "replace")[-4000:] + return out + except Exception as exc: + _reap(proc) + out["elapsed_sec"] = time.monotonic() - started + out["error"] = f"select() could not be collected: {type(exc).__name__}: {exc}" + return out + finally: + _reap(proc) + out["elapsed_sec"] = time.monotonic() - started + + if not result_path.is_file(): + out["error"] = (f"select() wrote no result (returncode={out['returncode']}); " + f"tail: {out['stderr_tail']}") + return out + try: + blob = json.loads(result_path.read_text()) + except Exception as exc: + out["error"] = f"select() result is unparseable: {type(exc).__name__}: {exc}" + return out + if not blob.get("ok"): + out["error"] = f"select() raised: {blob.get('error')}" + return out + out["raw"] = blob.get("value") + out["ok"] = True + return out + + +def _reap(proc) -> None: + """Kill the candidate's whole process group, then sweep any double-forked stragglers. + + start_new_session=True made the child a session/process-group leader (setsid(2)), so + its pgid equals its pid and one killpg reaches every descendant that stayed in the + group; the uid sweep is the backstop for anything that left it. + """ + if proc is not None: + try: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + except Exception: + pass + try: + subprocess.run(["pkill", "-9", "-u", str(CANDIDATE_UID)], timeout=30, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except Exception: + pass + + +def reference_perplexity(cfg, pool, eval_blocks, cache_dir=None, log=print) -> dict: + """The full-pool reference run. + + `cache_dir` is None at grade time, where the reference is computed exactly once per + invocation anyway, so no cache and no cache-shaped attack surface exists there. The + build-time baseline sweep passes a root-owned scratch directory so that N selectors + graded against one pool pay for one reference run instead of N; the key covers the + pool identity and every training hyperparameter. + """ + if cache_dir is None: + return H.run_cycle(cfg, pool, list(range(pool.n_docs)), eval_blocks, log=log) + key = hashlib.sha256( + (json.dumps(cfg, sort_keys=True) + "|" + str(Path(pool.dir).resolve()) + "|" + + str(pool.n_docs) + "|" + str(int(pool.offsets[-1])) + "|" + + str(int(eval_blocks.shape[0]))).encode("utf-8")).hexdigest()[:24] + path = Path(cache_dir) / f"reference-{key}.json" + if path.is_file(): + log(f"[grade] reference run served from {path}") + return json.loads(path.read_text()) + out = H.run_cycle(cfg, pool, list(range(pool.n_docs)), eval_blocks, log=log) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(out)) + return out + + +def grade(deliverable_src, pool_dir, eval_dir, config_path, session_dir, log=print, + reference_cache_dir=None) -> dict: + """Run the submission, train twice, evaluate twice, return the full record. + + This function NEVER raises. Every way the cycle can fail -- a hostile submission, a + crashed or timed-out selector, a wrong return type, a diverged training run, a broken + sealed slice, a bug in this file -- leaves `valid` False, which finalize() maps to + exactly 0.0. There is no path out of here that both fails and scores. + """ + record = { + "valid": False, "invalid_reason": None, "metric": None, + "ppl_selection": None, "ppl_full_pool": None, + "selection_stats": None, "select_elapsed_sec": None, + "gpu_visible_to_grader": None, "infra_error": None, + "writable_surface_violations": None, + "budget_tokens": BUDGET_TOKENS, "select_timeout_sec": SELECT_TIMEOUT_SEC, + } + try: + _grade_cycle(record, deliverable_src, pool_dir, eval_dir, config_path, session_dir, + log=log, reference_cache_dir=reference_cache_dir) + except BaseException as exc: + record["valid"] = False + record["metric"] = None + record["invalid_reason"] = f"the graded cycle raised: {type(exc).__name__}: {exc}" + record["grade_traceback"] = traceback.format_exc()[-6000:] + return record + + +def _grade_cycle(record, deliverable_src, pool_dir, eval_dir, config_path, session_dir, + log=print, reference_cache_dir=None) -> None: + """The cycle itself. Fills `record` in place; grade() owns the failure boundary.""" + deliverable_src = Path(deliverable_src) + pool_dir = Path(pool_dir) + eval_dir = Path(eval_dir) + session = Path(session_dir) + session.mkdir(parents=True, exist_ok=True) + + record["writable_surface_violations"] = writable_surface_violations(config_path) + for violation in record["writable_surface_violations"]: + log(f"[grade] writable-surface violation: {violation}") + + try: + import torch + record["gpu_visible_to_grader"] = int(torch.cuda.device_count()) + except Exception as exc: + record["gpu_visible_to_grader"] = -1 + record["infra_error"] = f"torch/CUDA unavailable to the grader: {exc}" + + try: + cfg = H.load_config(config_path) + pool = H.Pool(pool_dir) + block_size = int(cfg["block_size"]) + except Exception as exc: + record["infra_error"] = (f"the graded pool or config could not be loaded: " + f"{type(exc).__name__}: {exc}") + record["invalid_reason"] = "graded pool unavailable" + return + log(f"[grade] pool docs={pool.n_docs} tokens={int(pool.offsets[-1])}") + + sel = run_selector(deliverable_src, pool_dir, session, log=log) + record["select_elapsed_sec"] = sel["elapsed_sec"] + record["select_stderr_tail"] = sel["stderr_tail"] + if not sel["ok"]: + record["invalid_reason"] = sel["error"] + return + try: + accepted, used, stats = H.sanitize_selection(sel["raw"], pool.ntokens, BUDGET_TOKENS) + except ValueError as exc: + record["invalid_reason"] = str(exc) + return + record["selection_stats"] = stats + log(f"[grade] selection {stats}") + if len(accepted) == 0 or used < block_size: + record["invalid_reason"] = "selection buys fewer than one full training block" + return + + try: + eval_blocks = H.load_eval_blocks(eval_dir, block_size) + except Exception as exc: + record["infra_error"] = (f"the graded evaluation shard could not be loaded: " + f"{type(exc).__name__}: {exc}") + record["invalid_reason"] = "evaluation shard unavailable" + return + log(f"[grade] eval blocks={eval_blocks.shape[0]}") + + try: + sel_out = H.run_cycle(cfg, pool, accepted, eval_blocks, log=log) + except Exception as exc: + record["invalid_reason"] = f"training on the selection failed: {type(exc).__name__}: {exc}" + return + + try: + full_out = reference_perplexity(cfg, pool, eval_blocks, + cache_dir=reference_cache_dir, log=log) + except Exception as exc: + record["infra_error"] = f"full-pool reference run failed: {type(exc).__name__}: {exc}" + record["invalid_reason"] = "reference run unavailable" + return + + ppl_sel = float(sel_out["perplexity"]) + ppl_full = float(full_out["perplexity"]) + record["ppl_selection"] = ppl_sel + record["ppl_full_pool"] = ppl_full + if not (np.isfinite(ppl_sel) and np.isfinite(ppl_full)) or ppl_full <= 0.0: + record["invalid_reason"] = (f"perplexity is unusable (selection={ppl_sel!r}, " + f"full pool={ppl_full!r})") + return + metric = 100.0 * (ppl_full - ppl_sel) / ppl_full + if not np.isfinite(metric): + record["invalid_reason"] = "metric is not finite" + return + record["metric"] = float(metric) + record["valid"] = True + log(f"[grade] ppl_sel={ppl_sel:.6f} ppl_full={ppl_full:.6f} metric={metric:.4f}") + + +def finalize(record: dict) -> dict: + """Map the record to its reward. Never raises: anything it cannot score is 0.0. + + An invalid record does not get a small reward, it gets exactly 0.0 -- there is no + partial credit for a submission that failed, and none for a grader that failed either. + """ + record = dict(record) + try: + valid = bool(record.get("valid")) and record.get("metric") is not None + metric = float(record["metric"]) if valid else float("nan") + if valid and not np.isfinite(metric): + valid = False + record["invalid_reason"] = "metric is not finite" + reward = float(graded_reward(metric, valid)) + if not np.isfinite(reward): + raise ValueError(f"the reward map returned {reward!r}") + except BaseException as exc: + valid = False + reward = 0.0 + record["invalid_reason"] = (f"the reward map could not be evaluated: " + f"{type(exc).__name__}: {exc}") + record["valid"] = valid + record["reward"] = reward if valid else 0.0 + record["anchors"] = {"m_floor": M_FLOOR, "m0": M0, "baseline_score": BASELINE_SCORE, + "degenerate_reward": DEGENERATE_REWARD} + return record diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/intermediate.sh b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..2146390147cf5697b329836f1cd43945ab939e50 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,29 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +default_reward() { + if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /logs/verifier/reward.txt; fi +} +trap 'default_reward' EXIT +trap 'default_reward; exit 0' HUP INT TERM + +chmod -R go-rwx /tests + +export HIDDEN_SPLIT=intermediate +export PYTHONHASHSEED=0 +export OMP_NUM_THREADS=1 +export MKL_NUM_THREADS=1 +export OPENBLAS_NUM_THREADS=1 +export NUMEXPR_NUM_THREADS=1 +export CUBLAS_WORKSPACE_CONFIG=:4096:8 + +cd /tests +/usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +/usr/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/pretrain_harness.py b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/pretrain_harness.py new file mode 100644 index 0000000000000000000000000000000000000000..0078ac8c3ae7c967942dac0e8cc4a29ba7ea3f4e --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/pretrain_harness.py @@ -0,0 +1,340 @@ +from __future__ import annotations + +import json +import math +import os +import random +from pathlib import Path + +import numpy as np +import torch +import torch.nn as nn +from torch.nn import functional as F + +EOT_TOKEN = 50256 + + + +def set_determinism(seed: int) -> None: + """Pin every source of run-to-run variation this harness can reach.""" + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + os.environ["PYTHONHASHSEED"] = str(seed) + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.use_deterministic_algorithms(True) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.set_num_threads(1) + + + +class Pool: + """A token pool laid out as docs.jsonl + tokens.npy + offsets.npy.""" + + def __init__(self, pool_dir: str | os.PathLike): + self.dir = Path(pool_dir) + self.offsets = np.load(self.dir / "offsets.npy", mmap_mode="r") + self.tokens = np.load(self.dir / "tokens.npy", mmap_mode="r") + self.n_docs = int(self.offsets.shape[0] - 1) + self.ntokens = np.diff(np.asarray(self.offsets, dtype=np.int64)) + + def span(self, doc_id: int) -> np.ndarray: + a = int(self.offsets[doc_id]) + b = int(self.offsets[doc_id + 1]) + return np.asarray(self.tokens[a:b], dtype=np.int64) + + +def sanitize_selection(raw, ntokens: np.ndarray, budget_tokens: int): + """Turn an untrusted return value into the accepted document list. + + Contract (identical to the one stated in the task instructions): + * the value must be a list (or tuple) of ints; + * ids outside [0, N) are dropped; + * a repeat of an already-accepted id is dropped; + * documents are walked IN THE ORDER RETURNED and accepted whenever the running + token total plus that document's ntokens stays within budget_tokens; a document + that would overflow is skipped, never fatal. + + Returns (accepted_ids, tokens_used, stats). Raises ValueError when the value is not + a list of ints at all -- that is the invalid path, not a zero-length selection. + """ + if isinstance(raw, tuple): + raw = list(raw) + if not isinstance(raw, list): + raise ValueError(f"select() must return a list of ints, got {type(raw).__name__}") + n = int(ntokens.shape[0]) + accepted: list[int] = [] + seen: set[int] = set() + used = 0 + n_bad_type = 0 + n_out_of_range = 0 + n_duplicate = 0 + n_overflow = 0 + for item in raw: + if isinstance(item, bool) or not isinstance(item, (int, np.integer)): + n_bad_type += 1 + continue + i = int(item) + if i < 0 or i >= n: + n_out_of_range += 1 + continue + if i in seen: + n_duplicate += 1 + continue + cost = int(ntokens[i]) + if used + cost > budget_tokens: + n_overflow += 1 + continue + seen.add(i) + accepted.append(i) + used += cost + stats = { + "n_returned": len(raw), + "n_accepted": len(accepted), + "tokens_used": used, + "n_bad_type": n_bad_type, + "n_out_of_range": n_out_of_range, + "n_duplicate": n_duplicate, + "n_overflow": n_overflow, + } + return accepted, used, stats + + +def build_block_stream(pool: Pool, doc_ids, block_size: int, perm_seed: int) -> np.ndarray: + """Concatenate the selected documents in the order given, chunk into contiguous + blocks of block_size tokens, drop the final partial block, then permute the blocks + once with numpy.random.default_rng(perm_seed).""" + if len(doc_ids) == 0: + return np.zeros((0, block_size), dtype=np.uint16) + total = int(sum(int(pool.ntokens[i]) for i in doc_ids)) + flat = np.empty(total, dtype=np.uint16) + at = 0 + for i in doc_ids: + a = int(pool.offsets[i]) + b = int(pool.offsets[i + 1]) + k = b - a + flat[at:at + k] = pool.tokens[a:b] + at += k + n_blocks = total // block_size + if n_blocks == 0: + return np.zeros((0, block_size), dtype=np.uint16) + blocks = flat[: n_blocks * block_size].reshape(n_blocks, block_size) + perm = np.random.default_rng(perm_seed).permutation(n_blocks) + return np.ascontiguousarray(blocks[perm]) + + +def load_eval_blocks(eval_dir: str | os.PathLike, block_size: int) -> np.ndarray: + """The evaluation shard, already concatenated document-by-document at build time + (each document followed by one EOT), chunked into contiguous blocks with the final + partial block dropped. No permutation: the evaluation set is a fixed set.""" + toks = np.load(Path(eval_dir) / "tokens.npy", mmap_mode="r") + n_blocks = int(toks.shape[0]) // block_size + arr = np.asarray(toks[: n_blocks * block_size], dtype=np.uint16) + return arr.reshape(n_blocks, block_size) + + + +class CausalSelfAttention(nn.Module): + def __init__(self, cfg): + super().__init__() + assert cfg["n_embd"] % cfg["n_head"] == 0 + self.n_head = cfg["n_head"] + self.n_embd = cfg["n_embd"] + self.c_attn = nn.Linear(cfg["n_embd"], 3 * cfg["n_embd"], bias=cfg["bias"]) + self.c_proj = nn.Linear(cfg["n_embd"], cfg["n_embd"], bias=cfg["bias"]) + + def forward(self, x): + B, T, C = x.size() + q, k, v = self.c_attn(x).split(self.n_embd, dim=2) + hs = C // self.n_head + q = q.view(B, T, self.n_head, hs).transpose(1, 2) + k = k.view(B, T, self.n_head, hs).transpose(1, 2) + v = v.view(B, T, self.n_head, hs).transpose(1, 2) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True) + y = y.transpose(1, 2).contiguous().view(B, T, C) + return self.c_proj(y) + + +class MLP(nn.Module): + def __init__(self, cfg): + super().__init__() + self.c_fc = nn.Linear(cfg["n_embd"], 4 * cfg["n_embd"], bias=cfg["bias"]) + self.c_proj = nn.Linear(4 * cfg["n_embd"], cfg["n_embd"], bias=cfg["bias"]) + + def forward(self, x): + return self.c_proj(F.gelu(self.c_fc(x), approximate="tanh")) + + +class Block(nn.Module): + def __init__(self, cfg): + super().__init__() + self.ln_1 = nn.LayerNorm(cfg["n_embd"], bias=cfg["bias"]) + self.attn = CausalSelfAttention(cfg) + self.ln_2 = nn.LayerNorm(cfg["n_embd"], bias=cfg["bias"]) + self.mlp = MLP(cfg) + + def forward(self, x): + x = x + self.attn(self.ln_1(x)) + x = x + self.mlp(self.ln_2(x)) + return x + + +class GPT(nn.Module): + def __init__(self, cfg): + super().__init__() + self.cfg = cfg + self.wte = nn.Embedding(cfg["vocab_size"], cfg["n_embd"]) + self.wpe = nn.Embedding(cfg["block_size"], cfg["n_embd"]) + self.h = nn.ModuleList([Block(cfg) for _ in range(cfg["n_layer"])]) + self.ln_f = nn.LayerNorm(cfg["n_embd"], bias=cfg["bias"]) + self.lm_head = nn.Linear(cfg["n_embd"], cfg["vocab_size"], bias=False) + self.lm_head.weight = self.wte.weight + self.apply(self._init_weights) + scale = 0.02 / math.sqrt(2 * cfg["n_layer"]) + for name, p in self.named_parameters(): + if name.endswith("c_proj.weight"): + torch.nn.init.normal_(p, mean=0.0, std=scale) + + def _init_weights(self, module): + if isinstance(module, nn.Linear): + torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) + if module.bias is not None: + torch.nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) + + def forward(self, idx): + B, T = idx.size() + pos = torch.arange(0, T, dtype=torch.long, device=idx.device) + x = self.wte(idx) + self.wpe(pos) + for block in self.h: + x = block(x) + return self.lm_head(self.ln_f(x)) + + +def n_parameters(model: GPT) -> int: + seen, total = set(), 0 + for p in model.parameters(): + if id(p) in seen: + continue + seen.add(id(p)) + total += p.numel() + return total + + + +def _lr_at(step: int, cfg) -> float: + warm = cfg["warmup_steps"] + if step < warm: + return cfg["learning_rate"] * (step + 1) / warm + prog = (step - warm) / max(1, cfg["max_steps"] - warm) + prog = min(1.0, max(0.0, prog)) + coeff = 0.5 * (1.0 + math.cos(math.pi * prog)) + return cfg["min_lr"] + coeff * (cfg["learning_rate"] - cfg["min_lr"]) + + +def train_model(cfg, blocks: np.ndarray, device: str = "cuda", log=print) -> GPT: + """Train a fresh model from random initialisation on `blocks`, consumed cyclically. + + Deterministic: seeded init, seeded data order, deterministic kernels, no TF32. + """ + set_determinism(cfg["seed"]) + torch.manual_seed(cfg["seed"]) + model = GPT(cfg).to(device) + log(f"[train] parameters={n_parameters(model)}") + + decay, nodecay = [], [] + for _, p in model.named_parameters(): + if not p.requires_grad: + continue + (decay if p.dim() >= 2 else nodecay).append(p) + optim = torch.optim.AdamW( + [{"params": decay, "weight_decay": cfg["weight_decay"]}, + {"params": nodecay, "weight_decay": 0.0}], + lr=cfg["learning_rate"], betas=(cfg["beta1"], cfg["beta2"]), eps=1e-8, fused=False, + ) + + micro = cfg["micro_batch_size"] + seqs_per_step = cfg["tokens_per_step"] // cfg["block_size"] + assert seqs_per_step % micro == 0, "tokens_per_step/block_size must be a multiple of micro_batch_size" + accum = seqs_per_step // micro + n_blocks = int(blocks.shape[0]) + if n_blocks == 0: + raise ValueError("empty training stream") + + cursor = 0 + model.train() + for step in range(cfg["max_steps"]): + lr = _lr_at(step, cfg) + for group in optim.param_groups: + group["lr"] = lr + optim.zero_grad(set_to_none=True) + for _ in range(accum): + idx = (cursor + np.arange(micro)) % n_blocks + cursor = (cursor + micro) % n_blocks + batch = torch.from_numpy(blocks[idx].astype(np.int64)).to(device, non_blocking=False) + x, y = batch[:, :-1], batch[:, 1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = model(x) + loss = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), y.reshape(-1) + ) + (loss / accum).backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"]) + optim.step() + if step % 100 == 0 or step == cfg["max_steps"] - 1: + log(f"[train] step {step}/{cfg['max_steps']} lr {lr:.3e} loss {loss.item():.4f}") + return model + + +@torch.no_grad() +def eval_perplexity(model: GPT, eval_blocks: np.ndarray, cfg, device: str = "cuda"): + """Token-weighted mean cross-entropy over predicted positions 1..block_size-1. + + Position 0 of each block has no context and is excluded. Perplexity is + exp(total_ce / total_predicted_positions) -- one mean over the whole shard, not a + mean of per-block perplexities. + """ + model.eval() + micro = cfg["micro_batch_size"] + total_ce = 0.0 + total_pos = 0 + for start in range(0, int(eval_blocks.shape[0]), micro): + chunk = eval_blocks[start:start + micro] + batch = torch.from_numpy(chunk.astype(np.int64)).to(device) + x, y = batch[:, :-1], batch[:, 1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = model(x) + ce = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), y.reshape(-1), reduction="sum" + ) + total_ce += float(ce.item()) + total_pos += int(y.numel()) + if total_pos == 0: + raise ValueError("empty evaluation set") + mean_ce = total_ce / total_pos + return {"total_ce": total_ce, "n_positions": total_pos, + "mean_ce": mean_ce, "perplexity": math.exp(mean_ce)} + + +def load_config(path: str | os.PathLike) -> dict: + with open(path, "r", encoding="utf-8") as fh: + return json.load(fh) + + +def run_cycle(cfg, pool: Pool, doc_ids, eval_blocks: np.ndarray, device="cuda", log=print): + """One full train-then-evaluate cycle over the given document ids.""" + blocks = build_block_stream(pool, doc_ids, cfg["block_size"], cfg["block_permutation_seed"]) + log(f"[cycle] docs={len(doc_ids)} blocks={blocks.shape[0]}") + model = train_model(cfg, blocks, device=device, log=log) + out = eval_perplexity(model, eval_blocks, cfg, device=device) + del model + torch.cuda.empty_cache() + out["n_blocks"] = int(blocks.shape[0]) + out["n_docs"] = len(doc_ids) + log(f"[cycle] perplexity={out['perplexity']:.6f}") + return out diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/requirements-verifier.txt b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..04676c89520bf969f2cb861ad1811f46d8370700 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/requirements-verifier.txt @@ -0,0 +1,2 @@ +pytest==8.3.5 +pytest-json-ctrf==0.3.5 diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/test.sh b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b45b02a58a5afd4d762ebe145fdb47442bdbd24 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/test.sh @@ -0,0 +1,29 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +default_reward() { + if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /logs/verifier/reward.txt; fi +} +trap 'default_reward' EXIT +trap 'default_reward; exit 0' HUP INT TERM + +chmod -R go-rwx /tests + +export HIDDEN_SPLIT=final +export PYTHONHASHSEED=0 +export OMP_NUM_THREADS=1 +export MKL_NUM_THREADS=1 +export OPENBLAS_NUM_THREADS=1 +export NUMEXPR_NUM_THREADS=1 +export CUBLAS_WORKSPACE_CONFIG=:4096:8 + +cd /tests +/usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +/usr/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/test_state.py b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..61c45123fc95a42ee424179b9b4c196bb82742dc --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/test_state.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import json +import os +import sys +import traceback +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import grader_core +import pretrain_harness + +METRIC_PATH = Path("/logs/verifier/metric.json") +SPLIT = os.environ.get("HIDDEN_SPLIT", "final") +HIDDEN = Path(__file__).resolve().parent / "hidden_data" / SPLIT +CONFIG = Path(__file__).resolve().parent / "train_config.json" +SESSION = Path("/tmp/grade-session") + + +def _write(record: dict) -> None: + METRIC_PATH.parent.mkdir(parents=True, exist_ok=True) + METRIC_PATH.write_text(json.dumps(record, indent=2, sort_keys=True, default=str)) + + +def test_split_integrity(): + """The graded pool and the graded evaluation shard share no document. + + Asserted here, at grade time, on the shipped bytes -- not only in the builder that + produced them. The duplicate-key fixture rows make the check meaningful: a set-based + intersection over unique keys cannot detect grouped leakage, so the fixture below + deliberately repeats a key on each side and the assertion still has to hold. + """ + guard = json.loads((HIDDEN / "eval" / "guard.json").read_text()) + eval_hashes = set(guard["hashes"]) + eval_urls = set(guard["urls"]) + pool_meta = json.loads((HIDDEN / "pool" / "meta.json").read_text()) + pool_guard = json.loads((HIDDEN / "pool" / "guard.json").read_text()) + pool_hashes = set(pool_guard["hashes"]) + pool_urls = set(pool_guard["urls"]) + assert pool_hashes, "the graded pool shipped no document hashes" + assert eval_hashes, "the graded evaluation shard shipped no document hashes" + assert not (pool_hashes & eval_hashes), "pool/eval text overlap" + assert not (pool_urls & eval_urls), "pool/eval URL overlap" + assert pool_meta["n_tokens"] > 200_000_000, pool_meta + + fix_pool = ["k1", "k1", "k2", "k3", "k3"] + fix_eval = ["k4", "k4", "k5"] + assert not (set(fix_pool) & set(fix_eval)) + assert len(fix_pool) != len(set(fix_pool)) and len(fix_eval) != len(set(fix_eval)) + leaky_eval = ["k2", "k2", "k9"] + assert set(fix_pool) & set(leaky_eval), "the disjointness assertion cannot detect leakage" + + +def test_writable_surface(): + """The verifier reads exactly the files instruction.md lets a solution change. + + instruction.md, "Files you may change", names `/app/output/select.py` plus any further file + under `/app/output/` as the complete writable surface, and states that the harness, the + config and everything else under `/app` are development material the grader never reads. + This asserts the verifier honours that same list: the deliverable it stages is `/app/output` + and its entry point is `select.py`; the harness, the config and the graded data come from + the sealed tree beside this file; and no agent-editable path is reachable as an import or + present in this image. It scores nothing -- no submission can influence it. + """ + sealed = Path(__file__).resolve().parent + assert grader_core.DELIVERABLE_DIR == "/app/output" + assert grader_core.ENTRY_POINT == "select.py" + assert grader_core.WRITABLE_SURFACE_ROOT == grader_core.DELIVERABLE_DIR + assert Path(pretrain_harness.__file__).resolve().parent == sealed + assert CONFIG.is_file() and CONFIG.resolve().parent == sealed + assert str(HIDDEN.resolve()).startswith(str(sealed) + os.sep) + for name in ("pool", "eval"): + assert (HIDDEN / name).is_dir(), f"the sealed {name} is missing" + assert grader_core.writable_surface_violations(CONFIG) == [] + + +def test_grade(): + """Execute the submission, recompute the metric from the sealed slice, write it out.""" + record = {"reward": 0.0, "valid": False, "invalid_reason": "grader did not complete", + "split": SPLIT} + try: + try: + import torch + record["grader_cuda_device_count"] = int(torch.cuda.device_count()) + record["grader_cuda_available"] = bool(torch.cuda.is_available()) + except Exception as exc: + record["grader_cuda_device_count"] = -1 + record["infra_error"] = f"the grader itself cannot reach CUDA: {exc}" + + raw = grader_core.grade( + deliverable_src=grader_core.DELIVERABLE_DIR, + pool_dir=HIDDEN / "pool", + eval_dir=HIDDEN / "eval", + config_path=CONFIG, + session_dir=SESSION, + log=lambda msg: print(msg, flush=True), + ) + raw["split"] = SPLIT + record = grader_core.finalize(raw) + except BaseException: + record = {"reward": 0.0, "valid": False, "split": SPLIT, + "invalid_reason": "grader raised", + "traceback": traceback.format_exc()[-6000:]} + finally: + _write(record) + + print(json.dumps({k: v for k, v in record.items() + if k not in ("select_stderr_tail", "traceback", "grade_traceback")}, + indent=2, sort_keys=True, default=str), flush=True) + assert isinstance(record["reward"], float) and 0.0 <= record["reward"] <= 1.0 diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/train_config.json b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/train_config.json new file mode 100644 index 0000000000000000000000000000000000000000..6817b260d074bfce4020eae2d4a05defc470acd3 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/are-grader-ctx/train_config.json @@ -0,0 +1,20 @@ +{ + "beta1": 0.9, + "beta2": 0.95, + "bias": true, + "block_permutation_seed": 1234, + "block_size": 1024, + "grad_clip": 1.0, + "learning_rate": 0.0006, + "max_steps": 1500, + "micro_batch_size": 16, + "min_lr": 6e-05, + "n_embd": 768, + "n_head": 12, + "n_layer": 12, + "seed": 1234, + "tokens_per_step": 131072, + "vocab_size": 50257, + "warmup_steps": 100, + "weight_decay": 0.1 +} diff --git a/tasks/less-is-more-pretrain-token-budget-selector/environment/docker-compose.yaml b/tasks/less-is-more-pretrain-token-budget-selector/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac404596f9afda89cd148f274b7d7134c2fdd22e --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/environment/docker-compose.yaml @@ -0,0 +1,94 @@ +# ARE 1.1: grading lives in sidecars. Harbor configures `main` (build, limits, network). +services: + main: + depends_on: + grader: + condition: service_healthy + volumes: + - are-deliverable-0:/app/output + + grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: val + platform: linux/amd64 + environment: + ARE_ROLE: val + ARE_PORT: "8000" + ARE_BUDGET_SEC: "86400" + ARE_ARTIFACT_PATHS: "/app/output" + ARE_AGENT_UID: "1001" + ARE_GRADE_TIMEOUT_SEC: "14400" + volumes: + - are-deliverable-0:/run/are-deliverable/app/output + - are-secret:/run/are-secret + expose: + - "8000" + cap_add: [SYS_ADMIN] + networks: [default, are-private] + cpus: 8 + mem_limit: 32768m + deploy: + resources: + reservations: + devices: + - driver: nvidia + # GPU 0 is shared with the agent (works on any 1-GPU host). On a host with a + # spare GPU, export ARE_GRADER_GPU=1 to give grading its own, as in ARE 1.0. + device_ids: ["${ARE_GRADER_GPU:-0}"] + capabilities: [gpu] + depends_on: + test-grader: + condition: service_healthy + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + + test-grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: test + platform: linux/amd64 + environment: + ARE_ROLE: test + ARE_PORT: "8001" + ARE_ARTIFACT_PATHS: "/app/output" + ARE_GRADE_TIMEOUT_SEC: "14400" + expose: + - "8001" + volumes: + - are-secret:/run/are-secret + cap_add: [SYS_ADMIN] + networks: [are-private] + cpus: 8 + mem_limit: 32768m + deploy: + resources: + reservations: + devices: + - driver: nvidia + # GPU 0 is shared with the agent (works on any 1-GPU host). On a host with a + # spare GPU, export ARE_GRADER_GPU=1 to give grading its own, as in ARE 1.0. + device_ids: ["${ARE_GRADER_GPU:-0}"] + capabilities: [gpu] + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8001/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + +volumes: + are-deliverable-0: {} + are-secret: {} + +networks: + are-private: + internal: true diff --git a/tasks/less-is-more-pretrain-token-budget-selector/task.toml b/tasks/less-is-more-pretrain-token-budget-selector/task.toml index a3e25e123fab827258181566c7551e01473e0f92..73551a5d8250327f1457959cff96ddc98ac2b02c 100644 --- a/tasks/less-is-more-pretrain-token-budget-selector/task.toml +++ b/tasks/less-is-more-pretrain-token-budget-selector/task.toml @@ -1,13 +1,20 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/less-is-more-pretrain-token-budget-selector" -version = "1.0.0" +version = "1.1.0" description = "" -keywords = [ "autoresearch", "machine-learning", "benchmark",] -[[task.authors]] -name = "Bespoke Labs" +keywords = [ + "autoresearch", + "machine-learning", + "benchmark", +] +authors = [ + { name = "Bespoke Labs" }, +] [metadata] task_slug = "less-is-more-pretrain-token-budget-selector" @@ -22,33 +29,48 @@ degenerate_reward = 0.1 graded_gpu = "H100" dataset = "allenai/c4 (en and en.noclean), revision 1588ec454efa1a09f29cd18ddd04fe05fc8653a2" notes = "Open-ended: continuous reward in [0,1], no threshold, no reference solution. Anchors and measurements are never disclosed to the agent." +are_version = "1.1" +budget_seconds = 86400 [verifier] -network_mode = "no-network" -timeout_sec = 14400.0 +timeout_sec = 600.0 environment_mode = "separate" -collect = [] -[verifier.env] +[[verifier.collect]] +service = "grader" +command = "/opt/are/venv/bin/python /opt/are/drain.py" +timeout_sec = 28800.0 + +[verifier.environment] +network_mode = "no-network" +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +gpus = 0 [agent] network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] -timeout_sec = 28800.0 +allowed_hosts = [ + "api.openai.com", + "api.anthropic.com", + "grader", +] +timeout_sec = 86400.0 user = "agent" [environment] -network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] +network_mode = "public" build_timeout_sec = 10800.0 os = "linux" cpus = 8 memory_mb = 32768 storage_mb = 307200 gpus = 1 -gpu_types = [ "H100",] -mcp_servers = [] +gpu_types = [ + "H100", +] +mcp_servers = [ + { name = "are", transport = "streamable-http", url = "http://grader:8000/mcp" }, +] [environment.env] - -[solution.env] diff --git a/tasks/less-is-more-pretrain-token-budget-selector/tests/Dockerfile b/tasks/less-is-more-pretrain-token-budget-selector/tests/Dockerfile index 54dfbc537d7eaabee396d24dbb1d8b1bf4a357d5..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/less-is-more-pretrain-token-budget-selector/tests/Dockerfile +++ b/tasks/less-is-more-pretrain-token-budget-selector/tests/Dockerfile @@ -1,65 +1,2 @@ -FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 - -ENTRYPOINT [] -ENV PYTHONPATH= -ENV PYTHONSAFEPATH=1 -ENV PYTHONHASHSEED=0 \ - PYTHONDONTWRITEBYTECODE=1 \ - PIP_NO_CACHE_DIR=1 \ - PIP_DISABLE_PIP_VERSION_CHECK=1 \ - OMP_NUM_THREADS=1 \ - MKL_NUM_THREADS=1 \ - OPENBLAS_NUM_THREADS=1 \ - NUMEXPR_NUM_THREADS=1 \ - CUBLAS_WORKSPACE_CONFIG=:4096:8 \ - HF_HUB_DISABLE_PROGRESS_BARS=1 - -RUN useradd --create-home --uid 1001 agent - -COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt -RUN /usr/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements-verifier.txt \ - && rm /tmp/requirements-verifier.txt - -RUN /usr/bin/python3 -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='openai-community/gpt2', revision='607a30d783dfa663caf39e06633721c8d4cfcd7e', local_dir='/opt/assets/gpt2', allow_patterns=['config.json','generation_config.json','merges.txt','vocab.json','tokenizer.json','model.safetensors']); snapshot_download(repo_id='EleutherAI/pythia-160m', revision='50f5173d932e8e61f858120bcb800b97af589f46', local_dir='/opt/assets/pythia-160m', allow_patterns=['config.json','generation_config.json','tokenizer.json','tokenizer_config.json','special_tokens_map.json','model.safetensors'])" && rm -rf /opt/assets/gpt2/.cache /opt/assets/pythia-160m/.cache - -COPY . /tests - -RUN set -eux; \ - REV=1588ec454efa1a09f29cd18ddd04fe05fc8653a2; \ - B="https://huggingface.co/datasets/allenai/c4/resolve/$REV"; \ - TK=/opt/assets/gpt2/tokenizer.json; \ - mkdir -p /tmp/corpus /tests/hidden_data; \ - curl -sSL -o /tmp/corpus/valF.json.gz "$B/en/c4-validation.00003-of-00008.json.gz"; \ - curl -sSL -o /tmp/corpus/valI.json.gz "$B/en/c4-validation.00005-of-00008.json.gz"; \ - curl -sSL -o /tmp/corpus/trF0.json.gz "$B/en/c4-train.00777-of-01024.json.gz"; \ - curl -sSL -o /tmp/corpus/trF1.json.gz "$B/en/c4-train.00778-of-01024.json.gz"; \ - curl -sSL -o /tmp/corpus/ncF.json.gz "$B/en.noclean/c4-train.00777-of-07168.json.gz"; \ - curl -sSL -o /tmp/corpus/trI0.json.gz "$B/en/c4-train.00888-of-01024.json.gz"; \ - curl -sSL -o /tmp/corpus/trI1.json.gz "$B/en/c4-train.00889-of-01024.json.gz"; \ - curl -sSL -o /tmp/corpus/ncI.json.gz "$B/en.noclean/c4-train.00888-of-07168.json.gz"; \ - export TOKENIZERS_PARALLELISM=true; \ - /usr/bin/python3 /tests/build_data.py eval --shards /tmp/corpus/valF.json.gz \ - --out /tests/hidden_data/final/eval --tokenizer $TK --target-tokens 2000000; \ - /usr/bin/python3 /tests/build_data.py pool --shards /tmp/corpus/trF0.json.gz /tmp/corpus/trF1.json.gz \ - --shards-b /tmp/corpus/ncF.json.gz --target-tokens 250000000 --target-tokens-b 62500000 \ - --out /tests/hidden_data/final/pool --tokenizer $TK \ - --guard /tests/hidden_data/final/eval/guard.json; \ - /usr/bin/python3 /tests/build_data.py eval --shards /tmp/corpus/valI.json.gz \ - --out /tests/hidden_data/intermediate/eval --tokenizer $TK --target-tokens 2000000; \ - /usr/bin/python3 /tests/build_data.py pool --shards /tmp/corpus/trI0.json.gz /tmp/corpus/trI1.json.gz \ - --shards-b /tmp/corpus/ncI.json.gz --target-tokens 250000000 --target-tokens-b 62500000 \ - --out /tests/hidden_data/intermediate/pool --tokenizer $TK \ - --guard /tests/hidden_data/intermediate/eval/guard.json; \ - rm -rf /tmp/corpus - -RUN mkdir -p /app/output /logs/verifier - -RUN chown -R root:root /tests \ - && chmod 700 /tests/hidden_data \ - && chmod +x /tests/test.sh /tests/intermediate.sh \ - && find /tests -exec touch -d @1700000000 {} + - -WORKDIR /tests - -ENV HF_HUB_OFFLINE=1 -ENV TRANSFORMERS_OFFLINE=1 +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/less-is-more-pretrain-token-budget-selector/tests/finalize.py b/tasks/less-is-more-pretrain-token-budget-selector/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/less-is-more-pretrain-token-budget-selector/tests/finalize.py @@ -0,0 +1,59 @@ +"""Final verifier: score the run from the grader ledger. + +reward hidden test score of the submission with the best validation score + (ties go to the earlier submission); 0 if nothing was submitted. +auarc area under the curve of that same quantity over the wall-clock budget, + using the time each validation score became available, divided by the + budget. 0 before the first graded submission. +""" + +import json +from pathlib import Path + +STATE = Path("/var/lib/are") +OUT = Path("/logs/verifier") +OUT.mkdir(parents=True, exist_ok=True) + +meta = json.loads((STATE / "meta.json").read_text()) if (STATE / "meta.json").exists() else {} +budget = float(meta.get("budget_seconds") or 1.0) + +subs: dict[int, dict] = {} +ledger = STATE / "ledger.jsonl" +for line in (ledger.read_text().splitlines() if ledger.exists() else []): + ev = json.loads(line) + s = subs.setdefault(ev["id"], {"id": ev["id"]}) + if ev["event"] == "submitted": + s["submitted_t"] = ev["t"] + elif ev["event"] == "val": + s["val"] = ev["score"] + s["val_t"] = ev["t"] + elif ev["event"] == "test": + s["test"] = ev["score"] + +graded = sorted((s for s in subs.values() if "val" in s), key=lambda s: s["val_t"]) + +# Step function of the hidden score of the best-validation pick over time. +auc, best, last_t, cur = 0.0, None, 0.0, 0.0 +timeline = [] +for s in graded: + t = min(s["val_t"], budget) + auc += cur * (t - last_t) + last_t = t + if best is None or s["val"] > best["val"] or (s["val"] == best["val"] and s["id"] < best["id"]): + best = s + cur = float(best.get("test") or 0.0) + timeline.append({"t": s["val_t"], "id": s["id"], "val": s["val"], "test": s.get("test"), + "pick": best["id"]}) +auc += cur * (budget - last_t) if last_t < budget else 0.0 + +reward = { + "reward": float(best.get("test") or 0.0) if best else 0.0, + "auarc": auc / budget, + "best_val": float(best["val"]) if best else 0.0, + "n_submissions": float(len(subs)), + "n_test_graded": float(sum(s.get("test") is not None for s in subs.values())), +} +(OUT / "reward.json").write_text(json.dumps(reward)) +(OUT / "timeline.json").write_text(json.dumps({"budget": budget, "selected": best and best["id"], + "submissions": timeline}, indent=1)) +print(json.dumps(reward, indent=1)) diff --git a/tasks/less-is-more-pretrain-token-budget-selector/tests/test.sh b/tasks/less-is-more-pretrain-token-budget-selector/tests/test.sh index 0b45b02a58a5afd4d762ebe145fdb47442bdbd24..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/less-is-more-pretrain-token-budget-selector/tests/test.sh +++ b/tasks/less-is-more-pretrain-token-budget-selector/tests/test.sh @@ -1,29 +1,2 @@ #!/bin/bash -set -u - -mkdir -p /logs/verifier -chown root:root /logs/verifier 2>/dev/null || true -chmod 755 /logs/verifier 2>/dev/null || true -rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json - -default_reward() { - if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /logs/verifier/reward.txt; fi -} -trap 'default_reward' EXIT -trap 'default_reward; exit 0' HUP INT TERM - -chmod -R go-rwx /tests - -export HIDDEN_SPLIT=final -export PYTHONHASHSEED=0 -export OMP_NUM_THREADS=1 -export MKL_NUM_THREADS=1 -export OPENBLAS_NUM_THREADS=1 -export NUMEXPR_NUM_THREADS=1 -export CUBLAS_WORKSPACE_CONFIG=:4096:8 - -cd /tests -/usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA -/usr/bin/python3 /tests/compute_reward.py - -exit 0 +python3 /tests/finalize.py diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/.dockerignore b/tasks/mlh-coco-16bit-hash-head-map5000/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/Dockerfile b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ac2db52aaf1ac1bab5fe08079ef04b14b8c08741 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,33 @@ +FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONHASHSEED=0 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=8 \ + MKL_NUM_THREADS=8 \ + OPENBLAS_NUM_THREADS=8 \ + HF_HUB_OFFLINE=1 \ + TRANSFORMERS_OFFLINE=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements.txt /tmp/requirements.txt +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ + -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements.txt /tmp/requirements-verifier.txt + +RUN mkdir -p /app/output /logs/verifier + +COPY . /tests + +RUN chown -R root:root /tests \ + && chmod -R 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/Dockerfile.are b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..8c5951af80e4e594d9f4279980a24b02817949fa --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,51 @@ +FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONHASHSEED=0 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=8 \ + MKL_NUM_THREADS=8 \ + OPENBLAS_NUM_THREADS=8 \ + HF_HUB_OFFLINE=1 \ + TRANSFORMERS_OFFLINE=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements.txt /tmp/requirements.txt +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ + -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements.txt /tmp/requirements-verifier.txt + +RUN mkdir -p /app/output /logs/verifier + +COPY . /tests + +RUN chown -R root:root /tests \ + && chmod -R 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + + +# ---- ARE 1.1 grader layer (appended to the task's own verifier Dockerfile) ---- +ARG ARE_ROLE +# python.org images ship /usr/local/bin/python3; distro-python bases (kaggle GPU) lack +# ensurepip, so fall back to a pip-less venv filled by the base interpreter's pip. +RUN PY=$(command -v /usr/local/bin/python3 || command -v python3) \ + && if "$PY" -m venv /opt/are/venv; then \ + /opt/are/venv/bin/pip install --no-cache-dir "fastmcp==2.14.7"; \ + else rm -rf /opt/are/venv && "$PY" -m venv --without-pip /opt/are/venv \ + && "$PY" -m pip --python /opt/are/venv/bin/python install --no-cache-dir "fastmcp==2.14.7"; fi +COPY are/ /opt/are/ +# The val grader, whose output reaches the agent, never holds the private grader or its +# data. The test grader keeps everything; nothing from it reaches the agent. +RUN rm -rf /tests/are /tests/Dockerfile.are \ + && if [ "$ARE_ROLE" = "val" ]; then rm -rf /tests/test.sh /tests/hidden_data/final; fi +ENV ARE_ROLE=$ARE_ROLE +CMD ["/opt/are/venv/bin/python", "/opt/are/server.py"] diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/are/drain.py b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/are/drain.py @@ -0,0 +1,25 @@ +"""Verifier collect hook, run after the agent stops. + +Grades the final workspace as one last submission (unless it equals the last one), +then waits until every submission has both grades recorded. +""" + +import json +import time +import urllib.request +from pathlib import Path + +TOKEN = Path("/run/are-secret/token").read_text().strip() +H = {"x-are-token": TOKEN} + +req = urllib.request.Request("http://localhost:8000/final", method="POST", headers=H) +with urllib.request.urlopen(req, timeout=120) as resp: + print("final:", json.loads(resp.read()), flush=True) + +while True: + with urllib.request.urlopen(urllib.request.Request("http://localhost:8000/drain", headers=H), timeout=30) as resp: + state = json.loads(resp.read()) + print(state, flush=True) + if state["val_pending"] == 0 and state["test_pending"] == 0: + break + time.sleep(5) diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/are/server.py b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/are/server.py @@ -0,0 +1,538 @@ +"""ARE 1.1 grader sidecar. + +One image, two roles: + +- ARE_ROLE=val ("grader" service). Reachable from the agent. Serves MCP tools and a + REST fallback. On submit it snapshots the shared deliverable volume, grades the + snapshot with the task's public grader (intermediate.sh), and returns only that + score. Every snapshot is also sent to the test grader; the hidden score goes to a + root-only ledger and never back to the agent. +- ARE_ROLE=test ("test-grader" service). On a private network that only the val + grader can reach. Grades snapshots with the task's private grader (test.sh). +""" + +from __future__ import annotations + +import asyncio +import gzip +import hashlib +import io +import secrets +import json +import os +import queue +import shutil +import subprocess +import tarfile +import threading +import time +import urllib.request +from pathlib import Path + +from fastmcp import FastMCP +from starlette.requests import Request +from starlette.responses import JSONResponse, Response + +ROLE = os.environ.get("ARE_ROLE", "val") +PORT = int(os.environ.get("ARE_PORT", "8000")) +STATE = Path(os.environ.get("ARE_STATE_DIR", "/var/lib/are")) +ARTIFACT_PATHS = [p for p in os.environ.get("ARE_ARTIFACT_PATHS", "/app/output").split(":") if p] +# The shared deliverable volume. Its parent is root-only, so submitted code (which every +# task grader runs as the unprivileged agent user) cannot reach it to write back to the agent. +SUBMISSION_ROOT = Path(os.environ.get("ARE_SUBMISSION_ROOT", "/run/are-deliverable")) +AGENT_UID = int(os.environ.get("ARE_AGENT_UID", "1001")) +BUDGET_SEC = float(os.environ.get("ARE_BUDGET_SEC", "14400")) +GRADE_TIMEOUT_SEC = float(os.environ.get("ARE_GRADE_TIMEOUT_SEC", "1800")) +TEST_GRADER_URL = os.environ.get("ARE_TEST_GRADER_URL", "http://test-grader:8001") +FEEDBACK_TAIL = int(os.environ.get("ARE_FEEDBACK_TAIL_CHARS", "8192")) +SCRIPT = "/tests/intermediate.sh" if ROLE == "val" else "/tests/test.sh" +# Shared only by the two graders (a volume the agent's container never mounts). The test +# grader writes a fresh token at startup; every internal request must carry it, so the +# agent cannot reach the test grader or the internal endpoints even on a shared network. +TOKEN_FILE = Path(os.environ.get("ARE_TOKEN_FILE", "/run/are-secret/token")) +TOKEN = "" + + +def _authorized(request: Request) -> bool: + """Internal endpoints need the graders' token; an unset token never matches.""" + return bool(TOKEN) and secrets.compare_digest(request.headers.get("x-are-token", ""), TOKEN) + + +def _net_isolation_available() -> bool: + try: + return subprocess.run(["unshare", "-n", "true"], capture_output=True, timeout=10).returncode == 0 + except Exception: + return False + + +NET_ISOLATED = False # set at startup: grader scripts run in an empty network namespace + +T0 = time.time() +_lock = threading.Lock() + + +def _elapsed() -> float: + return round(time.time() - T0, 1) + + +def _ledger(event: dict) -> None: + event = {"t": _elapsed(), "wall": time.time(), **event} + for attempt in range(3): + try: + with _lock, open(STATE / "ledger.jsonl", "a") as fh: + fh.write(json.dumps(event) + "\n") + return + except OSError: + if attempt == 2: + raise + time.sleep(1) + + +def _kill_grading_processes(proc: subprocess.Popen) -> None: + """Kill everything a timed-out grade started, including processes that left its group.""" + try: + os.killpg(proc.pid, 9) + except ProcessLookupError: + pass + _kill_other_processes() + + +def _kill_other_processes() -> None: + """Kill every process run by the agent user. Every task grader runs submitted code as + that user, so this stops all graded code (detached or not) and nothing else: the grader + server, the task's own grader and Harbor's hooks run as root.""" + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + if entry.stat().st_uid == AGENT_UID: + os.kill(int(entry.name), 9) + except (ProcessLookupError, PermissionError, FileNotFoundError): + pass + + +# Places the agent user (who runs submitted code inside every task grader) can write. +_BASELINE: set[str] = set() # every path that existed when the grader started (its image) + + +def _walk_one_fs(base: Path): + """Every path under base on base's own filesystem (skips /proc, /sys and other mounts).""" + dev = base.stat().st_dev + for root, dirs, files in os.walk(base): + dirs[:] = [d for d in dirs if os.lstat(os.path.join(root, d)).st_dev == dev] + for name in dirs + files: + yield Path(root) / name + + +def _all_paths() -> set[str]: + out = set() + for base in (Path("/"), Path("/dev/shm")): + if base.is_dir(): + out.update(str(q) for q in _walk_one_fs(base)) + return out + + +def _protected(path: str) -> bool: + keep = [str(STATE), "/opt/are", str(TOKEN_FILE.parent)] + return any(path == k or path.startswith(k + "/") for k in keep) + + +def _fresh_state() -> None: + """Start every grade from the grader image's own files, as ARE 1.0's fresh verifier + container did. The grader container lives for the whole run, so before each grade + stop anything an earlier grade left running and delete every file it created, + whoever wrote it. The deliverable volume and the token are separate mounts and are + never walked; the grader's own state is kept.""" + _kill_other_processes() + # System V shared memory, semaphores and queues outlive processes; this server uses none. + subprocess.run(["ipcrm", "--all"], capture_output=True) + for path in sorted(_all_paths() - _BASELINE, key=lambda q: q.count("/"), reverse=True): + if _protected(path): + continue + try: + q = Path(path) + if q.is_dir() and not q.is_symlink(): + shutil.rmtree(q, ignore_errors=True) + else: + q.unlink() + except OSError: + pass + + +def grade_snapshot(tar_bytes: bytes, tag: str) -> dict: + """Extract a snapshot over the artifact paths and run this role's grader script.""" + _fresh_state() + for path in ARTIFACT_PATHS: + p = Path(path) + if p.exists(): + shutil.rmtree(p) + p.mkdir(parents=True) + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:gz") as tf: + tf.extractall("/", filter="tar") + logs = Path("/logs/verifier") + if logs.exists(): + shutil.rmtree(logs) + logs.mkdir(parents=True) + started = time.time() + # Submitted code runs with no network, as in ARE 1.0's verifier. + cmd = (["unshare", "-n"] if NET_ISOLATED else []) + ["bash", SCRIPT] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + cwd="/tests", start_new_session=True) + try: + out, err = proc.communicate(timeout=GRADE_TIMEOUT_SEC) + error = None + except subprocess.TimeoutExpired: + _kill_grading_processes(proc) + out, err = proc.communicate() + error = f"grader timed out after {GRADE_TIMEOUT_SEC:.0f}s" + output = (out or "") + (err or "") + # Nothing a grade started may keep running after it, not even detached processes. + _kill_other_processes() + score = 0.0 + reward_file = logs / "reward.txt" + if reward_file.exists(): + try: + score = float(reward_file.read_text().strip() or 0) + except ValueError: + error = error or "unparseable reward" + metric = None + if (logs / "metric.json").exists(): + try: + metric = json.loads((logs / "metric.json").read_text()) + except ValueError: + pass + (STATE / "logs").mkdir(exist_ok=True) + (STATE / "logs" / f"{tag}.log").write_text(output) + return { + "score": score, + "metric": metric, + "error": error, + "net_isolated": NET_ISOLATED, + "seconds": round(time.time() - started, 1), + # What the agent sees, as in ARE 1.0: the grader's stdout tail (not stderr). + "output_tail": (out or "")[-FEEDBACK_TAIL:], + } + + +mcp = FastMCP("are") + + +# ---------------------------------------------------------------- test role + + +_grade_lock = threading.Lock() + + +def _grade_one_at_a_time(tar_bytes: bytes, tag: str) -> dict: + # A request that timed out on the caller's side may still be grading; the next one + # waits for it rather than sharing /app/output and /logs/verifier with it. + with _grade_lock: + return grade_snapshot(tar_bytes, tag) + + +if ROLE == "test": + + @mcp.custom_route("/grade", methods=["POST"]) + async def http_grade(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + tag = request.query_params.get("tag", "x") + body = await request.body() + result = await asyncio.to_thread(_grade_one_at_a_time, body, f"{tag}-test") + return JSONResponse(result) + + +# ----------------------------------------------------------------- val role + + +class Board: + """Submissions and their grading state. Hidden scores are never stored here.""" + + def __init__(self) -> None: + self.subs: dict[int, dict] = {} + self.val_q: queue.Queue[int] = queue.Queue() + self.next_id = 1 + self.test_pending = 0 + self.last_digest: str | None = None + + def public(self, sid: int) -> dict: + s = self.subs[sid] + out = {k: s[k] for k in ("id", "note", "submitted_at_s", "status")} + if s["status"] == "graded": + v = s["val"] + out.update( + validation_score=v["score"], + error=v["error"], + grading_seconds=v["seconds"], + grader_output_tail=v["output_tail"], + ) + return out + + def best(self) -> dict | None: + graded = [s for s in self.subs.values() if s["status"] == "graded"] + if not graded: + return None + b = max(graded, key=lambda s: (s["val"]["score"], -s["id"])) + return {"id": b["id"], "validation_score": b["val"]["score"]} + + +board = Board() + + +def snapshot() -> bytes: + """Deterministic tar.gz of the deliverable: same content, same bytes (gzip mtime 0).""" + raw = io.BytesIO() + with tarfile.open(fileobj=raw, mode="w") as tf: + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + tf.add(str(src), arcname=path.lstrip("/")) + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as gz: + gz.write(raw.getvalue()) + return out.getvalue() + + +def do_submit(note: str, final: bool = False) -> dict: + with _lock: + pending = [s["id"] for s in board.subs.values() if s["status"] != "graded"] + if pending and not final: + return { + "error": f"Submission {pending[0]} is still being graded. One submission is " + f"graded at a time: check result({pending[0]}) and submit again " + "once it has its score.", + "pending_id": pending[0], + } + sid = board.next_id + board.next_id += 1 + board.subs[sid] = {"id": sid, "note": note[:500], "submitted_at_s": _elapsed(), + "status": "queued"} + try: + data = snapshot() + digest = hashlib.sha256(data).hexdigest() + (STATE / "snapshots" / f"{sid:04d}.tar.gz").write_bytes(data) + _ledger({"event": "submitted", "id": sid, "note": note[:500], "bytes": len(data), + "sha256": digest, "final": final}) + except Exception as exc: + with _lock: + board.subs.pop(sid, None) # release the slot; the id is not reused + return {"error": f"Could not snapshot the deliverable ({exc}). Nothing was submitted. " + "Make sure nothing is writing to it, then submit again."} + board.last_digest = digest + with _lock: + board.test_pending += 1 + board.val_q.put(sid) + return {"id": sid, "status": "queued", + "hint": "Grading has started. Check result(id) for the validation score."} + + +def final_submit() -> dict: + """After the agent stops: grade the final workspace unless it was already submitted.""" + try: + data = snapshot() + except Exception as exc: + return {"error": f"final snapshot failed: {exc}"} + if board.subs and hashlib.sha256(data).hexdigest() == board.last_digest: + return {"skipped": "final workspace equals the last submission"} + return do_submit("final workspace (automatic)", final=True) + + +def grade_worker() -> None: + """Grade each submission on val, then on test, one submission at a time. + + The val score is published as soon as it is ready. The next submission's val grade + waits until this test grade is done, so the two graders never run at the same time. + """ + while True: + sid = board.val_q.get() + board.subs[sid]["status"] = "grading" + data = b"" + try: + data = (STATE / "snapshots" / f"{sid:04d}.tar.gz").read_bytes() + res = grade_snapshot(data, f"{sid:04d}-val") + except Exception as exc: + res = {"score": 0.0, "metric": None, "error": f"grader failed: {exc}", + "net_isolated": NET_ISOLATED, "seconds": 0.0, "output_tail": ""} + board.subs[sid]["val"] = res + board.subs[sid]["status"] = "graded" + try: + _ledger({"event": "val", "id": sid, **{k: res[k] for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + test_grade(sid, data) + + +def test_grade(sid: int, data: bytes) -> None: + try: + _test_grade(sid, data) + finally: + with _lock: + board.test_pending -= 1 + + +def _test_grade(sid: int, data: bytes) -> None: + """Send one snapshot to the test grader. A failed request is retried (the same snapshot + is graded again, so a retry can only recover the honest score); a request that ran + past its timeout is not, since the grade itself already took the full time.""" + started = time.time() + for attempt in range(3): + try: + req = urllib.request.Request( + f"{TEST_GRADER_URL}/grade?tag={sid:04d}", data=data, method="POST", + headers={"x-are-token": TOKEN}, + ) + with urllib.request.urlopen(req, timeout=2 * GRADE_TIMEOUT_SEC + 300) as resp: + res = json.loads(resp.read()) + break + except Exception as exc: # recorded, never shown to the agent + res = {"score": None, "metric": None, "error": f"test grader: {exc}", + "seconds": round(time.time() - started, 1)} + if attempt == 2 or isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError): + break + time.sleep(5) + try: + _ledger({"event": "test", "id": sid, **{k: res.get(k) for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + + +def with_time(out: dict) -> dict: + """Wall-clock accounting on every reply, as the v1 harness gave each phase.""" + out["total_budget_seconds"] = BUDGET_SEC + out["time_remaining_seconds"] = round(max(0.0, BUDGET_SEC - _elapsed()), 1) + return out + + +def status_dict() -> dict: + return { + "submissions": len(board.subs), + "queued_or_grading": sum(s["status"] != "graded" for s in board.subs.values()), + "best": board.best(), + } + + +def current_result(sid: int) -> dict: + return board.public(sid) + + +if ROLE == "val": + + @mcp.tool + async def submit(note: str = "") -> dict: + """Submit the current deliverable for grading. + + Snapshots the deliverable directory right now (later edits do not affect this + submission) and starts grading it on the public validation split. Returns at + once with a submission id. One submission is graded at a time: check `result` + and submit again once the previous submission has its score. `note` is a short + description of what changed. + """ + return with_time(await asyncio.to_thread(do_submit, note)) + + @mcp.tool + async def result(id: int) -> dict: + """The current state of a submission: queued, grading, or graded with its + validation score and grader output. Returns immediately.""" + if id not in board.subs: + return {"error": f"unknown submission id {id}"} + return with_time(current_result(id)) + + @mcp.tool + async def status() -> dict: + """Submission count, whether one is being graded, the best validation score, + and the time budget and time remaining.""" + return with_time(status_dict()) + + @mcp.custom_route("/submit", methods=["POST"]) + async def http_submit(request: Request) -> Response: + note = request.query_params.get("note", "") + return JSONResponse(with_time(await asyncio.to_thread(do_submit, note))) + + @mcp.custom_route("/result/{sid}", methods=["GET"]) + async def http_result(request: Request) -> Response: + sid = int(request.path_params["sid"]) + if sid not in board.subs: + return JSONResponse({"error": f"unknown submission id {sid}"}, status_code=404) + return JSONResponse(with_time(current_result(sid))) + + @mcp.custom_route("/status", methods=["GET"]) + async def http_status(request: Request) -> Response: + return JSONResponse(with_time(status_dict())) + + @mcp.custom_route("/final", methods=["POST"]) + async def http_final(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Collect hook, after the agent has stopped. + return JSONResponse(await asyncio.to_thread(final_submit)) + + @mcp.custom_route("/drain", methods=["GET"]) + async def http_drain(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Used by the verifier collect hook after the agent has stopped. + pending = sum(s["status"] != "graded" for s in board.subs.values()) + return JSONResponse({"val_pending": pending, "test_pending": board.test_pending}) + + +def _gpus() -> list[str]: + try: + out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=20) + return [l for l in out.stdout.splitlines() if l.strip()] + except Exception: + return [] + + +@mcp.custom_route("/health", methods=["GET"]) +async def health(request: Request) -> Response: + return JSONResponse({"ok": True, "role": ROLE, "gpus": await asyncio.to_thread(_gpus)}) + + +def _setup_token() -> None: + global TOKEN + if ROLE == "test": + TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True) + os.chmod(TOKEN_FILE.parent, 0o700) + TOKEN = secrets.token_hex(32) + TOKEN_FILE.write_text(TOKEN) + os.chmod(TOKEN_FILE, 0o600) + else: + for _ in range(300): # the test grader is healthy before this one starts + if TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip(): + break + time.sleep(1) + TOKEN = TOKEN_FILE.read_text().strip() + if not TOKEN: + raise SystemExit("ARE: empty internal token; refusing to start") + + +def main() -> None: + global NET_ISOLATED + NET_ISOLATED = _net_isolation_available() + if not NET_ISOLATED: + # Graded code must never have a network path (for example back through /submit). + raise SystemExit("ARE grader: cannot run grades without network access " + "(needs `unshare -n`, i.e. CAP_SYS_ADMIN); refusing to start") + STATE.mkdir(parents=True, exist_ok=True) + _BASELINE.update(_all_paths()) + _setup_token() + STATE.mkdir(parents=True, exist_ok=True) + os.chmod(STATE, 0o700) + (STATE / "snapshots").mkdir(exist_ok=True) + if ROLE == "val": + # The deliverable volume starts empty and root-owned; hand it to the agent user. + SUBMISSION_ROOT.mkdir(parents=True, exist_ok=True) + os.chmod(SUBMISSION_ROOT, 0o700) + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + src.mkdir(parents=True, exist_ok=True) + os.chown(src, AGENT_UID, AGENT_UID) + (STATE / "meta.json").write_text(json.dumps( + {"t0_wall": T0, "budget_seconds": BUDGET_SEC, "artifact_paths": ARTIFACT_PATHS} + )) + threading.Thread(target=grade_worker, daemon=True).start() + mcp.run(transport="http", host="0.0.0.0", port=PORT, show_banner=False, + uvicorn_config={"timeout_keep_alive": 86400}) + + +if __name__ == "__main__": + main() diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/compute_reward.py b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..54501469dc5d13d792fb0b43fb9c9875e26c9f7d --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,17 @@ +import json +import math +from pathlib import Path + +REWARD_PATH = Path("/logs/verifier/reward.txt") + +try: + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + value = float(json.loads(Path("/logs/verifier/metric.json").read_text())["reward"]) + if not math.isfinite(value): + raise ValueError("non-finite reward") + reward = f"{min(1.0, max(0.0, value)):.12g}" + REWARD_PATH.write_text(reward + "\n") + print(f"reward={reward}") +except Exception as exc: + REWARD_PATH.write_text("0\n") + print(f"reward=0 (fallback: {exc})") diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/grader_core.py b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..ae71cb349b73a23b9e2143cb6aeba3f67bcb8792 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,79 @@ +import numpy as np + +CODE_BITS = 16 +TOP_K = 5000 +QUERY_CHUNK = 250 + +M0 = 0.435 +BASELINE_SCORE = 0.7903 + + +class InvalidSubmission(Exception): + """The deliverable produced nothing gradeable. Routes to reward exactly 0.""" + + +def validate_codes(array, n_rows, what): + """Enforce the code contract stated in instruction.md: an (n_rows, 16) int8 array whose + every element is -1 or +1. Anything else is an invalid submission, not a low score.""" + if not isinstance(array, np.ndarray): + raise InvalidSubmission(f"{what}: not an array") + if array.shape != (n_rows, CODE_BITS): + raise InvalidSubmission(f"{what}: shape {array.shape}, expected {(n_rows, CODE_BITS)}") + if array.dtype != np.int8: + raise InvalidSubmission(f"{what}: dtype {array.dtype}, expected int8") + bad = np.setdiff1d(np.unique(array), np.array([-1, 1], dtype=np.int8)) + if bad.size: + raise InvalidSubmission(f"{what}: values outside {{-1, +1}}: {bad[:4].tolist()}") + return array + + +def map_at_k(query_codes, db_codes, query_labels, db_labels, top_k=TOP_K): + """mAP@top_k. Returns (mAP, diagnostics).""" + q = query_codes.astype(np.float32) + d = db_codes.astype(np.float32) + ql = query_labels.astype(np.float32) + dl = db_labels.astype(np.float32) + n_q, n_db = q.shape[0], d.shape[0] + k = min(top_k, n_db) + ranks = np.arange(1, k + 1, dtype=np.float64) + + aps = np.empty(n_q, dtype=np.float64) + rel_frac = np.empty(n_q, dtype=np.float64) + for start in range(0, n_q, QUERY_CHUNK): + stop = min(start + QUERY_CHUNK, n_q) + dist = ((CODE_BITS - q[start:stop] @ d.T) / 2).astype(np.int16) + relevant = (ql[start:stop] @ dl.T) > 0 + order = np.argsort(dist, axis=1, kind="stable")[:, :k] + rel = np.take_along_axis(relevant, order, axis=1) + hits = np.cumsum(rel, axis=1, dtype=np.float64) + total = hits[:, -1] + prec = hits / ranks + with np.errstate(invalid="ignore", divide="ignore"): + ap = np.where(total > 0, (prec * rel).sum(axis=1) / np.maximum(total, 1.0), 0.0) + aps[start:stop] = ap + rel_frac[start:stop] = relevant.mean(axis=1) + + diagnostics = { + "n_query": int(n_q), + "n_database": int(n_db), + "top_k": int(k), + "ap_mean": float(aps.mean()), + "ap_median": float(np.median(aps)), + "ap_p10": float(np.quantile(aps, 0.10)), + "ap_p90": float(np.quantile(aps, 0.90)), + "query_relevant_fraction_mean": float(rel_frac.mean()), + "distinct_query_codes": int(np.unique(query_codes, axis=0).shape[0]), + "distinct_db_codes": int(np.unique(db_codes, axis=0).shape[0]), + "db_bit_imbalance_max": float(np.abs(db_codes.astype(np.float64).mean(axis=0)).max()), + } + return float(aps.mean()), diagnostics + + +def graded_reward(metric, valid=True): + """rational_squash, monotone in the metric, no cutoff, bounded in [0, 1).""" + if not valid or metric is None or not np.isfinite(metric): + return 0.0 + x_ref = BASELINE_SCORE - M0 + assert x_ref > 0, "malformed task: the reference result does not beat the trivial baseline" + u = max(0.0, float(metric) - M0) / x_ref + return u / (1.0 + u) diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_features_0.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_features_0.npy new file mode 100644 index 0000000000000000000000000000000000000000..99e2dbd86eff4faea2a070f4d0a6a100b1387723 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_features_0.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5da2e78f5366d2f3a06ce6a37962815c4a41261906fe52a9fc8e842bd6877c8 +size 17068160 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_features_1.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_features_1.npy new file mode 100644 index 0000000000000000000000000000000000000000..496c99f99bd542a40228f6df11dc9641d31c67d2 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_features_1.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da8f6cf1f8394e11c79ad4866f31f1adcb8c55600e8691d481a86efd7d400790 +size 17066112 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_features_2.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_features_2.npy new file mode 100644 index 0000000000000000000000000000000000000000..74ea9adcf4452fceeb7886dde1e5d875a9f96923 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_features_2.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7158b0587d149353358cba53a7607664403aa5869625f0962be85326d9edb2dd +size 17066112 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_labels.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..8e6897423fa11c14d21574fa05604c173a2c7917 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/database/db_labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4113e8657b1ba539c5adcb2b6be0b934c0f45782ad7c513fd9787014b0fc11c2 +size 2000128 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/final/query_features.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/final/query_features.npy new file mode 100644 index 0000000000000000000000000000000000000000..7516c8b48fb91665e4fda6abd027ff2d0ddd8220 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/final/query_features.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72b9f80d73de43e5fad04ee1b57222c8f9b1867a28fa7fe993250fa789925c3b +size 5120128 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/final/query_labels.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/final/query_labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..cc70f7361c1d4dc3cb3fb20f40526927f7676049 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/final/query_labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9d7dd9fcbd1c966b36fc3e7fe0b6037aedbeb33f1b7a31b0979dcab0ba6a0de +size 200128 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/intermediate/query_features.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/intermediate/query_features.npy new file mode 100644 index 0000000000000000000000000000000000000000..f304e845e465a9fe0fad18c7ed38cb50e860c691 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/intermediate/query_features.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98416c2494de1260d8cbcc1a0af072cf727aa665c9a2b2e75e38380552427050 +size 5120128 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/intermediate/query_labels.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/intermediate/query_labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..df6f5151275599cdff20985437a5ca6b46fc05ee --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/intermediate/query_labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:418f6c9ee8f7d16b5848b2732a05565e73ba3175b45705a278013518910204d8 +size 200128 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/train/train_features.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/train/train_features.npy new file mode 100644 index 0000000000000000000000000000000000000000..ec3e26370fa76b6db46d8022485cbfd226612421 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/train/train_features.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b997648f05974ecd4fd88f0c02afb4111e07abfb1ba9aed0b8747bae76021d5 +size 20480128 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/train/train_labels.npy b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/train/train_labels.npy new file mode 100644 index 0000000000000000000000000000000000000000..be7b018ba8d83513d109ee3afb55e74ab8417ef8 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/hidden_data/train/train_labels.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1aff7cbac144013e5242ea5d54f091c0b059e25eacc5ad216ceba8012d40f4df +size 800128 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/intermediate.sh b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..82f155885b445e06846a4a5761a2fed8527a77c7 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -u + +PY=/usr/local/bin/python3 + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +reward_floor() { [ -s /logs/verifier/reward.txt ] || echo 0 > /logs/verifier/reward.txt; } +trap reward_floor EXIT + +chmod -R go-rwx /tests + +cd /tests +export GRADE_SPLIT=intermediate +"$PY" -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +"$PY" /tests/compute_reward.py > /logs/verifier/intermediate_reward.log 2>&1 + +exit 0 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/requirements-verifier.txt b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..04676c89520bf969f2cb861ad1811f46d8370700 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/requirements-verifier.txt @@ -0,0 +1,2 @@ +pytest==8.3.5 +pytest-json-ctrf==0.3.5 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/requirements.txt b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..6294a416fc0edbf7b80b6b9b9cb7cbf73a395448 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,16 @@ +--extra-index-url https://download.pytorch.org/whl/cpu +numpy==2.5.2 +scipy==1.18.0 +scikit-learn==1.9.0 +torch==2.13.0+cpu +filelock==3.32.2 +fsspec==2026.4.0 +jinja2==3.1.6 +joblib==1.5.3 +markupsafe==3.0.3 +mpmath==1.3.0 +networkx==3.6.1 +setuptools==78.1.0 +sympy==1.14.0 +threadpoolctl==3.6.0 +typing-extensions==4.15.0 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/runner.py b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..50ce89f194c6e3af402e8dcca379c746554b81ad --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/runner.py @@ -0,0 +1,47 @@ +import importlib +import json +import os +import sys +import time +import traceback +from pathlib import Path + +import numpy as np +import torch + +SANDBOX = Path(__file__).resolve().parent +TRAIN_SEED = 0 +EVAL_NAMES = ("a", "b", "c") + + +def main(): + status = {"ok": False, "error": None, "seconds": {}} + try: + torch.set_num_threads(int(os.environ["OMP_NUM_THREADS"])) + sys.path.append(str(SANDBOX / "code")) + model = importlib.import_module("hash_model") + + train_features = np.load(SANDBOX / "inputs" / "train_features.npy") + train_labels = np.load(SANDBOX / "inputs" / "train_labels.npy") + + t0 = time.monotonic() + state = model.train(train_features, train_labels, TRAIN_SEED) + status["seconds"]["train"] = time.monotonic() - t0 + + for name in EVAL_NAMES: + features = np.load(SANDBOX / "inputs" / f"eval_{name}.npy") + t0 = time.monotonic() + codes = model.encode(state, features) + status["seconds"][f"encode_{name}"] = time.monotonic() - t0 + np.save(SANDBOX / "out" / f"codes_{name}.npy", np.asarray(codes)) + + status["ok"] = True + except BaseException as exc: + status["error"] = f"{type(exc).__name__}: {exc}"[:600] + traceback.print_exc() + finally: + (SANDBOX / "out" / "status.json").write_text(json.dumps(status)) + + +if __name__ == "__main__": + main() diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/test.sh b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..dfa4dcef3b7194a79dfee3b923accd9d1441ea84 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/test.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -u + +PY=/usr/local/bin/python3 + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +reward_floor() { [ -s /logs/verifier/reward.txt ] || echo 0 > /logs/verifier/reward.txt; } +trap reward_floor EXIT + +chmod -R go-rwx /tests + +cd /tests +export GRADE_SPLIT=final +"$PY" -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +"$PY" /tests/compute_reward.py + +exit 0 diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/test_state.py b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..001787698a28119b15c224b360515b189312b61a --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/are-grader-ctx/test_state.py @@ -0,0 +1,284 @@ +import json +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import grader_core +from grader_core import InvalidSubmission, graded_reward, map_at_k, validate_codes + +TESTS = Path(__file__).resolve().parent +HIDDEN = TESTS / "hidden_data" +DELIVERABLE = Path("/app/output") +ENTRY_NAME = "hash_model.py" +METRIC_PATH = Path("/logs/verifier/metric.json") + +RUN_BUDGET_SEC = 1200 +DELIVERABLE_MAX_BYTES = 1024**3 +N_DB_SHARDS = 3 +PERMUTATION_SEED = 4242 +AGENT_UID = AGENT_GID = 1001 +PY = "/usr/local/bin/python3" +GRADE_SPLIT = os.environ.get("GRADE_SPLIT", "final") + +_RESULT = {} + + +def _sealed_split(): + query_features = np.load(HIDDEN / GRADE_SPLIT / "query_features.npy") + query_labels = np.load(HIDDEN / GRADE_SPLIT / "query_labels.npy") + db_features = np.concatenate( + [np.load(HIDDEN / "database" / f"db_features_{k}.npy") for k in range(N_DB_SHARDS)], + axis=0, + ) + db_labels = np.load(HIDDEN / "database" / "db_labels.npy") + train_features = np.load(HIDDEN / "train" / "train_features.npy") + train_labels = np.load(HIDDEN / "train" / "train_labels.npy") + return query_features, query_labels, db_features, db_labels, train_features, train_labels + + +def _copy_deliverable(source, target): + """Copy regular files only. Symlinks are dropped rather than followed, so a link aimed + at the verifier tree can never be dereferenced by this root process.""" + if not source.is_dir(): + raise InvalidSubmission(f"{source} does not exist") + target.mkdir(parents=True) + total = 0 + for path in sorted(source.rglob("*")): + relative = path.relative_to(source) + if path.is_symlink(): + continue + if path.is_dir(): + (target / relative).mkdir(parents=True, exist_ok=True) + elif path.is_file(): + total += path.stat().st_size + if total > DELIVERABLE_MAX_BYTES: + raise InvalidSubmission("deliverable exceeds 1 GiB") + shutil.copyfile(path, target / relative) + entry = target / ENTRY_NAME + if not entry.is_file(): + raise InvalidSubmission(f"no {ENTRY_NAME} in {source}") + if entry.stat().st_size == 0: + raise InvalidSubmission(f"{ENTRY_NAME} is empty") + return total + + +def _own(path, uid, mode_dir, mode_file): + for current, _dirs, files in os.walk(path): + os.chown(current, uid, uid) + os.chmod(current, mode_dir) + for name in files: + os.chown(os.path.join(current, name), uid, uid) + os.chmod(os.path.join(current, name), mode_file) + + +def _build_sandbox(inputs): + sandbox = Path(tempfile.mkdtemp(prefix="grade_", dir="/tmp")) + os.chmod(sandbox, 0o711) + size = _copy_deliverable(DELIVERABLE, sandbox / "code") + (sandbox / "inputs").mkdir() + (sandbox / "out").mkdir() + for name, array in inputs.items(): + np.save(sandbox / "inputs" / f"{name}.npy", array) + os.chmod(sandbox / "inputs", 0o755) + for path in (sandbox / "inputs").iterdir(): + os.chmod(path, 0o444) + shutil.copyfile(TESTS / "runner.py", sandbox / "runner.py") + os.chmod(sandbox / "runner.py", 0o444) + _own(sandbox / "code", AGENT_UID, 0o700, 0o600) + _own(sandbox / "out", AGENT_UID, 0o700, 0o600) + return sandbox, size + + +def _reap_agent_processes(): + """Kill anything still running as the agent uid, including a process that escaped its + group by starting its own session.""" + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + if entry.stat().st_uid == AGENT_UID: + os.kill(int(entry.name), 9) + except (ProcessLookupError, PermissionError, FileNotFoundError): + pass + + +def _execute(sandbox): + runuser = shutil.which("runuser") or "/usr/sbin/runuser" + env_bin = shutil.which("env") or "/usr/bin/env" + timeout_bin = shutil.which("timeout") or "/usr/bin/timeout" + child_env = { + "PATH": "/usr/local/bin:/usr/bin:/bin", + "HOME": str(sandbox / "code"), + "TMPDIR": str(sandbox / "out"), + "PYTHONSAFEPATH": "1", + "PYTHONHASHSEED": "0", + "PYTHONDONTWRITEBYTECODE": "1", + "OMP_NUM_THREADS": "8", + "MKL_NUM_THREADS": "8", + "OPENBLAS_NUM_THREADS": "8", + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + } + command = [ + runuser, "-u", "agent", "--", + env_bin, "-i", *[f"{k}={v}" for k, v in child_env.items()], + timeout_bin, "-s", "KILL", str(RUN_BUDGET_SEC), + PY, str(sandbox / "runner.py"), + ] + process = subprocess.Popen( + command, + cwd=str(sandbox / "out"), + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=True, + text=True, + errors="replace", + ) + timed_out = False + try: + stdout, stderr = process.communicate(timeout=RUN_BUDGET_SEC + 120) + except subprocess.TimeoutExpired: + timed_out = True + try: + os.killpg(os.getpgid(process.pid), 9) + except (ProcessLookupError, PermissionError): + pass + try: + stdout, stderr = process.communicate(timeout=60) + except subprocess.TimeoutExpired: + stdout, stderr = "", "" + finally: + _reap_agent_processes() + return process.returncode, timed_out, stdout or "", stderr or "" + + +def _load_codes(path, n_rows, what): + if not path.is_file(): + raise InvalidSubmission(f"{what}: no codes written") + try: + array = np.load(path, allow_pickle=False) + except Exception as exc: + raise InvalidSubmission(f"{what}: unreadable array ({type(exc).__name__})") from exc + return validate_codes(array, n_rows, what) + + +def graded_run(): + if _RESULT: + return _RESULT + + record = { + "half": GRADE_SPLIT, + "metric_name": "mAP@5000", + "metric": None, + "reward": 0.0, + "valid": False, + "error": None, + "executed": False, + "timed_out": False, + "returncode": None, + "contract_ok": False, + "permutation_equivariant": False, + "deliverable_bytes": None, + "run_seconds": None, + "diagnostics": None, + } + sandbox = None + try: + query, query_labels, db, db_labels, train, train_labels = _sealed_split() + permutation = np.random.default_rng(PERMUTATION_SEED).permutation(len(query)) + sandbox, record["deliverable_bytes"] = _build_sandbox( + { + "train_features": train, + "train_labels": train_labels, + "eval_a": query, + "eval_b": db, + "eval_c": query[permutation], + } + ) + code, timed_out, stdout, stderr = _execute(sandbox) + record["returncode"], record["timed_out"] = code, timed_out + if stderr.strip(): + print("--- deliverable stderr (tail) ---") + print(stderr.strip()[-2000:]) + if timed_out or code == 137: + raise InvalidSubmission(f"run exceeded the {RUN_BUDGET_SEC}s budget") + + status_path = sandbox / "out" / "status.json" + if not status_path.is_file(): + raise InvalidSubmission(f"run produced no status (exit {code})") + status = json.loads(status_path.read_text()) + record["executed"] = True + record["run_seconds"] = status.get("seconds") + if not status.get("ok"): + raise InvalidSubmission(status.get("error") or f"run failed (exit {code})") + + codes_query = _load_codes(sandbox / "out" / "codes_a.npy", len(query), "query codes") + codes_db = _load_codes(sandbox / "out" / "codes_b.npy", len(db), "database codes") + codes_perm = _load_codes( + sandbox / "out" / "codes_c.npy", len(query), "permuted query codes" + ) + record["contract_ok"] = True + if not np.array_equal(codes_perm, codes_query[permutation]): + raise InvalidSubmission("encode is not permutation-equivariant") + record["permutation_equivariant"] = True + + metric, diagnostics = map_at_k(codes_query, codes_db, query_labels, db_labels) + record.update( + metric=float(metric), + diagnostics=diagnostics, + valid=True, + reward=float(graded_reward(metric, valid=True)), + ) + except InvalidSubmission as exc: + record["error"] = f"invalid submission: {exc}" + except Exception as exc: + record["error"] = f"grader error: {type(exc).__name__}: {exc}" + finally: + if sandbox is not None: + shutil.rmtree(sandbox, ignore_errors=True) + + METRIC_PATH.parent.mkdir(parents=True, exist_ok=True) + METRIC_PATH.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n") + print(f"half={record['half']} metric[mAP@5000]={record['metric']} valid={record['valid']}") + if record["diagnostics"]: + print("diagnostics=" + json.dumps(record["diagnostics"], sort_keys=True)) + if record["error"]: + print("error=" + record["error"]) + _RESULT.update(record) + return _RESULT + + +def test_entry_point_executes(): + """/app/output/hash_model.py exists, imports, and completes train + encode inside the + disclosed wall-clock budget.""" + result = graded_run() + assert result["executed"], result["error"] + assert not result["timed_out"], result["error"] + + +def test_code_contract(): + """Every encode call returns an (M, 16) int8 array whose values are all -1 or +1.""" + result = graded_run() + assert result["contract_ok"], result["error"] + + +def test_permutation_equivariance(): + """Codes are a function of the rows, not of their order: encode(X[P]) == encode(X)[P].""" + result = graded_run() + assert result["permutation_equivariant"], result["error"] + + +def test_metric_recorded(): + """The scorer derived mAP@5000 from sealed labels and recorded a reward in [0, 1].""" + result = graded_run() + assert METRIC_PATH.is_file() + assert 0.0 <= result["reward"] <= 1.0 + assert result["valid"], result["error"] diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/environment/docker-compose.yaml b/tasks/mlh-coco-16bit-hash-head-map5000/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9883cfae52b5004d6fd749b42b16a3c9b9299121 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/environment/docker-compose.yaml @@ -0,0 +1,76 @@ +# ARE 1.1: grading lives in sidecars. Harbor configures `main` (build, limits, network). +services: + main: + depends_on: + grader: + condition: service_healthy + volumes: + - are-deliverable-0:/app/output + + grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: val + platform: linux/amd64 + environment: + ARE_ROLE: val + ARE_PORT: "8000" + ARE_BUDGET_SEC: "86400" + ARE_ARTIFACT_PATHS: "/app/output" + ARE_AGENT_UID: "1001" + ARE_GRADE_TIMEOUT_SEC: "1800" + volumes: + - are-deliverable-0:/run/are-deliverable/app/output + - are-secret:/run/are-secret + expose: + - "8000" + cap_add: [SYS_ADMIN] + networks: [default, are-private] + cpus: 8 + mem_limit: 14336m + depends_on: + test-grader: + condition: service_healthy + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + + test-grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: test + platform: linux/amd64 + environment: + ARE_ROLE: test + ARE_PORT: "8001" + ARE_ARTIFACT_PATHS: "/app/output" + ARE_GRADE_TIMEOUT_SEC: "1800" + expose: + - "8001" + volumes: + - are-secret:/run/are-secret + cap_add: [SYS_ADMIN] + networks: [are-private] + cpus: 8 + mem_limit: 14336m + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8001/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + +volumes: + are-deliverable-0: {} + are-secret: {} + +networks: + are-private: + internal: true diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/task.toml b/tasks/mlh-coco-16bit-hash-head-map5000/task.toml index 904845d5b00e37171274e87bb5c476bf1b8b58ba..358e0a9936ff40c2271cd2b2ace0e5b8ab3f360d 100644 --- a/tasks/mlh-coco-16bit-hash-head-map5000/task.toml +++ b/tasks/mlh-coco-16bit-hash-head-map5000/task.toml @@ -1,57 +1,71 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/mlh-coco-16bit-hash-head-map5000" -version = "1.0.0" +version = "1.1.0" description = "" -keywords = [ "autoresearch", "machine-learning", "benchmark",] -[[task.authors]] -name = "Bespoke Labs" +keywords = [ + "autoresearch", + "machine-learning", + "benchmark", +] +authors = [ + { name = "Bespoke Labs" }, +] [metadata] category = "Machine Learning and AI" subcategory = "Unsupervised and representation learning" -task_objective = [ "Implement", "Optimize",] -artifact_type = [ "Single script or program",] +task_objective = [ + "Implement", + "Optimize", +] +artifact_type = [ + "Single script or program", +] expert_time_estimate_hours = 4.0 +are_version = "1.1" +budget_seconds = 86400 [verifier] -timeout_sec = 1800.0 +timeout_sec = 600.0 environment_mode = "separate" -collect = [] -[verifier.env] +[[verifier.collect]] +service = "grader" +command = "/opt/are/venv/bin/python /opt/are/drain.py" +timeout_sec = 3600.0 [verifier.environment] network_mode = "no-network" -build_timeout_sec = 3600.0 -os = "linux" -cpus = 8 -memory_mb = 14336 -storage_mb = 153600 +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 gpus = 0 -mcp_servers = [] - -[verifier.environment.env] [agent] network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] -timeout_sec = 14400.0 +allowed_hosts = [ + "api.openai.com", + "api.anthropic.com", + "grader", +] +timeout_sec = 86400.0 user = "agent" [environment] -network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] +network_mode = "public" build_timeout_sec = 3600.0 os = "linux" cpus = 8 memory_mb = 14336 storage_mb = 153600 gpus = 0 -mcp_servers = [] +mcp_servers = [ + { name = "are", transport = "streamable-http", url = "http://grader:8000/mcp" }, +] [environment.env] - -[solution.env] diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/tests/Dockerfile b/tasks/mlh-coco-16bit-hash-head-map5000/tests/Dockerfile index ac2db52aaf1ac1bab5fe08079ef04b14b8c08741..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/mlh-coco-16bit-hash-head-map5000/tests/Dockerfile +++ b/tasks/mlh-coco-16bit-hash-head-map5000/tests/Dockerfile @@ -1,33 +1,2 @@ -FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb - -ENTRYPOINT [] -ENV PYTHONPATH= -ENV PYTHONSAFEPATH=1 -ENV DEBIAN_FRONTEND=noninteractive \ - PYTHONHASHSEED=0 \ - PIP_NO_CACHE_DIR=1 \ - PIP_DISABLE_PIP_VERSION_CHECK=1 \ - OMP_NUM_THREADS=8 \ - MKL_NUM_THREADS=8 \ - OPENBLAS_NUM_THREADS=8 \ - HF_HUB_OFFLINE=1 \ - TRANSFORMERS_OFFLINE=1 - -RUN useradd --create-home --uid 1001 agent - -COPY ./requirements.txt /tmp/requirements.txt -COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt -RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ - -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ - && rm /tmp/requirements.txt /tmp/requirements-verifier.txt - -RUN mkdir -p /app/output /logs/verifier - -COPY . /tests - -RUN chown -R root:root /tests \ - && chmod -R 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ - && chmod +x /tests/test.sh /tests/intermediate.sh \ - && find /tests -exec touch -d @1700000000 {} + - -WORKDIR /tests +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/tests/finalize.py b/tasks/mlh-coco-16bit-hash-head-map5000/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/mlh-coco-16bit-hash-head-map5000/tests/finalize.py @@ -0,0 +1,59 @@ +"""Final verifier: score the run from the grader ledger. + +reward hidden test score of the submission with the best validation score + (ties go to the earlier submission); 0 if nothing was submitted. +auarc area under the curve of that same quantity over the wall-clock budget, + using the time each validation score became available, divided by the + budget. 0 before the first graded submission. +""" + +import json +from pathlib import Path + +STATE = Path("/var/lib/are") +OUT = Path("/logs/verifier") +OUT.mkdir(parents=True, exist_ok=True) + +meta = json.loads((STATE / "meta.json").read_text()) if (STATE / "meta.json").exists() else {} +budget = float(meta.get("budget_seconds") or 1.0) + +subs: dict[int, dict] = {} +ledger = STATE / "ledger.jsonl" +for line in (ledger.read_text().splitlines() if ledger.exists() else []): + ev = json.loads(line) + s = subs.setdefault(ev["id"], {"id": ev["id"]}) + if ev["event"] == "submitted": + s["submitted_t"] = ev["t"] + elif ev["event"] == "val": + s["val"] = ev["score"] + s["val_t"] = ev["t"] + elif ev["event"] == "test": + s["test"] = ev["score"] + +graded = sorted((s for s in subs.values() if "val" in s), key=lambda s: s["val_t"]) + +# Step function of the hidden score of the best-validation pick over time. +auc, best, last_t, cur = 0.0, None, 0.0, 0.0 +timeline = [] +for s in graded: + t = min(s["val_t"], budget) + auc += cur * (t - last_t) + last_t = t + if best is None or s["val"] > best["val"] or (s["val"] == best["val"] and s["id"] < best["id"]): + best = s + cur = float(best.get("test") or 0.0) + timeline.append({"t": s["val_t"], "id": s["id"], "val": s["val"], "test": s.get("test"), + "pick": best["id"]}) +auc += cur * (budget - last_t) if last_t < budget else 0.0 + +reward = { + "reward": float(best.get("test") or 0.0) if best else 0.0, + "auarc": auc / budget, + "best_val": float(best["val"]) if best else 0.0, + "n_submissions": float(len(subs)), + "n_test_graded": float(sum(s.get("test") is not None for s in subs.values())), +} +(OUT / "reward.json").write_text(json.dumps(reward)) +(OUT / "timeline.json").write_text(json.dumps({"budget": budget, "selected": best and best["id"], + "submissions": timeline}, indent=1)) +print(json.dumps(reward, indent=1)) diff --git a/tasks/mlh-coco-16bit-hash-head-map5000/tests/test.sh b/tasks/mlh-coco-16bit-hash-head-map5000/tests/test.sh index dfa4dcef3b7194a79dfee3b923accd9d1441ea84..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/mlh-coco-16bit-hash-head-map5000/tests/test.sh +++ b/tasks/mlh-coco-16bit-hash-head-map5000/tests/test.sh @@ -1,21 +1,2 @@ #!/bin/bash -set -u - -PY=/usr/local/bin/python3 - -mkdir -p /logs/verifier -chown root:root /logs/verifier 2>/dev/null || true -chmod 755 /logs/verifier 2>/dev/null || true -rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json - -reward_floor() { [ -s /logs/verifier/reward.txt ] || echo 0 > /logs/verifier/reward.txt; } -trap reward_floor EXIT - -chmod -R go-rwx /tests - -cd /tests -export GRADE_SPLIT=final -"$PY" -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA -"$PY" /tests/compute_reward.py - -exit 0 +python3 /tests/finalize.py diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/.dockerignore b/tasks/reppo-reliable-onpolicy-control-trainer/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/Dockerfile b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eecf368ab2e270d72769fce908d380caafac46d0 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,34 @@ +FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONHASHSEED=0 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements.txt /tmp/requirements.txt +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ + -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements.txt /tmp/requirements-verifier.txt + +RUN mkdir -p /app/solution /logs/verifier + +COPY . /tests + +RUN chown -R root:root /tests \ + && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/Dockerfile.are b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..af832a8f3c5a676dce9b48b2d6464eaa78799f39 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,52 @@ +FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONHASHSEED=0 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements.txt /tmp/requirements.txt +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ + -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements.txt /tmp/requirements-verifier.txt + +RUN mkdir -p /app/solution /logs/verifier + +COPY . /tests + +RUN chown -R root:root /tests \ + && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 + + +# ---- ARE 1.1 grader layer (appended to the task's own verifier Dockerfile) ---- +ARG ARE_ROLE +# python.org images ship /usr/local/bin/python3; distro-python bases (kaggle GPU) lack +# ensurepip, so fall back to a pip-less venv filled by the base interpreter's pip. +RUN PY=$(command -v /usr/local/bin/python3 || command -v python3) \ + && if "$PY" -m venv /opt/are/venv; then \ + /opt/are/venv/bin/pip install --no-cache-dir "fastmcp==2.14.7"; \ + else rm -rf /opt/are/venv && "$PY" -m venv --without-pip /opt/are/venv \ + && "$PY" -m pip --python /opt/are/venv/bin/python install --no-cache-dir "fastmcp==2.14.7"; fi +COPY are/ /opt/are/ +# The val grader, whose output reaches the agent, never holds the private grader or its +# data. The test grader keeps everything; nothing from it reaches the agent. +RUN rm -rf /tests/are /tests/Dockerfile.are \ + && if [ "$ARE_ROLE" = "val" ]; then rm -rf /tests/test.sh /tests/hidden_data/final; fi +ENV ARE_ROLE=$ARE_ROLE +CMD ["/opt/are/venv/bin/python", "/opt/are/server.py"] diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/are/drain.py b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/are/drain.py @@ -0,0 +1,25 @@ +"""Verifier collect hook, run after the agent stops. + +Grades the final workspace as one last submission (unless it equals the last one), +then waits until every submission has both grades recorded. +""" + +import json +import time +import urllib.request +from pathlib import Path + +TOKEN = Path("/run/are-secret/token").read_text().strip() +H = {"x-are-token": TOKEN} + +req = urllib.request.Request("http://localhost:8000/final", method="POST", headers=H) +with urllib.request.urlopen(req, timeout=120) as resp: + print("final:", json.loads(resp.read()), flush=True) + +while True: + with urllib.request.urlopen(urllib.request.Request("http://localhost:8000/drain", headers=H), timeout=30) as resp: + state = json.loads(resp.read()) + print(state, flush=True) + if state["val_pending"] == 0 and state["test_pending"] == 0: + break + time.sleep(5) diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/are/server.py b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/are/server.py @@ -0,0 +1,538 @@ +"""ARE 1.1 grader sidecar. + +One image, two roles: + +- ARE_ROLE=val ("grader" service). Reachable from the agent. Serves MCP tools and a + REST fallback. On submit it snapshots the shared deliverable volume, grades the + snapshot with the task's public grader (intermediate.sh), and returns only that + score. Every snapshot is also sent to the test grader; the hidden score goes to a + root-only ledger and never back to the agent. +- ARE_ROLE=test ("test-grader" service). On a private network that only the val + grader can reach. Grades snapshots with the task's private grader (test.sh). +""" + +from __future__ import annotations + +import asyncio +import gzip +import hashlib +import io +import secrets +import json +import os +import queue +import shutil +import subprocess +import tarfile +import threading +import time +import urllib.request +from pathlib import Path + +from fastmcp import FastMCP +from starlette.requests import Request +from starlette.responses import JSONResponse, Response + +ROLE = os.environ.get("ARE_ROLE", "val") +PORT = int(os.environ.get("ARE_PORT", "8000")) +STATE = Path(os.environ.get("ARE_STATE_DIR", "/var/lib/are")) +ARTIFACT_PATHS = [p for p in os.environ.get("ARE_ARTIFACT_PATHS", "/app/output").split(":") if p] +# The shared deliverable volume. Its parent is root-only, so submitted code (which every +# task grader runs as the unprivileged agent user) cannot reach it to write back to the agent. +SUBMISSION_ROOT = Path(os.environ.get("ARE_SUBMISSION_ROOT", "/run/are-deliverable")) +AGENT_UID = int(os.environ.get("ARE_AGENT_UID", "1001")) +BUDGET_SEC = float(os.environ.get("ARE_BUDGET_SEC", "14400")) +GRADE_TIMEOUT_SEC = float(os.environ.get("ARE_GRADE_TIMEOUT_SEC", "1800")) +TEST_GRADER_URL = os.environ.get("ARE_TEST_GRADER_URL", "http://test-grader:8001") +FEEDBACK_TAIL = int(os.environ.get("ARE_FEEDBACK_TAIL_CHARS", "8192")) +SCRIPT = "/tests/intermediate.sh" if ROLE == "val" else "/tests/test.sh" +# Shared only by the two graders (a volume the agent's container never mounts). The test +# grader writes a fresh token at startup; every internal request must carry it, so the +# agent cannot reach the test grader or the internal endpoints even on a shared network. +TOKEN_FILE = Path(os.environ.get("ARE_TOKEN_FILE", "/run/are-secret/token")) +TOKEN = "" + + +def _authorized(request: Request) -> bool: + """Internal endpoints need the graders' token; an unset token never matches.""" + return bool(TOKEN) and secrets.compare_digest(request.headers.get("x-are-token", ""), TOKEN) + + +def _net_isolation_available() -> bool: + try: + return subprocess.run(["unshare", "-n", "true"], capture_output=True, timeout=10).returncode == 0 + except Exception: + return False + + +NET_ISOLATED = False # set at startup: grader scripts run in an empty network namespace + +T0 = time.time() +_lock = threading.Lock() + + +def _elapsed() -> float: + return round(time.time() - T0, 1) + + +def _ledger(event: dict) -> None: + event = {"t": _elapsed(), "wall": time.time(), **event} + for attempt in range(3): + try: + with _lock, open(STATE / "ledger.jsonl", "a") as fh: + fh.write(json.dumps(event) + "\n") + return + except OSError: + if attempt == 2: + raise + time.sleep(1) + + +def _kill_grading_processes(proc: subprocess.Popen) -> None: + """Kill everything a timed-out grade started, including processes that left its group.""" + try: + os.killpg(proc.pid, 9) + except ProcessLookupError: + pass + _kill_other_processes() + + +def _kill_other_processes() -> None: + """Kill every process run by the agent user. Every task grader runs submitted code as + that user, so this stops all graded code (detached or not) and nothing else: the grader + server, the task's own grader and Harbor's hooks run as root.""" + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + if entry.stat().st_uid == AGENT_UID: + os.kill(int(entry.name), 9) + except (ProcessLookupError, PermissionError, FileNotFoundError): + pass + + +# Places the agent user (who runs submitted code inside every task grader) can write. +_BASELINE: set[str] = set() # every path that existed when the grader started (its image) + + +def _walk_one_fs(base: Path): + """Every path under base on base's own filesystem (skips /proc, /sys and other mounts).""" + dev = base.stat().st_dev + for root, dirs, files in os.walk(base): + dirs[:] = [d for d in dirs if os.lstat(os.path.join(root, d)).st_dev == dev] + for name in dirs + files: + yield Path(root) / name + + +def _all_paths() -> set[str]: + out = set() + for base in (Path("/"), Path("/dev/shm")): + if base.is_dir(): + out.update(str(q) for q in _walk_one_fs(base)) + return out + + +def _protected(path: str) -> bool: + keep = [str(STATE), "/opt/are", str(TOKEN_FILE.parent)] + return any(path == k or path.startswith(k + "/") for k in keep) + + +def _fresh_state() -> None: + """Start every grade from the grader image's own files, as ARE 1.0's fresh verifier + container did. The grader container lives for the whole run, so before each grade + stop anything an earlier grade left running and delete every file it created, + whoever wrote it. The deliverable volume and the token are separate mounts and are + never walked; the grader's own state is kept.""" + _kill_other_processes() + # System V shared memory, semaphores and queues outlive processes; this server uses none. + subprocess.run(["ipcrm", "--all"], capture_output=True) + for path in sorted(_all_paths() - _BASELINE, key=lambda q: q.count("/"), reverse=True): + if _protected(path): + continue + try: + q = Path(path) + if q.is_dir() and not q.is_symlink(): + shutil.rmtree(q, ignore_errors=True) + else: + q.unlink() + except OSError: + pass + + +def grade_snapshot(tar_bytes: bytes, tag: str) -> dict: + """Extract a snapshot over the artifact paths and run this role's grader script.""" + _fresh_state() + for path in ARTIFACT_PATHS: + p = Path(path) + if p.exists(): + shutil.rmtree(p) + p.mkdir(parents=True) + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:gz") as tf: + tf.extractall("/", filter="tar") + logs = Path("/logs/verifier") + if logs.exists(): + shutil.rmtree(logs) + logs.mkdir(parents=True) + started = time.time() + # Submitted code runs with no network, as in ARE 1.0's verifier. + cmd = (["unshare", "-n"] if NET_ISOLATED else []) + ["bash", SCRIPT] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + cwd="/tests", start_new_session=True) + try: + out, err = proc.communicate(timeout=GRADE_TIMEOUT_SEC) + error = None + except subprocess.TimeoutExpired: + _kill_grading_processes(proc) + out, err = proc.communicate() + error = f"grader timed out after {GRADE_TIMEOUT_SEC:.0f}s" + output = (out or "") + (err or "") + # Nothing a grade started may keep running after it, not even detached processes. + _kill_other_processes() + score = 0.0 + reward_file = logs / "reward.txt" + if reward_file.exists(): + try: + score = float(reward_file.read_text().strip() or 0) + except ValueError: + error = error or "unparseable reward" + metric = None + if (logs / "metric.json").exists(): + try: + metric = json.loads((logs / "metric.json").read_text()) + except ValueError: + pass + (STATE / "logs").mkdir(exist_ok=True) + (STATE / "logs" / f"{tag}.log").write_text(output) + return { + "score": score, + "metric": metric, + "error": error, + "net_isolated": NET_ISOLATED, + "seconds": round(time.time() - started, 1), + # What the agent sees, as in ARE 1.0: the grader's stdout tail (not stderr). + "output_tail": (out or "")[-FEEDBACK_TAIL:], + } + + +mcp = FastMCP("are") + + +# ---------------------------------------------------------------- test role + + +_grade_lock = threading.Lock() + + +def _grade_one_at_a_time(tar_bytes: bytes, tag: str) -> dict: + # A request that timed out on the caller's side may still be grading; the next one + # waits for it rather than sharing /app/output and /logs/verifier with it. + with _grade_lock: + return grade_snapshot(tar_bytes, tag) + + +if ROLE == "test": + + @mcp.custom_route("/grade", methods=["POST"]) + async def http_grade(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + tag = request.query_params.get("tag", "x") + body = await request.body() + result = await asyncio.to_thread(_grade_one_at_a_time, body, f"{tag}-test") + return JSONResponse(result) + + +# ----------------------------------------------------------------- val role + + +class Board: + """Submissions and their grading state. Hidden scores are never stored here.""" + + def __init__(self) -> None: + self.subs: dict[int, dict] = {} + self.val_q: queue.Queue[int] = queue.Queue() + self.next_id = 1 + self.test_pending = 0 + self.last_digest: str | None = None + + def public(self, sid: int) -> dict: + s = self.subs[sid] + out = {k: s[k] for k in ("id", "note", "submitted_at_s", "status")} + if s["status"] == "graded": + v = s["val"] + out.update( + validation_score=v["score"], + error=v["error"], + grading_seconds=v["seconds"], + grader_output_tail=v["output_tail"], + ) + return out + + def best(self) -> dict | None: + graded = [s for s in self.subs.values() if s["status"] == "graded"] + if not graded: + return None + b = max(graded, key=lambda s: (s["val"]["score"], -s["id"])) + return {"id": b["id"], "validation_score": b["val"]["score"]} + + +board = Board() + + +def snapshot() -> bytes: + """Deterministic tar.gz of the deliverable: same content, same bytes (gzip mtime 0).""" + raw = io.BytesIO() + with tarfile.open(fileobj=raw, mode="w") as tf: + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + tf.add(str(src), arcname=path.lstrip("/")) + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as gz: + gz.write(raw.getvalue()) + return out.getvalue() + + +def do_submit(note: str, final: bool = False) -> dict: + with _lock: + pending = [s["id"] for s in board.subs.values() if s["status"] != "graded"] + if pending and not final: + return { + "error": f"Submission {pending[0]} is still being graded. One submission is " + f"graded at a time: check result({pending[0]}) and submit again " + "once it has its score.", + "pending_id": pending[0], + } + sid = board.next_id + board.next_id += 1 + board.subs[sid] = {"id": sid, "note": note[:500], "submitted_at_s": _elapsed(), + "status": "queued"} + try: + data = snapshot() + digest = hashlib.sha256(data).hexdigest() + (STATE / "snapshots" / f"{sid:04d}.tar.gz").write_bytes(data) + _ledger({"event": "submitted", "id": sid, "note": note[:500], "bytes": len(data), + "sha256": digest, "final": final}) + except Exception as exc: + with _lock: + board.subs.pop(sid, None) # release the slot; the id is not reused + return {"error": f"Could not snapshot the deliverable ({exc}). Nothing was submitted. " + "Make sure nothing is writing to it, then submit again."} + board.last_digest = digest + with _lock: + board.test_pending += 1 + board.val_q.put(sid) + return {"id": sid, "status": "queued", + "hint": "Grading has started. Check result(id) for the validation score."} + + +def final_submit() -> dict: + """After the agent stops: grade the final workspace unless it was already submitted.""" + try: + data = snapshot() + except Exception as exc: + return {"error": f"final snapshot failed: {exc}"} + if board.subs and hashlib.sha256(data).hexdigest() == board.last_digest: + return {"skipped": "final workspace equals the last submission"} + return do_submit("final workspace (automatic)", final=True) + + +def grade_worker() -> None: + """Grade each submission on val, then on test, one submission at a time. + + The val score is published as soon as it is ready. The next submission's val grade + waits until this test grade is done, so the two graders never run at the same time. + """ + while True: + sid = board.val_q.get() + board.subs[sid]["status"] = "grading" + data = b"" + try: + data = (STATE / "snapshots" / f"{sid:04d}.tar.gz").read_bytes() + res = grade_snapshot(data, f"{sid:04d}-val") + except Exception as exc: + res = {"score": 0.0, "metric": None, "error": f"grader failed: {exc}", + "net_isolated": NET_ISOLATED, "seconds": 0.0, "output_tail": ""} + board.subs[sid]["val"] = res + board.subs[sid]["status"] = "graded" + try: + _ledger({"event": "val", "id": sid, **{k: res[k] for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + test_grade(sid, data) + + +def test_grade(sid: int, data: bytes) -> None: + try: + _test_grade(sid, data) + finally: + with _lock: + board.test_pending -= 1 + + +def _test_grade(sid: int, data: bytes) -> None: + """Send one snapshot to the test grader. A failed request is retried (the same snapshot + is graded again, so a retry can only recover the honest score); a request that ran + past its timeout is not, since the grade itself already took the full time.""" + started = time.time() + for attempt in range(3): + try: + req = urllib.request.Request( + f"{TEST_GRADER_URL}/grade?tag={sid:04d}", data=data, method="POST", + headers={"x-are-token": TOKEN}, + ) + with urllib.request.urlopen(req, timeout=2 * GRADE_TIMEOUT_SEC + 300) as resp: + res = json.loads(resp.read()) + break + except Exception as exc: # recorded, never shown to the agent + res = {"score": None, "metric": None, "error": f"test grader: {exc}", + "seconds": round(time.time() - started, 1)} + if attempt == 2 or isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError): + break + time.sleep(5) + try: + _ledger({"event": "test", "id": sid, **{k: res.get(k) for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + + +def with_time(out: dict) -> dict: + """Wall-clock accounting on every reply, as the v1 harness gave each phase.""" + out["total_budget_seconds"] = BUDGET_SEC + out["time_remaining_seconds"] = round(max(0.0, BUDGET_SEC - _elapsed()), 1) + return out + + +def status_dict() -> dict: + return { + "submissions": len(board.subs), + "queued_or_grading": sum(s["status"] != "graded" for s in board.subs.values()), + "best": board.best(), + } + + +def current_result(sid: int) -> dict: + return board.public(sid) + + +if ROLE == "val": + + @mcp.tool + async def submit(note: str = "") -> dict: + """Submit the current deliverable for grading. + + Snapshots the deliverable directory right now (later edits do not affect this + submission) and starts grading it on the public validation split. Returns at + once with a submission id. One submission is graded at a time: check `result` + and submit again once the previous submission has its score. `note` is a short + description of what changed. + """ + return with_time(await asyncio.to_thread(do_submit, note)) + + @mcp.tool + async def result(id: int) -> dict: + """The current state of a submission: queued, grading, or graded with its + validation score and grader output. Returns immediately.""" + if id not in board.subs: + return {"error": f"unknown submission id {id}"} + return with_time(current_result(id)) + + @mcp.tool + async def status() -> dict: + """Submission count, whether one is being graded, the best validation score, + and the time budget and time remaining.""" + return with_time(status_dict()) + + @mcp.custom_route("/submit", methods=["POST"]) + async def http_submit(request: Request) -> Response: + note = request.query_params.get("note", "") + return JSONResponse(with_time(await asyncio.to_thread(do_submit, note))) + + @mcp.custom_route("/result/{sid}", methods=["GET"]) + async def http_result(request: Request) -> Response: + sid = int(request.path_params["sid"]) + if sid not in board.subs: + return JSONResponse({"error": f"unknown submission id {sid}"}, status_code=404) + return JSONResponse(with_time(current_result(sid))) + + @mcp.custom_route("/status", methods=["GET"]) + async def http_status(request: Request) -> Response: + return JSONResponse(with_time(status_dict())) + + @mcp.custom_route("/final", methods=["POST"]) + async def http_final(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Collect hook, after the agent has stopped. + return JSONResponse(await asyncio.to_thread(final_submit)) + + @mcp.custom_route("/drain", methods=["GET"]) + async def http_drain(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Used by the verifier collect hook after the agent has stopped. + pending = sum(s["status"] != "graded" for s in board.subs.values()) + return JSONResponse({"val_pending": pending, "test_pending": board.test_pending}) + + +def _gpus() -> list[str]: + try: + out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=20) + return [l for l in out.stdout.splitlines() if l.strip()] + except Exception: + return [] + + +@mcp.custom_route("/health", methods=["GET"]) +async def health(request: Request) -> Response: + return JSONResponse({"ok": True, "role": ROLE, "gpus": await asyncio.to_thread(_gpus)}) + + +def _setup_token() -> None: + global TOKEN + if ROLE == "test": + TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True) + os.chmod(TOKEN_FILE.parent, 0o700) + TOKEN = secrets.token_hex(32) + TOKEN_FILE.write_text(TOKEN) + os.chmod(TOKEN_FILE, 0o600) + else: + for _ in range(300): # the test grader is healthy before this one starts + if TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip(): + break + time.sleep(1) + TOKEN = TOKEN_FILE.read_text().strip() + if not TOKEN: + raise SystemExit("ARE: empty internal token; refusing to start") + + +def main() -> None: + global NET_ISOLATED + NET_ISOLATED = _net_isolation_available() + if not NET_ISOLATED: + # Graded code must never have a network path (for example back through /submit). + raise SystemExit("ARE grader: cannot run grades without network access " + "(needs `unshare -n`, i.e. CAP_SYS_ADMIN); refusing to start") + STATE.mkdir(parents=True, exist_ok=True) + _BASELINE.update(_all_paths()) + _setup_token() + STATE.mkdir(parents=True, exist_ok=True) + os.chmod(STATE, 0o700) + (STATE / "snapshots").mkdir(exist_ok=True) + if ROLE == "val": + # The deliverable volume starts empty and root-owned; hand it to the agent user. + SUBMISSION_ROOT.mkdir(parents=True, exist_ok=True) + os.chmod(SUBMISSION_ROOT, 0o700) + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + src.mkdir(parents=True, exist_ok=True) + os.chown(src, AGENT_UID, AGENT_UID) + (STATE / "meta.json").write_text(json.dumps( + {"t0_wall": T0, "budget_seconds": BUDGET_SEC, "artifact_paths": ARTIFACT_PATHS} + )) + threading.Thread(target=grade_worker, daemon=True).start() + mcp.run(transport="http", host="0.0.0.0", port=PORT, show_banner=False, + uvicorn_config={"timeout_keep_alive": 86400}) + + +if __name__ == "__main__": + main() diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/child_main.py b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/child_main.py new file mode 100644 index 0000000000000000000000000000000000000000..d77deb47a20d2f571c5796bd6d44d404aa61c163 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/child_main.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +import importlib.util +import json +import os +import struct +import sys +from dataclasses import dataclass + +import numpy as np +import torch + + + + + +torch.set_num_threads(1) + +_HDR = struct.Struct(" None: + buf = _HDR.pack(kind, len(payload)) + payload + while buf: + buf = buf[os.write(self._w, buf) :] + + def _read_exact(self, n: int) -> bytes: + out = bytearray() + while len(out) < n: + chunk = os.read(self._r, n - len(out)) + if not chunk: + raise Shutdown("harness closed the pipe") + out += chunk + return bytes(out) + + def _recv(self) -> tuple[bytes, bytes]: + kind, length = _HDR.unpack(self._read_exact(_HDR.size)) + return kind, self._read_exact(length) + + def _answer_query(self, payload: bytes) -> None: + obs = np.frombuffer(payload, dtype=" tuple[bytes, bytes]: + self._send(kind, payload) + while True: + k, p = self._recv() + if k == b"Q": + self._answer_query(p) + elif k == b"X": + raise Shutdown("harness asked the run to stop") + else: + return k, p + + def serve_until_shutdown(self) -> None: + while True: + k, p = self._recv() + if k == b"Q": + self._answer_query(p) + elif k == b"X": + return + + +ACT_STATE = [8, 2] + + +class RemoteEnv: + """The vectorised environment handle a training procedure is given.""" + + def __init__(self, link: _Link, cfg: dict): + self._link = link + self.n_envs = int(cfg["n_envs"]) + self.obs_dim = int(cfg["obs_dim"]) + self.act_dim = int(cfg["act_dim"]) + self.max_episode_steps = int(cfg["max_episode_steps"]) + + def reset(self) -> np.ndarray: + _, payload = self._link.request(b"R") + return np.frombuffer(payload, dtype=" int: + solution_dir, rfd, wfd = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) + link = _Link(rfd, wfd) + kind, payload = link._recv() + if kind != b"I": + return 2 + cfg = json.loads(payload.decode()) + ACT_STATE[0] = int(cfg["obs_dim"]) + ACT_STATE[1] = int(cfg["act_dim"]) + + env = RemoteEnv(link, cfg) + budget = Budget( + total_env_steps=int(cfg["total_env_steps"]), + cpu_seconds=float(cfg["cpu_seconds"]), + n_checkpoints=int(cfg["n_checkpoints"]), + ) + + def report(policy_fn) -> None: + if not callable(policy_fn): + raise TypeError("report() expects a callable policy") + link._policy = policy_fn + link.request(b"P") + + train = _load_train(solution_dir) + try: + link.request(b"G") + train(env, int(cfg["seed"]), budget, report) + link.request(b"D") + link.serve_until_shutdown() + except Shutdown: + return 0 + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except Shutdown: + sys.exit(0) diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/compute_reward.py b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..711a62a5a0d08a6a0956ab171990c6d9f5dca07a --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,18 @@ +import json +import math +from pathlib import Path + +REWARD_PATH = Path("/logs/verifier/reward.txt") + +try: + value = float(json.loads(Path("/logs/verifier/metric.json").read_text())["reward"]) + if not math.isfinite(value): + raise ValueError("non-finite reward") + reward = f"{min(1.0, max(0.0, value)):.12g}" + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + REWARD_PATH.write_text(reward + "\n") + print(f"reward={reward}") +except Exception as exc: + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + REWARD_PATH.write_text("0\n") + print(f"reward=0 (fallback: {exc})") diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/envs.py b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/envs.py new file mode 100644 index 0000000000000000000000000000000000000000..5283f889988a0feded6a9e2912d005a5b887a3c5 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/envs.py @@ -0,0 +1,344 @@ +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import Any + +import numpy as np + +OBS_DIM = 8 +ACT_DIM = 2 +MAX_EPISODE_STEPS = 100 + +FAMILIES = ( + "double_integrator", + "pendulum_balance", + "pendulum_swingup", + "cartpole_swingup", + "reacher2", + "delayed_pendulum", +) + + + + +PARAM_RANGES: dict[str, dict[str, tuple[float, float]]] = { + "double_integrator": { + "mass": (0.6, 1.6), + "drag": (0.0, 0.4), + "ctrl_cost": (0.02, 0.12), + "vel_cost": (0.05, 0.30), + "force": (1.0, 2.0), + }, + "pendulum_balance": { + "mass": (0.7, 1.4), + "length": (0.7, 1.3), + "gravity": (8.0, 12.0), + "damping": (0.02, 0.20), + "ctrl_cost": (0.005, 0.05), + "torque_frac": (0.50, 0.90), + }, + "pendulum_swingup": { + "mass": (0.7, 1.4), + "length": (0.7, 1.3), + "gravity": (8.0, 12.0), + "damping": (0.02, 0.20), + "ctrl_cost": (0.005, 0.05), + "torque_frac": (0.26, 0.40), + }, + "cartpole_swingup": { + "cart_mass": (0.8, 1.4), + "pole_mass": (0.08, 0.20), + "length": (0.5, 0.9), + "gravity": (9.0, 11.0), + "ctrl_cost": (0.005, 0.05), + "force_frac": (0.75, 1.25), + }, + "reacher2": { + "l1": (0.8, 1.2), + "l2": (0.7, 1.1), + "damping": (0.5, 1.5), + "ctrl_cost": (0.02, 0.10), + "torque": (1.5, 3.0), + }, + "delayed_pendulum": { + "mass": (0.7, 1.4), + "length": (0.7, 1.3), + "gravity": (8.0, 12.0), + "damping": (0.02, 0.20), + "ctrl_cost": (0.005, 0.05), + "torque_frac": (0.26, 0.40), + "delay": (1.0, 2.0), + }, +} + +DT = 0.05 + + +@dataclass(frozen=True) +class EnvSpec: + """A single environment: a family, one parameter draw, and its two transforms.""" + + family: str + params: dict[str, float] + q_rot: np.ndarray + a_perm: np.ndarray + + def to_json(self) -> dict[str, Any]: + return { + "family": self.family, + "params": {k: float(v) for k, v in self.params.items()}, + "q_rot": [[float(x) for x in row] for row in self.q_rot], + "a_perm": [[float(x) for x in row] for row in self.a_perm], + } + + @staticmethod + def from_json(d: dict[str, Any]) -> "EnvSpec": + return EnvSpec( + family=d["family"], + params={k: float(v) for k, v in d["params"].items()}, + q_rot=np.asarray(d["q_rot"], dtype=np.float64), + a_perm=np.asarray(d["a_perm"], dtype=np.float64), + ) + + +def _random_orthogonal(rng: np.random.Generator, n: int) -> np.ndarray: + a = rng.normal(size=(n, n)) + q, r = np.linalg.qr(a) + return (q * np.sign(np.diag(r))).astype(np.float64) + + +def _random_signed_permutation(rng: np.random.Generator, n: int) -> np.ndarray: + perm = rng.permutation(n) + signs = rng.choice([-1.0, 1.0], size=n) + p = np.zeros((n, n), dtype=np.float64) + for i, j in enumerate(perm): + p[i, j] = signs[i] + return p + + +def draw_spec(family: str, seed: int) -> EnvSpec: + """Draw one environment of ``family`` from the disclosed ranges under ``seed``.""" + rng = np.random.default_rng(seed) + params: dict[str, float] = {} + for name, (lo, hi) in PARAM_RANGES[family].items(): + params[name] = float(rng.uniform(lo, hi)) + if family == "delayed_pendulum": + params["delay"] = float(int(round(params["delay"]))) + return EnvSpec( + family=family, + params=params, + q_rot=_random_orthogonal(rng, OBS_DIM), + a_perm=_random_signed_permutation(rng, ACT_DIM), + ) + + +class VecEnv: + """A batch of ``n_envs`` independent copies of one :class:`EnvSpec`. + + Episodes are fixed length (:data:`MAX_EPISODE_STEPS`); ``done`` is True only on the + final step of an episode and the batch auto-resets on the following ``step``. + """ + + obs_dim = OBS_DIM + act_dim = ACT_DIM + max_episode_steps = MAX_EPISODE_STEPS + + def __init__(self, spec: EnvSpec, n_envs: int, seed: int, init_states: np.ndarray | None = None): + self.spec = spec + self.n_envs = int(n_envs) + self._rng = np.random.default_rng(seed) + self._fixed_init = None if init_states is None else np.asarray(init_states, dtype=np.float64) + self._p = spec.params + self._family = spec.family + self._q = spec.q_rot + self._ap = spec.a_perm + self._delay = int(self._p.get("delay", 0.0)) if self._family == "delayed_pendulum" else 0 + self._state = np.zeros((self.n_envs, self.state_dim), dtype=np.float64) + self._buf = np.zeros((self.n_envs, max(self._delay, 1)), dtype=np.float64) + self._t = 0 + + + + @property + def state_dim(self) -> int: + return { + "double_integrator": 4, + "pendulum_balance": 2, + "pendulum_swingup": 2, + "cartpole_swingup": 4, + "reacher2": 6, + "delayed_pendulum": 2, + }[self._family] + + + + def sample_init(self, n: int, rng: np.random.Generator) -> np.ndarray: + f = self._family + if f == "double_integrator": + s = np.zeros((n, 4)) + s[:, 0:2] = rng.uniform(-1.5, 1.5, size=(n, 2)) + s[:, 2:4] = rng.uniform(-0.5, 0.5, size=(n, 2)) + elif f == "pendulum_balance": + s = np.zeros((n, 2)) + s[:, 0] = rng.uniform(-0.35, 0.35, size=n) + s[:, 1] = rng.uniform(-0.8, 0.8, size=n) + elif f in ("pendulum_swingup", "delayed_pendulum"): + s = np.zeros((n, 2)) + s[:, 0] = math.pi + rng.uniform(-0.6, 0.6, size=n) + s[:, 1] = rng.uniform(-0.5, 0.5, size=n) + elif f == "cartpole_swingup": + s = np.zeros((n, 4)) + s[:, 0] = rng.uniform(-0.3, 0.3, size=n) + s[:, 1] = rng.uniform(-0.2, 0.2, size=n) + s[:, 2] = math.pi + rng.uniform(-0.6, 0.6, size=n) + s[:, 3] = rng.uniform(-0.3, 0.3, size=n) + elif f == "reacher2": + s = np.zeros((n, 6)) + s[:, 0] = rng.uniform(-math.pi, math.pi, size=n) + s[:, 1] = rng.uniform(-2.0, 2.0, size=n) + s[:, 2:4] = rng.uniform(-0.5, 0.5, size=(n, 2)) + radius = rng.uniform(0.4, 1.4, size=n) + angle = rng.uniform(-math.pi, math.pi, size=n) + s[:, 4] = radius * np.cos(angle) + s[:, 5] = radius * np.sin(angle) + else: + raise KeyError(self._family) + return s + + + + def _features(self, s: np.ndarray) -> np.ndarray: + f = self._family + n = s.shape[0] + raw = np.zeros((n, OBS_DIM), dtype=np.float64) + if f == "double_integrator": + raw[:, 0:2] = s[:, 0:2] / 1.5 + raw[:, 2:4] = s[:, 2:4] / 2.0 + elif f in ("pendulum_balance", "pendulum_swingup", "delayed_pendulum"): + raw[:, 0] = np.cos(s[:, 0]) + raw[:, 1] = np.sin(s[:, 0]) + raw[:, 2] = s[:, 1] / 8.0 + elif f == "cartpole_swingup": + raw[:, 0] = s[:, 0] / 2.0 + raw[:, 1] = s[:, 1] / 3.0 + raw[:, 2] = np.cos(s[:, 2]) + raw[:, 3] = np.sin(s[:, 2]) + raw[:, 4] = s[:, 3] / 8.0 + elif f == "reacher2": + raw[:, 0] = np.cos(s[:, 0]) + raw[:, 1] = np.sin(s[:, 0]) + raw[:, 2] = np.cos(s[:, 2]) + raw[:, 3] = np.sin(s[:, 2]) + raw[:, 4] = s[:, 1] / 6.0 + raw[:, 5] = s[:, 3] / 6.0 + raw[:, 6] = s[:, 4] / 1.5 + raw[:, 7] = s[:, 5] / 1.5 + return raw @ self._q.T + + def _obs(self) -> np.ndarray: + return self._features(self._state).astype(np.float32) + + + + def _dynamics(self, s: np.ndarray, u: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """One Euler step. Returns (next_state, reward).""" + p = self._p + f = self._family + s = s.copy() + if f == "double_integrator": + acc = (p["force"] * u[:, 0:2] - p["drag"] * s[:, 2:4]) / p["mass"] + s[:, 2:4] += DT * acc + s[:, 0:2] += DT * s[:, 2:4] + s[:, 0:2] = np.clip(s[:, 0:2], -4.0, 4.0) + s[:, 2:4] = np.clip(s[:, 2:4], -6.0, 6.0) + cost = ( + np.sum(s[:, 0:2] ** 2, axis=1) + + p["vel_cost"] * np.sum(s[:, 2:4] ** 2, axis=1) + + p["ctrl_cost"] * np.sum(u[:, 0:2] ** 2, axis=1) + ) + return s, -cost + if f in ("pendulum_balance", "pendulum_swingup", "delayed_pendulum"): + torque = p["torque_frac"] * p["mass"] * p["gravity"] * p["length"] * u[:, 0] + ml2 = p["mass"] * p["length"] ** 2 + acc = ( + p["mass"] * p["gravity"] * p["length"] * np.sin(s[:, 0]) / ml2 + - p["damping"] * s[:, 1] / ml2 + + torque / ml2 + ) + s[:, 1] = np.clip(s[:, 1] + DT * acc, -8.0, 8.0) + s[:, 0] = s[:, 0] + DT * s[:, 1] + ang = np.arctan2(np.sin(s[:, 0]), np.cos(s[:, 0])) + cost = ang**2 + 0.1 * s[:, 1] ** 2 + p["ctrl_cost"] * u[:, 0] ** 2 + return s, -cost + if f == "cartpole_swingup": + mc, mp, l, g = p["cart_mass"], p["pole_mass"], p["length"], p["gravity"] + force = p["force_frac"] * (mc + mp) * g * u[:, 0] + th, thd = s[:, 2], s[:, 3] + sin_t, cos_t = np.sin(th), np.cos(th) + total = mc + mp + temp = (force + mp * l * thd**2 * sin_t) / total + thacc = (g * sin_t - cos_t * temp) / (l * (4.0 / 3.0 - mp * cos_t**2 / total)) + xacc = temp - mp * l * thacc * cos_t / total + s[:, 1] = np.clip(s[:, 1] + DT * xacc, -8.0, 8.0) + s[:, 0] = np.clip(s[:, 0] + DT * s[:, 1], -3.0, 3.0) + s[:, 3] = np.clip(thd + DT * thacc, -12.0, 12.0) + s[:, 2] = th + DT * s[:, 3] + ang = np.arctan2(np.sin(s[:, 2]), np.cos(s[:, 2])) + cost = ang**2 + 0.1 * s[:, 0] ** 2 + 0.02 * s[:, 3] ** 2 + p["ctrl_cost"] * u[:, 0] ** 2 + return s, -cost + if f == "reacher2": + tau = p["torque"] * u[:, 0:2] + s[:, 1] = np.clip(s[:, 1] + DT * (tau[:, 0] - p["damping"] * s[:, 1]), -6.0, 6.0) + s[:, 3] = np.clip(s[:, 3] + DT * (tau[:, 1] - p["damping"] * s[:, 3]), -6.0, 6.0) + s[:, 0] = s[:, 0] + DT * s[:, 1] + s[:, 2] = s[:, 2] + DT * s[:, 3] + ex = p["l1"] * np.cos(s[:, 0]) + p["l2"] * np.cos(s[:, 0] + s[:, 2]) + ey = p["l1"] * np.sin(s[:, 0]) + p["l2"] * np.sin(s[:, 0] + s[:, 2]) + dist2 = (ex - s[:, 4]) ** 2 + (ey - s[:, 5]) ** 2 + cost = dist2 + 0.01 * (s[:, 1] ** 2 + s[:, 3] ** 2) + p["ctrl_cost"] * np.sum( + u[:, 0:2] ** 2, axis=1 + ) + return s, -cost + raise KeyError(f) + + + + def reset(self) -> np.ndarray: + if self._fixed_init is not None: + self._state = self._fixed_init[: self.n_envs].copy() + else: + self._state = self.sample_init(self.n_envs, self._rng) + self._buf[:] = 0.0 + self._t = 0 + return self._obs() + + def step(self, actions: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + a = np.asarray(actions, dtype=np.float64).reshape(self.n_envs, ACT_DIM) + u = a @ self._ap.T + if self._delay > 0: + applied = self._buf[:, 0].copy() + self._buf[:, :-1] = self._buf[:, 1:] + self._buf[:, -1] = u[:, 0] + u = np.stack([applied, u[:, 1]], axis=1) + self._state, reward = self._dynamics(self._state, u) + self._t += 1 + done = self._t >= MAX_EPISODE_STEPS + if done: + obs = self._obs() + dones = np.ones(self.n_envs, dtype=bool) + self._state = ( + self._fixed_init[: self.n_envs].copy() + if self._fixed_init is not None + else self.sample_init(self.n_envs, self._rng) + ) + self._buf[:] = 0.0 + self._t = 0 + return obs, reward.astype(np.float32), dones + return self._obs(), reward.astype(np.float32), np.zeros(self.n_envs, dtype=bool) + + +def eval_init_states(spec: EnvSpec, n: int, seed: int) -> np.ndarray: + """The fixed evaluation initial states for one environment.""" + probe = VecEnv(spec, n_envs=1, seed=0) + return probe.sample_init(n, np.random.default_rng(seed)) diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/grader_core.py b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..d60bf4772cd0c7207295d270321574b59842d606 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import json +from typing import Any + +TAU = 0.9 +HOLD_CHECKPOINTS = 10 + + +M0 = 0.0 +BASELINE_SCORE = 0.8 + + +def normalised_scores(checkpoint_returns, r_rand: float, r_ref: float) -> list[float]: + """s_k = clip((R_k - R_rand) / (R_ref - R_rand), 0, 1); a missing checkpoint is 0.""" + denom = float(r_ref) - float(r_rand) + if denom <= 0.0: + raise ValueError("malformed panel: R_ref does not exceed R_rand") + out = [] + for x in checkpoint_returns: + if x is None: + out.append(0.0) + else: + out.append(min(1.0, max(0.0, (float(x) - float(r_rand)) / denom))) + return out + + +def run_is_reliable(scores: list[float]) -> bool: + """True iff the run holds s >= TAU over the last HOLD_CHECKPOINTS checkpoints.""" + tail = scores[-HOLD_CHECKPOINTS:] + return len(tail) == HOLD_CHECKPOINTS and all(s >= TAU for s in tail) + + +def reliable_success_fraction(runs: list[dict[str, Any]]) -> float: + if not runs: + return 0.0 + return sum(1 for r in runs if r["reliable"]) / len(runs) + + +def graded_reward(metric: float, valid: bool) -> float: + """rational_squash: 0 at the trivial baseline, 0.5 at the baseline score, no cutoff.""" + if not valid: + return 0.0 + x_ref = BASELINE_SCORE - M0 + if x_ref <= 0.0: + raise ValueError("malformed task: the baseline score does not beat the trivial baseline") + u = max(0.0, float(metric) - M0) / x_ref + return u / (1.0 + u) + + +def score_panel(panel: dict[str, Any], results: list[dict[str, Any]]) -> dict[str, Any]: + """Turn raw per-run checkpoint returns into the metric and the reward.""" + by_env = {e["name"]: e for e in panel["envs"]} + runs = [] + for r in results: + env = by_env[r["env"]] + scores = normalised_scores(r["checkpoint_returns"], env["r_rand"], env["r_ref"]) + runs.append( + { + "env": r["env"], + "seed": r["seed"], + "status": r["status"], + "final_s": scores[-1], + "max_s": max(scores), + "reliable": run_is_reliable(scores), + "child_cpu_seconds": r.get("child_cpu_seconds"), + } + ) + metric = reliable_success_fraction(runs) + per_env: dict[str, float] = {} + for r in runs: + per_env.setdefault(r["env"], 0.0) + per_env[r["env"]] += 1.0 / max(1, sum(1 for q in runs if q["env"] == r["env"])) * ( + 1.0 if r["reliable"] else 0.0 + ) + return { + "metric_name": "reliable_success_fraction", + "metric": metric, + "n_runs": len(runs), + "n_reliable": sum(1 for r in runs if r["reliable"]), + "per_env_fraction": {k: round(v, 4) for k, v in per_env.items()}, + "mean_final_s": round(sum(r["final_s"] for r in runs) / max(1, len(runs)), 4), + "runs": runs, + } + + +def load_panel(path: str) -> dict[str, Any]: + with open(path) as fh: + return json.load(fh) diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/hidden_data/final/panel.json b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/hidden_data/final/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..27534dfc3d9e47f882d38201d2730565031d1a6a --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/hidden_data/final/panel.json @@ -0,0 +1,1701 @@ +{ + "envs": [ + { + "name": "env0", + "spec": { + "family": "double_integrator", + "params": { + "mass": 0.7500904531768806, + "drag": 0.22880469707860107, + "ctrl_cost": 0.06215148288605657, + "vel_cost": 0.16093156174667922, + "force": 1.672614072100946 + }, + "q_rot": [ + [ + 0.07993440537345187, + 0.17942468813657392, + -0.39838045586484133, + 0.6359448253087389, + -0.5308771468864227, + -0.28135110543489467, + 0.08521824607321514, + -0.17330125387066272 + ], + [ + -0.4674256577245195, + 0.24434638758954513, + -0.08735165142151924, + -0.5418242732911945, + -0.32384480449551994, + -0.3225635432259124, + -0.27439896819766696, + -0.3693057712438322 + ], + [ + -0.22773690708027183, + 0.4179282585818514, + 0.5645190185056339, + 0.18267502148321504, + -0.3404255875232331, + 0.08610380368901831, + -0.17558203649552176, + 0.5169985385991194 + ], + [ + 0.12411930921958714, + 0.16991715012520456, + 0.16941647998098538, + -0.3069977050233571, + -0.2973669351022548, + 0.07774684895204975, + 0.8557587004192687, + -0.07732014379234066 + ], + [ + -0.5990316947844613, + 0.24419653558472815, + -0.47752339270040617, + 0.09758679943056249, + 0.19126280664477496, + 0.4979681552564524, + 0.20155105318900896, + 0.13711577136170724 + ], + [ + -0.47989408490854174, + -0.6321000225562241, + 0.026891677774991782, + 0.060377444037302046, + -0.08540895445490929, + -0.4178972606800209, + 0.25113669146326395, + 0.34753443410419366 + ], + [ + 0.1174838232547594, + 0.48011186202165046, + -0.1983969952735943, + -0.08225385021909837, + 0.4536737049117078, + -0.597689910173191, + 0.14148188353325453, + 0.3556584105441933 + ], + [ + -0.3239047556885374, + 0.12196708724096109, + 0.467082342624822, + 0.39299944863137054, + 0.3991006659319303, + -0.15327180322616837, + 0.17487556632142595, + -0.5424391270438563 + ] + ], + "a_perm": [ + [ + 1.0, + 0.0 + ], + [ + 0.0, + 1.0 + ] + ] + }, + "eval_init": [ + [ + -0.9648610765262745, + -0.9684037988377553, + -0.03755906360107286, + 0.4877262128108776 + ], + [ + 0.8357640755346951, + 0.273164483812395, + -0.3885127236202546, + -0.3765723744433086 + ], + [ + 0.743049536237065, + 1.2177624137900125, + -0.4585837953504539, + -0.2641477202661314 + ], + [ + -1.4569500201853347, + 1.4249467404458604, + 0.3462919290702561, + -0.3618086692437348 + ], + [ + -1.331834867045592, + -0.32749835465705157, + -0.11174938972827375, + -0.3755570961640359 + ], + [ + 0.8763246015525068, + 1.0670434810747618, + -0.2762963014928852, + -0.48363135713353456 + ], + [ + 1.1827958557064964, + 0.010351825118354085, + 0.4613829098938811, + 0.24561927827577612 + ], + [ + 0.8081530428992072, + -1.07695990192801, + -0.23149102342996752, + 0.031203729480277165 + ], + [ + 0.7186902215996076, + -1.2833915591833431, + 0.44127224389629305, + -0.0314964636585604 + ], + [ + 1.4462494183926609, + 0.23512127733354404, + 0.1467274998892023, + -0.39223643940612396 + ], + [ + -0.3095232750625896, + -0.5342427314011037, + -0.17058086595593358, + -0.08206350441798271 + ], + [ + -0.05965214299162547, + 1.1267027275427695, + -0.24522033102221064, + -0.23547724011131022 + ], + [ + -1.3137860823959056, + 0.6673894576304793, + -0.015547454061527799, + 0.3081155362532264 + ], + [ + -0.2205416607384909, + -0.3163115872971951, + -0.08547053144337113, + 0.3907923851073952 + ], + [ + -1.2100941508200262, + 1.1006758679224289, + 0.25571545743314983, + 0.02851304047026837 + ], + [ + 1.0859219435642116, + 0.2678749014187276, + -0.09861819901497415, + 0.03965750608098795 + ], + [ + 1.1659712733022367, + 0.28076899456537197, + 0.10424231985913401, + 0.028368423561911826 + ], + [ + -1.0435941780892934, + -0.9025088362218904, + 0.45212980798506186, + -0.30994864080756745 + ], + [ + -1.0710846889145187, + -0.7794770730944733, + 0.19454077195921216, + -0.45848073815428003 + ], + [ + 0.048221843869362235, + -0.8322072918204048, + 0.14135660080455037, + -0.3552799863829571 + ], + [ + -0.9928911219275014, + 1.4977807699546712, + -0.22135398942326479, + -0.25617328100035275 + ], + [ + -1.039217177812882, + -1.4868272646089498, + 0.3712557326186926, + -0.29724744713730566 + ], + [ + 1.4748619829564098, + -0.15269276491085804, + 0.49249036014956105, + -0.20532773698163254 + ], + [ + -0.00821789862511646, + -0.4419918503334084, + -0.36477832837222146, + 0.14207285632421174 + ], + [ + -1.2295118964816787, + -0.7281704026800392, + -0.09947113757953419, + 0.49612787318589446 + ], + [ + 1.1842964593236305, + -0.6022933914284196, + 0.27006467366743914, + 0.29138364932608696 + ], + [ + 1.3233057812045979, + -1.1249799659561979, + -0.461156875978625, + 0.3354105022105093 + ], + [ + -0.0035448024737825268, + -1.4322657434585104, + 0.2882166636804797, + -0.4447833235812447 + ], + [ + -0.8165555650429385, + 0.9664972290647169, + -0.03421742352816792, + 0.11434914242462102 + ], + [ + -0.810148138168204, + -0.7885441372616736, + -0.4464732521881506, + -0.42162873031182935 + ], + [ + -0.6801592703678854, + 1.2201617016260076, + -0.28400354254288873, + 0.32540750531982243 + ], + [ + -0.030598277044317834, + -0.036922976070434155, + -0.21520497159263718, + -0.0689558999747576 + ] + ], + "r_rand": -305.89647344611876, + "r_ref": -25.581103072667663 + }, + { + "name": "env1", + "spec": { + "family": "pendulum_balance", + "params": { + "mass": 1.2425864795683883, + "length": 1.1945843427711962, + "gravity": 11.127554189393, + "damping": 0.15513138306412044, + "ctrl_cost": 0.03555220401881967, + "torque_frac": 0.5947573322950525 + }, + "q_rot": [ + [ + -0.0877667273624847, + 0.3272324241402534, + 0.1000900907535637, + -0.06989626048735698, + -0.6399674995673811, + 0.2217716812076996, + 0.5938470398273613, + -0.24272833139595382 + ], + [ + -0.14049692745828937, + 0.2690251005122621, + -0.6154240239084909, + -0.46134907419691895, + 0.30131855462151463, + -0.3375716520632548, + 0.23366012543873477, + -0.2386458994978022 + ], + [ + -0.7916164393728983, + -0.46613499032603506, + -0.13407220099144476, + -0.12534917280147248, + -0.013437955103129775, + 0.34625952847526237, + 0.021437495839337, + 0.04287199065230704 + ], + [ + 0.32648835982105545, + 0.02246845557853985, + -0.2991809090291071, + 0.13762594461031713, + 0.3113098790201263, + 0.7619152168986788, + 0.01998097181255267, + -0.32653104706298064 + ], + [ + -0.012644265207984767, + 0.32510445410430966, + -0.5302814894477662, + 0.14084973901135758, + -0.29824473221845627, + 0.17267596651877243, + -0.1904165255129802, + 0.6618797070092826 + ], + [ + -0.4405427217367011, + 0.5110789615973728, + 0.04232560623525938, + 0.4415416824514173, + 0.02603302662484914, + -0.06519722769867731, + -0.4174250571549152, + -0.4108501134678347 + ], + [ + 0.04275086519958183, + -0.3733170279562185, + -0.3779817750847838, + 0.6918539901331383, + -0.07064348390650153, + -0.3107415871635685, + 0.3496528668687384, + -0.11604581458339859 + ], + [ + 0.20794464447455208, + -0.3106405652121897, + -0.27908875977488584, + -0.23271995782676885, + -0.554919965522632, + -0.07631671134295519, + -0.5090486958701017, + -0.39410831777892225 + ] + ], + "a_perm": [ + [ + -1.0, + 0.0 + ], + [ + 0.0, + 1.0 + ] + ] + }, + "eval_init": [ + [ + 0.24071866233154016, + -0.6568435645826792 + ], + [ + -0.08035434791483748, + 0.507528897023509 + ], + [ + 0.34563206838184823, + -0.08140422305686723 + ], + [ + 0.22913746541815716, + 0.28677382479289437 + ], + [ + 0.07205335256861395, + 0.7704822827749374 + ], + [ + -0.04552634442952275, + -0.6896060934226969 + ], + [ + -0.2679446960998738, + 0.26113936541872373 + ], + [ + -0.16345164985176114, + 0.25902339623206894 + ], + [ + 0.3242331240400038, + -0.4303790581898948 + ], + [ + -0.11047324196636366, + 0.14494236665130877 + ], + [ + 0.22459837892548395, + -0.5103391336924992 + ], + [ + 0.11035913997018593, + 0.5264865286292044 + ], + [ + -0.26120282407498635, + -0.4081252634812284 + ], + [ + -0.12489292521500334, + -0.03536279721345004 + ], + [ + -0.13192197808637512, + 0.3567621405908059 + ], + [ + 0.08046016677266077, + 0.2666921660275219 + ], + [ + -0.33886798378533106, + 0.749149151307452 + ], + [ + -0.05236563936532118, + 0.539021730699345 + ], + [ + -0.23176526734210373, + 0.7072610364225473 + ], + [ + -0.3365143886914327, + 0.09049726059928331 + ], + [ + 0.12120500555811742, + 0.35165150250115107 + ], + [ + -0.12378405602423645, + -0.5534941835054861 + ], + [ + -0.2734220789536866, + -0.6309239499774689 + ], + [ + -0.2438918590144312, + 0.6681410193503716 + ], + [ + -0.040761535837380014, + 0.5773288601703752 + ], + [ + -0.2266649557422829, + 0.28639791134602355 + ], + [ + 0.2608740276547392, + 0.7795949014354366 + ], + [ + 0.34955909748152425, + 0.17655482528298538 + ], + [ + -0.1736838539237584, + -0.02071666160569463 + ], + [ + 0.24611849442301348, + -0.19683005798636244 + ], + [ + 0.078758531407149, + 0.3402862920180083 + ], + [ + -0.008443363716029606, + -0.3638022250497825 + ] + ], + "r_rand": -379.22507980343084, + "r_ref": -0.5318407513647495 + }, + { + "name": "env2", + "spec": { + "family": "pendulum_swingup", + "params": { + "mass": 0.918057156873241, + "length": 0.9654386864609132, + "gravity": 9.592148104489734, + "damping": 0.03720809855049635, + "ctrl_cost": 0.01645288786036244, + "torque_frac": 0.3260343637119746 + }, + "q_rot": [ + [ + -0.589119147176133, + 0.03495001210024787, + -0.0906555784685015, + -0.660831276927197, + -0.16975738615021194, + -0.24052108898358307, + -0.339846787723149, + -0.06809488297828573 + ], + [ + -0.06188022626473018, + -0.009162460155340264, + -0.3198284694339003, + 0.08881546996607736, + -0.6089277897313676, + 0.07321603739313422, + 0.3909891583983315, + -0.5973962555388875 + ], + [ + 0.4936669014754002, + 0.16198261433869157, + 0.05384555892858437, + -0.17046338142136966, + 0.14174749497893444, + -0.7498110786361799, + 0.00602915569637479, + -0.34022368777170064 + ], + [ + -0.4937644800320026, + -0.12034237152793631, + 0.08291270276794965, + 0.36838771795396913, + -0.007123838540713673, + -0.5600319733227725, + 0.44611901680147775, + 0.2939754878946009 + ], + [ + -0.21483813138985716, + 0.9345450849353298, + 0.17676218422017945, + 0.1640563622364079, + 0.06175007845105615, + 0.09172894901259905, + 0.026036085237810397, + -0.096982223904289 + ], + [ + 0.3356564997333801, + 0.2513250071394755, + -0.1193617625580476, + -0.3098136896974391, + -0.5015018345019461, + -0.04496509509117507, + 0.23289370575528426, + 0.637317247783526 + ], + [ + 0.047205753802158724, + -0.11026669075178958, + 0.698867714413612, + 0.22288111624132012, + -0.5469954320132198, + -0.08080557261387215, + -0.3742516282563984, + -0.04150873438911861 + ], + [ + -0.023452184757828693, + -0.09631393546802262, + 0.5880555019337326, + -0.46698132328110653, + 0.16039049376787795, + 0.20969251871318195, + 0.5810262247535715, + -0.13785954616953108 + ] + ], + "a_perm": [ + [ + 1.0, + 0.0 + ], + [ + 0.0, + -1.0 + ] + ] + }, + "eval_init": [ + [ + 3.740931550381392, + -0.09244991571981331 + ], + [ + 2.7199750963396783, + -0.0866314715331189 + ], + [ + 2.9066386525080063, + -0.22912445793175373 + ], + [ + 2.8192970796010925, + -0.12195949955095031 + ], + [ + 3.062245334121198, + -0.09335987660311151 + ], + [ + 2.5864695606329766, + 0.3110821742336014 + ], + [ + 3.4347790683335275, + 0.15496194067394198 + ], + [ + 3.4845970709190306, + -0.22667257674191155 + ], + [ + 2.76865049063757, + -0.34924213715015195 + ], + [ + 2.596739445938068, + -0.11085473794716694 + ], + [ + 3.7250940784007063, + 0.1836909112472016 + ], + [ + 3.0361056641761937, + -0.07828404899526786 + ], + [ + 3.0215973903169706, + 0.17632012710485745 + ], + [ + 3.6491607508926016, + 0.05834054344738404 + ], + [ + 3.4846569923724577, + -0.313381898784742 + ], + [ + 3.069048265056339, + 0.45766738253459105 + ], + [ + 2.701303854604547, + -0.01586670425086001 + ], + [ + 3.5330248740414936, + 0.03783538075254944 + ], + [ + 3.1756727228250745, + -0.3007819670113896 + ], + [ + 3.4943388290824666, + 0.17312298589987185 + ], + [ + 3.4286855355773165, + 0.10092895625135001 + ], + [ + 2.723631560404087, + 0.44512256399954764 + ], + [ + 2.9196665906768464, + -0.2749502476944321 + ], + [ + 2.8176889152447995, + 0.07701607828049462 + ], + [ + 3.721215877331861, + 0.19503115647162905 + ], + [ + 3.5436813147295707, + -0.12469737623511734 + ], + [ + 2.5647824928053904, + 0.14257079006705298 + ], + [ + 3.559471926240808, + -0.13375200394075404 + ], + [ + 3.2904671805958916, + -0.4301173798192003 + ], + [ + 2.684033261667719, + -0.1186618845029972 + ], + [ + 3.547532624347445, + 0.1602910208819488 + ], + [ + 3.264046824760361, + 0.19976525024302716 + ] + ], + "r_rand": -853.1133078355342, + "r_ref": -486.4170036247039 + }, + { + "name": "env3", + "spec": { + "family": "cartpole_swingup", + "params": { + "cart_mass": 1.002104553764785, + "pole_mass": 0.09621757293513652, + "length": 0.6241178959968927, + "gravity": 10.807397315487474, + "ctrl_cost": 0.020631272820427562, + "force_frac": 0.8569369051785882 + }, + "q_rot": [ + [ + -0.022244992198632296, + -0.2821017490585682, + -0.2235023236925052, + 0.44402772525066525, + -0.5507682271981285, + -0.4989561666002753, + -0.3464376490017322, + -0.02208875477910442 + ], + [ + 0.10467282658220385, + 0.48450500300790106, + 0.27244789102507616, + 0.37776421873732546, + 0.009716508501381097, + 0.21500288804791262, + -0.380422296805949, + -0.5884921977731374 + ], + [ + -0.4129384243654649, + -0.10830310729183781, + -0.5775977890935541, + -0.21420453282728427, + -0.19110202666963128, + 0.5426186758695102, + -0.2515166788755964, + -0.20984245288251807 + ], + [ + 0.2011992521692435, + -0.40443919285954244, + 0.5605245443550585, + -0.3371749322504785, + -0.2855970824541314, + 0.2817218353704474, + -0.43714429300455404, + 0.12666918135774607 + ], + [ + 0.09260909347867609, + 0.5480905095185243, + -0.08767702163745603, + 0.15287638593482408, + -0.2938549361510523, + 0.2505544481868873, + -0.13814731520572127, + 0.7012481472174812 + ], + [ + -0.8672493024274475, + 0.09774127707506887, + 0.3968226550305425, + 0.03325328572599955, + 0.08720198285530249, + -0.1760162537771394, + -0.13222945554236948, + 0.15388552016713647 + ], + [ + 0.06572788853591294, + -0.3219116450786702, + -0.13619949516277904, + 0.40715979616268244, + 0.6600773779860407, + 0.14946729826819324, + -0.4147951270740945, + 0.27861392591288064 + ], + [ + 0.11194429962822242, + 0.31110964363495397, + -0.21049015425556414, + -0.5570520509156419, + 0.22094618581197253, + -0.4635887786219311, + -0.5218043232208633, + -0.007392329078769345 + ] + ], + "a_perm": [ + [ + 1.0, + 0.0 + ], + [ + 0.0, + -1.0 + ] + ] + }, + "eval_init": [ + [ + 0.23223417144012087, + 0.18527911639555822, + 2.8692036465318673, + -0.2190922328039951 + ], + [ + 0.06514931157065718, + -0.05273431480824167, + 3.452651317884337, + -0.15705570566554777 + ], + [ + 0.29843134093856843, + -0.058423072215492644, + 3.306754578963818, + -0.04385335275248914 + ], + [ + -0.1313196085502593, + -0.1663304765247678, + 2.7999523834777826, + -0.0769639156873638 + ], + [ + -0.16645188243760264, + 0.06376353477561836, + 2.6754880257470295, + 0.03741295866520211 + ], + [ + 0.0769956672406753, + 0.05442872029030521, + 3.2422259017802704, + -0.06785507972730404 + ], + [ + 0.26303469923178174, + -0.012325876483914255, + 3.3680282601269376, + -0.10118331389857799 + ], + [ + 0.11472912880030928, + 0.18237930295018223, + 2.7753462022001374, + 0.2664793892469092 + ], + [ + -0.1679732605956964, + -0.08690403661345183, + 2.8762693763278264, + 0.24575457230468428 + ], + [ + -0.22281797873504516, + -0.17048008815627536, + 3.6720418233585477, + 0.005578114133584555 + ], + [ + 0.265455628799735, + -0.13203575358057257, + 2.574856313751377, + 0.16007273804912464 + ], + [ + -0.00478794539076105, + -0.19846330741415216, + 2.554162971580686, + 0.0830967635783435 + ], + [ + -0.10364968638317812, + 0.01363437310854404, + 2.7752813850962306, + -0.029515829651447834 + ], + [ + 0.14999619444297257, + 0.14854320954395928, + 3.5183281195770935, + -0.15069468408222275 + ], + [ + -0.11626438200870448, + 0.18733247297218664, + 2.7475096819992038, + -0.10826377090211517 + ], + [ + 0.15200868991760025, + -0.17267942646253498, + 3.2140912723005046, + 0.01764334630865655 + ], + [ + -0.15806873703998295, + -0.11916139477902399, + 3.2742199679468262, + 0.2879674349169959 + ], + [ + 0.22757065082706546, + 0.0013615730131579795, + 3.4088895746037595, + 0.051493172100620654 + ], + [ + -0.2686382996644591, + 0.16206455042213025, + 3.073984189559009, + -0.017447437537759625 + ], + [ + 0.15807279483901443, + -0.19641385536992623, + 3.222722324239422, + -0.20543479320875965 + ], + [ + -0.27468352107142735, + 0.05762426151307415, + 2.6257888630552655, + 0.29505754570311266 + ], + [ + 0.06632007226490189, + -0.06479999727192207, + 2.988672451015667, + 0.02095436650316662 + ], + [ + -0.2513673828321628, + 0.09927609329144027, + 2.9665030316914485, + -0.03583256611680807 + ], + [ + -0.1264475018337169, + -0.10198366334818904, + 3.5506679593493375, + -0.17927504311159304 + ], + [ + 0.04720355676088428, + 0.03142268363075673, + 2.7821733995315903, + 0.1318518244209933 + ], + [ + 0.07780530294706767, + -0.14121528039575276, + 2.8028826242633373, + -0.03301201984656771 + ], + [ + -0.20882413072833844, + 0.07722453074670155, + 2.7357494836179224, + -0.1525471684470231 + ], + [ + 0.1540054718728236, + 0.15898574380408015, + 3.200454451085376, + 0.08309004089907918 + ], + [ + 0.2784097507565371, + -0.09232958429623195, + 3.096300592451788, + -0.12091775777800726 + ], + [ + 0.090282811560505, + 0.014739786589943016, + 3.4219487669575233, + 0.19597997939193929 + ], + [ + 0.08305749452500688, + 0.08823690499593617, + 3.145303169984563, + 0.21427613436250742 + ], + [ + 0.2583498873751852, + 0.09713475999508236, + 3.094330098410026, + -0.25176016333610335 + ] + ], + "r_rand": -817.0520738759078, + "r_ref": -199.50662789696557 + }, + { + "name": "env4", + "spec": { + "family": "reacher2", + "params": { + "l1": 0.8111295463086842, + "l2": 0.7538973560736589, + "damping": 1.1798085882396492, + "ctrl_cost": 0.02312545857048761, + "torque": 1.5391573022569864 + }, + "q_rot": [ + [ + -0.6362074456375248, + -0.03870778904091528, + 0.7133401121062471, + 0.15344374753446766, + -0.009284297632616425, + 0.11004698413494857, + -0.21193594752447995, + 0.06503315487454722 + ], + [ + 0.15613212905351165, + 0.027909027996300344, + 0.1560808284530764, + -0.1111108568749814, + -0.894323389296727, + 0.25911610523658113, + 0.06546565054858146, + -0.2586421560177676 + ], + [ + -0.09730570570051492, + -0.22568179456380277, + 0.11690200395849597, + 0.11487379439275186, + 0.1386188695097647, + -0.34711088787171973, + 0.38042106251014735, + -0.7926638100785715 + ], + [ + -0.028911314375680428, + -0.14120287900313302, + -0.2941962600761151, + 0.1566373830334889, + 0.05197648582908616, + 0.21545040733076812, + -0.790070356363116, + -0.44137010836039553 + ], + [ + -0.499140149137702, + 0.012428573765728436, + -0.49178106789273324, + 0.4742536566415959, + -0.371377762510811, + -0.3306823588741304, + 0.08188357391070857, + 0.17309623873098612 + ], + [ + 0.3434760174874002, + 0.06228666626767105, + 0.13167886148253333, + 0.8123401149130602, + 0.1061918998900343, + 0.39038148657457133, + 0.19220198788094808, + 0.01711090149990296 + ], + [ + -0.1284274668121563, + -0.8593742885037814, + -0.15200696483532286, + -0.09165893880468527, + 0.013534083558603084, + 0.37794391025766355, + 0.2099656700924222, + 0.16237113742780745 + ], + [ + -0.4206522347852065, + 0.4292947726278333, + -0.290298265271879, + -0.18210925629310612, + 0.16970974516336734, + 0.5909767609307117, + 0.30681255434046756, + -0.2216572995699551 + ] + ], + "a_perm": [ + [ + -1.0, + 0.0 + ], + [ + 0.0, + 1.0 + ] + ] + }, + "eval_init": [ + [ + -0.5505739307211002, + -0.859503834688859, + 0.24944996040394196, + -0.28930401063245637, + -0.12808079402786296, + 0.7736141650193881 + ], + [ + 1.9319689255074648, + 1.5560391924058936, + 0.20245214234012887, + 0.2423334131868512, + 0.2337558549527762, + 0.5004337190927453 + ], + [ + 0.22531701032764495, + -0.7213508934212238, + 0.4262552612655477, + -0.45772307325547756, + -0.16926820487300953, + -0.8671781674680692 + ], + [ + -0.9564956852007991, + -1.1120489201829904, + 0.20354831510337845, + 0.45421474007588103, + -0.4063619583453039, + -1.289188911269633 + ], + [ + -2.758414286403215, + -1.7159161441422945, + 0.4744443745299308, + -0.3265956399723575, + -1.0958436165035819, + 0.01654778179879407 + ], + [ + -2.53714015787531, + 1.1530851471906955, + -0.3791795223140788, + -0.02774680454762324, + -0.5827516420212072, + 0.12509759009508523 + ], + [ + 2.8906980931286723, + -1.211543166803672, + -0.1116024123136592, + -0.06418746045080381, + -0.7799837423758038, + 0.302325215940251 + ], + [ + 2.8558072904379914, + 1.9841003915856779, + -0.406015422479055, + -0.4291531576282238, + 1.0734446967144275, + -0.8152913841193362 + ], + [ + 1.6842702363770519, + 1.7729892028024774, + -0.048129594093566874, + -0.41588247977673454, + 0.2384104007638285, + 1.120925132961921 + ], + [ + 1.238671163052408, + 1.1563225324841637, + 0.3803520121687227, + -0.1298323556029245, + -0.18562457248186925, + -0.515082935501918 + ], + [ + 1.4009358397841742, + -1.4323937251542307, + -0.2761866137502781, + -0.2223445967641532, + 1.0811406643857122, + 0.2302547713083256 + ], + [ + 1.008822323299583, + -1.2879932693594216, + 0.17534995616071802, + -0.11085105838200782, + 0.18575991478045342, + 0.3661034294248313 + ], + [ + -2.301516322879199, + -0.895621189765166, + 0.08190986071587936, + 0.43811792434362884, + 0.06973598968350829, + 0.39698909979896413 + ], + [ + -0.4663436182373655, + -1.4136624648826523, + 0.10488335763283796, + 0.22982586319009923, + 0.12325945712109163, + -1.009677995381358 + ], + [ + -1.7589038056165593, + -1.9707413413531172, + -0.4804811505367734, + -0.03838520751031482, + -0.7149269840204858, + 0.16352003234754275 + ], + [ + -1.6204101338267127, + -0.19671299829557842, + 0.16071879600509087, + -0.41410960647315986, + -1.018876999819982, + 0.1891268207924593 + ], + [ + -1.7037372216669084, + -1.7244611562295424, + 0.0674568128821722, + -0.23025385063538784, + -0.40921600786000983, + -0.9501113909763963 + ], + [ + 2.0527235170236278, + 1.683142760671199, + -0.09539348890554233, + -0.21469862155526054, + 0.9124930198255984, + 0.7517674379590363 + ], + [ + 0.3699819528212962, + 1.6627960610589216, + 0.1466590634983943, + -0.44846377197042775, + -0.3325114636985053, + 0.8188368335889805 + ], + [ + -2.687523171585151, + -0.13293100126939672, + -0.22228897592097496, + 0.13551738179670125, + -0.42708292534318854, + -0.3906485271088465 + ], + [ + 0.6843827775070657, + 0.1619231881381662, + -0.37236250689650585, + 0.15457560737726495, + 0.4689974649492484, + 1.006720976504375 + ], + [ + -0.22150317225870886, + 1.2456219721566306, + -0.2705079287740745, + -0.23833586654106076, + -0.11307888911204746, + 0.5594481640253594 + ], + [ + 0.6196758443117893, + -1.4813914244488706, + -0.2805318263997969, + -0.32656370144127156, + -0.23172072651884734, + 0.33971723672299375 + ], + [ + -2.451615825599631, + 0.04158967599998231, + -0.3148117578086156, + 0.19057651559751576, + 0.7702188013995771, + -0.6557091123318787 + ], + [ + 2.6057306255086043, + 0.4098823002901262, + -0.24017130537297304, + -0.05200038580153643, + 0.15022440711353544, + -0.8551891217894325 + ], + [ + -3.0658137774506895, + 1.7974997241321118, + 0.0054476227161806, + 0.41775828386479497, + 0.45682165965663524, + -0.00784400456863943 + ], + [ + 1.5943940677247026, + 1.8509319230868635, + 0.06415233022128763, + 0.2596088558007329, + -0.5063919351178977, + -0.31290486902470027 + ], + [ + 2.290566085329, + -1.0471485082063459, + -0.3932102678678179, + 0.08364499210062704, + -0.7540545571322818, + 0.21788790506047948 + ], + [ + 2.102826667854564, + 1.213989472688874, + 0.37801288861262483, + 0.41630561073033157, + -0.5460192328156022, + -0.13615598166883497 + ], + [ + -2.434840163963004, + 0.6340021820107622, + -0.20077668886006472, + 0.3581684850967928, + 0.8158336155368012, + 0.842381637722042 + ], + [ + 1.505411557573689, + 1.5247286317501536, + -0.2550881531228356, + -0.3794706704540797, + -0.39485699186557044, + -0.8241719166893933 + ], + [ + -2.1263291771488575, + 0.36722552678661646, + -0.03356412605402592, + 0.2579214426678421, + 0.24601495573446688, + -1.0704734884230607 + ] + ], + "r_rand": -260.68119913357805, + "r_ref": -75.06904838883277 + }, + { + "name": "env5", + "spec": { + "family": "delayed_pendulum", + "params": { + "mass": 0.968202987609961, + "length": 0.8112885408287115, + "gravity": 9.616577526240151, + "damping": 0.15210873469416128, + "ctrl_cost": 0.014734183001814179, + "torque_frac": 0.30289531167687944, + "delay": 1.0 + }, + "q_rot": [ + [ + -0.2754017134123945, + 0.019328976981859824, + -0.11994677020873731, + 0.6881985251183269, + 0.04213072084667263, + -0.6453452861992819, + -0.13189297716100112, + 0.011599817098466626 + ], + [ + 0.2042443249036316, + 0.32547133389136923, + -0.07586169794560105, + -0.25418551660886896, + -0.4542958585729603, + -0.2284409839287693, + -0.6841503187984811, + -0.23527797075751747 + ], + [ + 0.6534443920393568, + 0.10321674995350624, + 0.12059719017759232, + 0.30008744392762443, + -0.22414975081396346, + -0.09295419512116052, + 0.4511790995101536, + -0.4419438875516071 + ], + [ + -0.5919611713171568, + -0.0666448362347112, + 0.3765141511023292, + 0.04756378651765311, + -0.23278930127220074, + 0.19643745183311556, + 0.040453204731469426, + -0.6377305266688512 + ], + [ + 0.11753227747233894, + -0.3732644364951861, + -0.6153042573379759, + 0.20138850215077334, + 0.24584710809194257, + 0.33305359224030917, + -0.278024483418188, + -0.4231312527597443 + ], + [ + 0.09971918477679821, + -0.6841785625921096, + 0.13767924932461742, + 0.17342080726495615, + -0.5966736489756869, + 0.08637616821603188, + -0.11475238392119293, + 0.3102854027449311 + ], + [ + -0.17799218931508362, + 0.499318025816323, + -0.35420850281596195, + 0.34630922904076916, + -0.4164800562584228, + 0.4763306730319881, + 0.1310826437552933, + 0.23680653966006318 + ], + [ + 0.22269166720322356, + 0.14783245187815575, + 0.5482085539120233, + 0.4229604450425084, + 0.31223456641999753, + 0.3726118298682248, + -0.44910484273305423, + 0.10535972136239254 + ] + ], + "a_perm": [ + [ + -1.0, + 0.0 + ], + [ + 0.0, + -1.0 + ] + ] + }, + "eval_init": [ + [ + 3.4248781776173387, + -0.2885294379631418 + ], + [ + 3.1850396865998043, + -0.220072711208675 + ], + [ + 2.5620780181869205, + -0.21584468148523195 + ], + [ + 2.778559521078085, + -0.12997487976395772 + ], + [ + 3.0992013083003522, + 0.09530572854515684 + ], + [ + 2.61095995074227, + 0.03481922962413386 + ], + [ + 2.74483678118007, + 0.49912793141078227 + ], + [ + 2.7527077481681, + -0.35235591588078397 + ], + [ + 3.2664041937037886, + -0.3508343792375076 + ], + [ + 3.412277737309541, + -0.11430587318388241 + ], + [ + 2.8351706589757564, + -0.327601858795455 + ], + [ + 2.9030324167283985, + -0.3431248795444134 + ], + [ + 2.9830520986421094, + 0.2940074762316821 + ], + [ + 2.9791727789960043, + 0.39465470433328054 + ], + [ + 3.6445008512760064, + -0.440251389034504 + ], + [ + 2.800058006317318, + 0.09979766607642615 + ], + [ + 3.5304502567641176, + -0.02907000630746348 + ], + [ + 3.64495492800879, + 0.07692801992895282 + ], + [ + 2.702895588276774, + 0.09204381984156329 + ], + [ + 3.515505828625556, + 0.3636088631605139 + ], + [ + 2.9397872460211225, + -0.12645476415267054 + ], + [ + 2.8122695571652594, + -0.017345257660904112 + ], + [ + 2.73560556992783, + 0.14538189054592532 + ], + [ + 3.025801766883327, + -0.17995287056797904 + ], + [ + 3.477093931707235, + 0.43235440866236974 + ], + [ + 2.9365370486943965, + -0.20760375475804516 + ], + [ + 3.105491363386058, + 0.2756651127127909 + ], + [ + 3.6423270739642675, + -0.4609419893797614 + ], + [ + 2.962014130516781, + 0.41051461084320373 + ], + [ + 3.3260945139866225, + 0.29696562302801965 + ], + [ + 3.377825327863407, + -0.11903738712677159 + ], + [ + 3.2249727516688393, + 0.009460696303471128 + ] + ], + "r_rand": -884.8063509892672, + "r_ref": -557.7100983995479 + } + ], + "run_seeds": [ + 1000, + 1001, + 1002, + 1003, + 1004, + 1005, + 1006, + 1007, + 1008, + 1009, + 1010, + 1011 + ] +} \ No newline at end of file diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/hidden_data/intermediate/panel.json b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/hidden_data/intermediate/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..7347f629774c76ed40870667115ba03196fb9d77 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/hidden_data/intermediate/panel.json @@ -0,0 +1,1701 @@ +{ + "envs": [ + { + "name": "env0", + "spec": { + "family": "double_integrator", + "params": { + "mass": 1.124965366951646, + "drag": 0.1939583414060612, + "ctrl_cost": 0.07213898702641623, + "vel_cost": 0.13982851633588594, + "force": 1.9580313215835972 + }, + "q_rot": [ + [ + 0.44583599719885303, + -0.24444658675342348, + -0.42051761175705715, + -0.02388668575277161, + 0.04014916726912448, + 0.6075387647732341, + -0.43873811388481915, + 0.02939481863176642 + ], + [ + 0.1552941898790499, + -0.4585629526960799, + 0.30410517518888197, + -0.6802198474086955, + 0.2638592855736102, + 0.11713120519416328, + 0.34980267950304733, + 0.06871228578593418 + ], + [ + 0.627091612864061, + 0.22111745294010532, + -0.3756572984093942, + 0.07398367763531606, + 0.1570143460259932, + -0.2638830328140909, + 0.5019399566891942, + -0.25502884285871874 + ], + [ + 0.32906819194798775, + 0.2823007728225626, + 0.6589074326468852, + 0.04664934704937324, + -0.03606644956114793, + 0.21570432288493216, + -0.19758939761799318, + -0.5374146616795904 + ], + [ + 0.208555926250435, + -0.4658625420151944, + 0.2675644887938891, + 0.5594383327593013, + 0.4760459003417587, + -0.27911043921622175, + -0.14698672322035272, + 0.1696675585791176 + ], + [ + 0.23130476153891547, + -0.21512993659373547, + -0.06514580402830283, + -0.33987774615980265, + -0.3506422633046476, + -0.6356125833337396, + -0.48536362523570015, + -0.13388486824097143 + ], + [ + 0.33231784688771254, + -0.15309482795162993, + 0.24191579024889018, + 0.2251067326243156, + -0.6968186112302102, + 0.10382032907626909, + 0.2871434261422298, + 0.4220714948759678 + ], + [ + 0.26105860236795464, + 0.560921033917516, + 0.14508476474858417, + -0.22342664955302755, + 0.26016563020096056, + -0.09126700415812382, + -0.2335109633044925, + 0.6447509224318316 + ] + ], + "a_perm": [ + [ + 0.0, + 1.0 + ], + [ + -1.0, + 0.0 + ] + ] + }, + "eval_init": [ + [ + -1.054374532730682, + 0.6172335752160634, + 0.06295880097801176, + 0.24759229883505074 + ], + [ + -1.161917138072713, + 0.6942318065741833, + -0.13188330479230415, + 0.015717385753870272 + ], + [ + -1.1850251698013174, + -0.31204940266413583, + 0.30661296637720437, + 0.09898120081781869 + ], + [ + -0.3785314504688708, + -0.811094521993782, + 0.41343400007824527, + 0.06580994784590322 + ], + [ + 1.353686495017974, + -0.930544229571102, + 0.15144666810276608, + -0.3545760832024687 + ], + [ + -0.6422651250014255, + -1.472723181230272, + -0.41719212077224754, + 0.4226986276360134 + ], + [ + 0.6073458666816709, + 0.4964300084820765, + -0.42824183538793215, + -0.022551009593869464 + ], + [ + 0.8640285913126062, + -0.8347848987863831, + -0.20499596573135104, + -0.4706472869456002 + ], + [ + 1.146857701059679, + -1.0923458197436349, + -0.3379244411017388, + 0.2273650663385779 + ], + [ + -0.06171828444395899, + -1.0235820098249355, + 0.08251837112441285, + 0.3623660631925758 + ], + [ + 1.2227587659335342, + -1.3309109137942257, + -0.12832014069862108, + -0.3364067129024235 + ], + [ + -0.06092354255292376, + -0.895907712584884, + -0.3356593348991834, + 0.3994216026206254 + ], + [ + -1.0830406436056892, + 0.06341553455974314, + 0.0996129753972963, + -0.32667375700852996 + ], + [ + 0.7387025793702859, + -1.4638863121180945, + -0.440605090985867, + -0.3789505945952074 + ], + [ + 0.7913534162146636, + -1.23046460709315, + -0.0776383253556926, + -0.26457355455169707 + ], + [ + 1.3433881131618381, + 0.5800279627183791, + 0.24363763864518218, + 0.007664947316886939 + ], + [ + -0.8189816831925906, + -0.46599686959892805, + 0.011990072656397732, + 0.1033370999276767 + ], + [ + -0.5304647214454828, + 0.7551349519912911, + -0.4459657318459238, + -0.3917248906046391 + ], + [ + 0.2980648321464332, + 0.566824480579081, + -0.2640014470518294, + -0.43694589548856544 + ], + [ + -1.2471932388133502, + -1.462118402636355, + -0.4561737181181854, + 0.4474956513006074 + ], + [ + -0.8489281645135708, + -0.4944909313873993, + -0.07194244400389416, + -0.42497700334588207 + ], + [ + -0.4625083751171686, + -0.4780112326042212, + 0.027671689846367697, + 0.4297223442053445 + ], + [ + -1.4152598467693296, + -1.3546882513985423, + -0.20059584345133874, + -0.09958329818834144 + ], + [ + -0.6820408180695049, + 0.8878063368069338, + -0.010544788613086276, + 0.02651430827499157 + ], + [ + 0.14532457069480031, + -0.1407232687389839, + 0.34838017691649426, + -0.21706895796871017 + ], + [ + -1.4906739252552148, + 0.7023040529310434, + 0.09295446106050764, + -0.00459186276134127 + ], + [ + 0.29349835805584634, + -0.900626920809547, + -0.08783266060602635, + -0.1364763091513549 + ], + [ + 1.2276993255236368, + -0.8646439138562431, + -0.21003718357449774, + -0.007752991531712605 + ], + [ + 1.310991496036149, + 1.0814879183158785, + 0.18610901819115766, + 0.49502035410139 + ], + [ + -1.2353198151474813, + -0.9665263908327826, + 0.15052752418169657, + 0.10659449315020564 + ], + [ + -0.6223684497185147, + 0.8609986122351088, + -0.24363233803706008, + -0.4179978057069105 + ], + [ + -0.3079775677706249, + 0.9407951016252905, + 0.37003126197998437, + 0.43796375066406923 + ] + ], + "r_rand": -326.8313553012158, + "r_ref": -26.976107954886857 + }, + { + "name": "env1", + "spec": { + "family": "pendulum_balance", + "params": { + "mass": 0.8871263299204162, + "length": 0.9089845954928153, + "gravity": 11.242973953517195, + "damping": 0.11067469518762682, + "ctrl_cost": 0.01723906176219982, + "torque_frac": 0.7429828719789657 + }, + "q_rot": [ + [ + -0.5771919615068266, + -0.43318027297408135, + 0.022257732245839098, + 0.3844723615055009, + 0.4377935093908616, + -0.34185086024089983, + -0.030872024429345914, + 0.1463271603875477 + ], + [ + 0.32525723766057296, + -0.04985462356372951, + 0.17515673746031923, + -0.4077833660302053, + 0.07607148083232092, + -0.767060026645246, + 0.23712140858923028, + 0.2106194969267954 + ], + [ + -0.10257396004098411, + -0.3629111382495501, + 0.497803912478994, + -0.36281410365969846, + 0.021787039153666712, + 0.03375580476756905, + -0.2552055723296356, + -0.6415506728103836 + ], + [ + 0.035142958177143455, + 0.37817547322029343, + -0.3124518994726311, + -0.06121160331736757, + 0.24778126084373983, + -0.2965568480476642, + -0.7669909580603415, + -0.12945496122138 + ], + [ + -0.05988767254019586, + 0.6382966440549609, + 0.49293161861971707, + 0.17778774335704012, + 0.4697758593554903, + 0.03576398409502591, + 0.2611820445367854, + -0.15561592965662624 + ], + [ + -0.5988705662323661, + 0.2730739030147406, + 0.294369627650481, + -0.34575045865301884, + -0.384029977907369, + 0.001699738539243487, + -0.18148459920445592, + 0.4244634946139978 + ], + [ + -0.28814412940853484, + 0.030762542472220746, + -0.4652846885754243, + -0.610377624321608, + 0.42368104373496196, + 0.20869868495650823, + 0.31082566057394195, + -0.0854551448344248 + ], + [ + 0.3225541759131743, + -0.22849483247014135, + 0.27796562048788326, + -0.16370732974773528, + 0.4393241808206601, + 0.40104163577370944, + -0.3027375602627309, + 0.5423963304424542 + ] + ], + "a_perm": [ + [ + 0.0, + 1.0 + ], + [ + -1.0, + 0.0 + ] + ] + }, + "eval_init": [ + [ + -0.055057583757106676, + -0.05656053265562255 + ], + [ + -0.15318031837593787, + 0.48503129437656 + ], + [ + -0.26084455247664373, + 0.5121427815603934 + ], + [ + 0.15658585756175203, + 0.4516593429069642 + ], + [ + 0.09044529599426737, + -0.1303424144733425 + ], + [ + -0.03644120813911789, + -0.3483888118123355 + ], + [ + 0.23744948949256117, + -0.37890174723047515 + ], + [ + 0.28171661722394514, + 0.15819212925711823 + ], + [ + 0.19114149578034523, + -0.06666899716631536 + ], + [ + -0.24745155069626898, + -0.010549106894509386 + ], + [ + 0.030543181622079196, + 0.5687465609712667 + ], + [ + -0.1771906530301729, + 0.29449291384588117 + ], + [ + 0.19864636903372923, + 0.12759380779221752 + ], + [ + -0.004179144788901246, + 0.1746928495979686 + ], + [ + 0.05252919408872614, + -0.1826814247219003 + ], + [ + -0.053118959990550885, + 0.5096215977242271 + ], + [ + -0.003915172958506852, + -0.6245691403874525 + ], + [ + -0.19036195975861636, + -0.17359511093575575 + ], + [ + 0.2795316581581577, + 0.3596518891463687 + ], + [ + -0.037066036956395876, + 0.6855328860879444 + ], + [ + -0.03840061618801005, + -0.399561835296937 + ], + [ + -0.1488736977690363, + -0.024825409128754417 + ], + [ + -0.2325197143065607, + 0.2671227468099757 + ], + [ + -0.25730857106883087, + 0.03156278913351884 + ], + [ + -0.04708129121902649, + 0.5429431014176642 + ], + [ + -0.2480256545506456, + -0.11575597672961369 + ], + [ + -0.15747659236703523, + -0.375506683496813 + ], + [ + 0.34149968197150615, + 0.5755864951002538 + ], + [ + -0.08680370255302988, + 0.6359353156480274 + ], + [ + 0.03806668943379715, + 0.004633464362952422 + ], + [ + -0.18878683716390146, + 0.5172190553261877 + ], + [ + 0.0008143097501605578, + 0.3291357695439905 + ] + ], + "r_rand": -447.2507961750398, + "r_ref": -0.2951849073250041 + }, + { + "name": "env2", + "spec": { + "family": "pendulum_swingup", + "params": { + "mass": 0.7570762299375084, + "length": 0.8446169021254499, + "gravity": 9.18819315250673, + "damping": 0.024969621996953142, + "ctrl_cost": 0.03855337027159401, + "torque_frac": 0.38720860953977687 + }, + "q_rot": [ + [ + -0.7367268823464612, + 0.27796079628320736, + -0.14056502170566415, + 0.04472066207327548, + -0.03850823796440468, + -0.2264722846028188, + -0.45440192387995987, + -0.3145777250603272 + ], + [ + -0.5675686439872069, + -0.5854925206593645, + 0.2540207656015544, + -0.25761030204790347, + 0.11214457533786533, + -0.04778197905304908, + 0.43095947094081183, + 0.05990940362692653 + ], + [ + 0.2970514089730893, + -0.2638853904084533, + 0.12193241346302373, + -0.19558522352149793, + 0.6368586844724584, + -0.28290495740389204, + -0.28789309929055273, + -0.46957132846075705 + ], + [ + -0.026701352475911322, + -0.48718537375653787, + -0.8101318461364867, + 0.13089034483985318, + 0.0672985477565388, + 0.2581624889614538, + -0.13132527599986638, + 0.00826229529241102 + ], + [ + 0.11738199005590173, + 0.04533765484667712, + -0.2101269533972803, + -0.889039397994644, + -0.3669844972501832, + -0.06415032175124832, + -0.09823420570187018, + -0.034332689381728676 + ], + [ + 0.1710195847652456, + -0.4073218916357284, + 0.14285367974924987, + 0.2814384739400542, + -0.6572878428285235, + -0.282157127026429, + -0.04349734090599994, + -0.4378292115214929 + ], + [ + -0.017139530522772884, + -0.3181524250492591, + 0.3746714432478978, + -0.026914028443078043, + -0.08884278381155931, + 0.23806871503761393, + -0.7039641378837886, + 0.4441249316067757 + ], + [ + -0.05316803479859337, + 0.06134838539684812, + 0.19898392646460128, + -0.0769941679794356, + -0.03499516431602996, + 0.8119972167204921, + 0.023591862639688693, + -0.5355054745944232 + ] + ], + "a_perm": [ + [ + 1.0, + 0.0 + ], + [ + 0.0, + -1.0 + ] + ] + }, + "eval_init": [ + [ + 3.2421982828323523, + 0.23004133744415667 + ], + [ + 2.7697626722087283, + -0.34991360415330997 + ], + [ + 2.732899022903412, + -0.18721607828382136 + ], + [ + 3.2703104133984, + -0.2585503416266647 + ], + [ + 3.494287948322025, + -0.08920591393243116 + ], + [ + 3.6073146866921686, + 0.34487307284486624 + ], + [ + 3.536092292189208, + -0.3826328205922638 + ], + [ + 3.5502755260700547, + -0.2505912210491015 + ], + [ + 3.123582601400414, + 0.14096418893140372 + ], + [ + 3.0584165942664407, + 0.49163459431292333 + ], + [ + 3.180580551090248, + -0.3875777848854657 + ], + [ + 3.3512015928908894, + 0.43796337153352205 + ], + [ + 2.8297442599198597, + -0.27355753389038273 + ], + [ + 3.6649884387784173, + 0.064931695850867 + ], + [ + 2.8935354266552618, + -0.13254922108174938 + ], + [ + 3.2971329916314374, + -0.15397534918403044 + ], + [ + 2.581437258602291, + -0.40056154661680243 + ], + [ + 3.2145169012007218, + 0.1039039168881345 + ], + [ + 3.7224477828652165, + -0.12037869042447225 + ], + [ + 3.1765973568068544, + 0.040830809901209464 + ], + [ + 3.3562861638916446, + -0.014066388377210859 + ], + [ + 3.0882391915631633, + -0.10549977095571716 + ], + [ + 3.4702080473416625, + 0.390950748126244 + ], + [ + 3.535407177791133, + 0.46132458481455973 + ], + [ + 2.6211777884439647, + 0.26686152195865775 + ], + [ + 2.694993455884459, + 0.2843675967904423 + ], + [ + 2.596175888564588, + -0.36575878190927347 + ], + [ + 3.191140574139402, + 0.026467295165510718 + ], + [ + 3.090888342554864, + 0.18093571193370983 + ], + [ + 3.265396671453933, + 0.32122440462578294 + ], + [ + 3.106192668713641, + -0.36916386901583176 + ], + [ + 2.821736034102919, + -0.3663080613927755 + ] + ], + "r_rand": -862.5093513019383, + "r_ref": -384.75089956215726 + }, + { + "name": "env3", + "spec": { + "family": "cartpole_swingup", + "params": { + "cart_mass": 1.0902149102036889, + "pole_mass": 0.08867088920566205, + "length": 0.8341894630829016, + "gravity": 10.143827432550612, + "ctrl_cost": 0.010540811268299682, + "force_frac": 1.014351790913103 + }, + "q_rot": [ + [ + 0.016964612139340973, + 0.5873207548366175, + 0.5407175083465724, + -0.24272518129483156, + -0.06720764714607015, + -0.0745929757939565, + -0.40457803620403326, + -0.3601544504161408 + ], + [ + 0.325819985608281, + -0.12631133029482985, + 0.26281705284390966, + -0.3828891379246509, + 0.7227742001262725, + 0.20963793205606496, + -0.02234869399726566, + 0.3088038512759022 + ], + [ + 0.05000412587546306, + 0.39870505685342283, + 0.21169540202115578, + 0.08646567266604693, + 0.10917997147680725, + -0.16453224081584428, + 0.8633164496974651, + -0.04400218733941735 + ], + [ + 0.4801961214104228, + -0.035788826058899534, + -0.3591899437801952, + -0.32652291822840684, + -0.11344334997396262, + 0.37169124418469235, + 0.16433439920666476, + -0.5953710134453999 + ], + [ + -0.3431564439424652, + -0.44010302840051335, + 0.18189879588930377, + -0.6681043049215122, + -0.1819112081687688, + -0.3500634782311613, + 0.19542980597194773, + -0.12358604153329818 + ], + [ + -0.0628493251789879, + 0.2357892021543939, + 0.05124530058722064, + -0.32064946017208285, + -0.5000889215539533, + 0.533304777473242, + 0.1065840410154144, + 0.5377250081547831 + ], + [ + -0.4300665051422076, + -0.2835700378996475, + 0.40419538418644163, + 0.26592806526638657, + 0.10704267606605598, + 0.6057621644109025, + 0.11521673065997488, + -0.329936904439734 + ], + [ + -0.5948119280504331, + 0.38620464328101345, + -0.5153952391867028, + -0.24594652119331425, + 0.39198491852892137, + 0.10656623215234333, + -0.025849555734495887, + -0.072429705043969 + ] + ], + "a_perm": [ + [ + -1.0, + 0.0 + ], + [ + 0.0, + -1.0 + ] + ] + }, + "eval_init": [ + [ + -0.09038071378771964, + 0.04068162680815007, + 2.9919459282547995, + -0.25622692165632077 + ], + [ + 0.27569283968661457, + 0.14750731486831664, + 3.676731871505362, + -0.04546001656749599 + ], + [ + -0.0980457264085478, + -0.1532112447776297, + 3.2926645144369266, + -0.1466653771917832 + ], + [ + 0.1928931351887807, + -0.13695383959190888, + 3.6581774170354695, + -0.2741866052962451 + ], + [ + -0.12696139888055627, + -0.08158721972647043, + 2.582856452980264, + 0.22332242584752243 + ], + [ + 0.26319933403641066, + 0.06998755822577707, + 3.25984643601049, + -0.2816485218711176 + ], + [ + 0.1783880213651921, + -0.10031796285389918, + 3.453525454407892, + -0.2756834570723297 + ], + [ + 0.09012325928489257, + 0.13543320165983475, + 3.459152356370974, + -0.1348483699856408 + ], + [ + 0.04570535549476107, + 0.08520391458557758, + 3.621543116160693, + -0.061604017248391624 + ], + [ + -0.11155377261585323, + -0.02807240250892659, + 2.6083308340176456, + -0.2196594492200456 + ], + [ + -0.15261635407594018, + 0.01282605902347106, + 3.2621915277338065, + 0.0975401686473682 + ], + [ + 0.028409883672931957, + 0.05569052223444737, + 2.91604896766412, + -0.1793595468669291 + ], + [ + -0.07576863672096432, + 0.09400658433689713, + 2.9834550742610615, + 0.21715878905588687 + ], + [ + -0.2160468299202445, + -0.17730406039701785, + 2.6924484884567477, + 0.22776635197162115 + ], + [ + -0.10264185404537599, + 0.07973863629456707, + 2.817912028598323, + -0.21679904490895657 + ], + [ + -0.2109490472720426, + -0.18212165970510807, + 3.3253664187958565, + -0.26505895255139694 + ], + [ + 0.16034791996643366, + 0.1801625495248157, + 3.1667022243077967, + 0.05171354150252261 + ], + [ + 0.17577292794701493, + -0.12921103044808105, + 2.736541957024075, + -0.11859025996070088 + ], + [ + -0.03982709263406886, + -0.05471601635701484, + 2.704233154319306, + 0.18412012122762483 + ], + [ + -0.28137142289811706, + 0.1646606113287386, + 3.143582897710848, + 0.05385300200637122 + ], + [ + 0.0810403526276674, + -0.08842647862019115, + 2.8838824384375905, + -0.10185080633463217 + ], + [ + 0.08559089817389642, + 0.1642910806380185, + 2.8600553149136365, + 0.2298418201143118 + ], + [ + -0.09623454802467427, + 0.08921159459194589, + 3.3889533088441164, + -0.17784357338588186 + ], + [ + -0.1322407375764428, + 0.07969025312532613, + 3.2632613267949786, + -0.28783767138826016 + ], + [ + 0.04860026084742908, + 0.17735068853851788, + 2.825056178375992, + 0.011963293123890606 + ], + [ + 0.03651007395405392, + -0.07938405911723852, + 2.7580690713460174, + -0.23656720310653723 + ], + [ + -0.10200522927574576, + -0.15040521509187613, + 3.254450408802335, + 0.12889413125347066 + ], + [ + 0.12989966031020694, + 0.18006531122218766, + 2.974374592127556, + 0.013307390933049057 + ], + [ + -0.2140875006219079, + -0.040307162322276435, + 3.541404274598602, + -0.0324391111244261 + ], + [ + 0.12143195995019951, + -0.050010003822192645, + 2.901254103358225, + -0.06194613750361416 + ], + [ + -0.2819797501294853, + 0.03272092377190389, + 3.673520000281672, + 0.1469927920718863 + ], + [ + -0.01119960446058954, + -0.19386964749505806, + 3.316037361569065, + -0.20178581519352712 + ] + ], + "r_rand": -808.3928492856212, + "r_ref": -215.84911968400775 + }, + { + "name": "env4", + "spec": { + "family": "reacher2", + "params": { + "l1": 0.9022205463328637, + "l2": 0.9928331982930164, + "damping": 0.6581695882554542, + "ctrl_cost": 0.09395623924347146, + "torque": 1.9632176428283898 + }, + "q_rot": [ + [ + 0.45993759496839437, + -0.15764050636616542, + -0.29591740315176857, + 0.34684363024272935, + -0.16105451548092845, + -0.41237012207910195, + -0.5585358753626624, + -0.21860756517513613 + ], + [ + 0.3803164294268134, + -0.05017659835788612, + -0.03589236915361257, + -0.5607574245695677, + -0.2152466119101254, + -0.1283575809369414, + 0.3798185210553545, + -0.5744873276691745 + ], + [ + -0.2803021145611697, + -0.2746351566239378, + 0.5361223212343498, + -0.305442230714256, + -0.3201768983935762, + -0.5252585635195093, + -0.22254199517925088, + 0.19325995771344637 + ], + [ + -0.12942751117515236, + -0.09484220984536745, + -0.6910496952772488, + -0.49908629990703113, + -0.216938994800597, + 0.05735472690145951, + -0.16482587843779942, + 0.41242817086028083 + ], + [ + 0.42647541167864844, + 0.39711459487460044, + 0.2594292331390227, + -0.42948118543311165, + 0.4413017409143896, + 0.05865341708160397, + -0.4134312550963761, + 0.19886742710407035 + ], + [ + 0.5484739043251659, + -0.4926210992745861, + 0.2258625946292817, + 0.08139377079534231, + -0.2419614873698914, + 0.38607044545927793, + 0.14478057163794236, + 0.41268002992108377 + ], + [ + -0.23461442836480487, + -0.1370866304452838, + 0.14126216413950785, + -0.12160723718522229, + -0.22954175596031784, + 0.6149999206024575, + -0.5239373379923633, + -0.43127178482960715 + ], + [ + 0.10366887516108154, + 0.6848678504265491, + 0.08885587207843289, + 0.13038850099000424, + -0.6871481352232017, + 0.05977939486529073, + 0.02618981516040512, + 0.13740532148499526 + ] + ], + "a_perm": [ + [ + 0.0, + -1.0 + ], + [ + -1.0, + 0.0 + ] + ] + }, + "eval_init": [ + [ + 1.9889849032498912, + -1.3381531052929412, + 0.15089109200984419, + 0.1978844905411663, + 0.7027666016692433, + 0.9494093263743589 + ], + [ + 1.6716906290409126, + -0.4834248886080168, + 0.42925351703111425, + 0.126633575653463, + 1.2831018384160349, + 0.018372395851841767 + ], + [ + -1.6548606690249852, + 0.40412589866979154, + 0.06320890584595185, + 0.37705169382244674, + 0.3378320830070317, + 0.6924389360044608 + ], + [ + 1.2435599526700187, + 0.3990339148308175, + 0.09362234032717498, + -0.10532209463543396, + -0.08328604973621334, + 0.6827128078523109 + ], + [ + -0.7216273466200196, + -0.8420910558186514, + 0.19665239124225775, + 0.13923186409705102, + -1.179452282884972, + -0.3155822805314627 + ], + [ + -1.588678045156288, + 0.4125882977625013, + -0.23833873556030793, + 0.285970878063049, + 0.8417548641488161, + 0.576268235955039 + ], + [ + 1.2754503478956503, + -0.8835591324558707, + 0.137352453167355, + 0.451682499077636, + -1.2442273428865813, + -0.0032863980565035946 + ], + [ + -2.6436676361460814, + -0.5580713647234057, + 0.23842592909578608, + 0.4308811635119907, + -0.10035073168401779, + 0.8007342044710324 + ], + [ + 1.099229124382659, + 0.6979425443670313, + -0.3326082928392271, + 0.015071043005467022, + -1.1131781499631517, + 0.11202407764118993 + ], + [ + 0.34043619028850625, + 1.4153908972805556, + -0.2632694544516424, + -0.49946956249853514, + 0.5964426310423512, + -1.108659909832426 + ], + [ + 0.9454352596613553, + 0.24183993636208, + 0.11018387245506522, + 0.38242767938807, + 0.8787246599650252, + 0.9189495384144385 + ], + [ + -1.0982241554920522, + 0.880133078876483, + -0.1907189450723088, + -0.2728865208264899, + -0.6402564290867567, + -0.22191633127391144 + ], + [ + 3.062987489964515, + 0.8041210700160288, + 0.40873043781401286, + -0.08736593379430901, + 0.5408534282238925, + -0.3647573620648756 + ], + [ + 2.2946927153571037, + 1.1006887383682344, + 0.014392183848833784, + -0.21283227069436916, + -0.6747207536156674, + -0.20590739578382586 + ], + [ + 1.3467693796944236, + 1.0931404771620206, + 0.01380050581113279, + 0.22833672198064892, + -0.697537081396152, + 1.1886148106606493 + ], + [ + 1.1763860031272761, + 1.0149938128019897, + -0.12659149925688318, + 0.04286789442538852, + -0.33314137535894917, + -0.7507957674626984 + ], + [ + -1.7979846717877963, + -1.2848106561985801, + 0.30713672928539015, + 0.43801174976901514, + -0.6814633621432036, + 0.43683605159078615 + ], + [ + 2.022367202817483, + 1.5244914898256208, + -0.1251402190411487, + 0.43811034275285854, + 0.024746585189532263, + 0.5504460894205239 + ], + [ + 0.26123866267762974, + 0.02118520013088565, + 0.05211858574484807, + -0.1828500733983489, + -0.7254844216640802, + 0.5299624092773327 + ], + [ + -2.3506111011039015, + 1.7737775871971206, + 0.26432201403172684, + -0.036584341346367566, + -0.7323123892337032, + -0.636314002678775 + ], + [ + -0.3381772617369365, + -1.7738410184810158, + 0.10959774670428923, + 0.29823618045384537, + 0.2998577859038557, + -1.2323272250039798 + ], + [ + -0.6822355383965575, + 1.0952675419312476, + 0.4224502129130333, + -0.2519488347810497, + 0.18322984919796007, + 0.9328786688287857 + ], + [ + 2.871161908170648, + -0.6167813192595011, + 0.323141556826151, + 0.3024214569431388, + -0.07570620563965767, + 0.5884600317048464 + ], + [ + -2.5982844403441305, + -1.2496811823238847, + -0.4331340120205067, + 0.14498996606357384, + -1.1773625117726993, + 0.5737139618452062 + ], + [ + -2.790810392417177, + 1.7321078861392198, + 0.0282538513413344, + 0.04861819638358622, + 0.29007314922985444, + 0.8157052044535001 + ], + [ + 2.765886340584787, + -0.2893299521064039, + 0.34354783976329173, + 0.46256146514991003, + 0.863864640187762, + 0.24591761627637326 + ], + [ + -0.5271157824756241, + -1.7811068440479385, + -0.4086240345905502, + 0.05567793978538471, + -0.3471321682266121, + -0.3727978037609861 + ], + [ + 1.250070672756272, + -1.7962432551835734, + 0.12565519027791971, + -0.4123213916521643, + -1.322423465981295, + -0.39097975703158355 + ], + [ + -0.3642731396014849, + -0.4434042720820228, + 0.3248887755474551, + 0.34844961277408226, + 0.8843153608105677, + 0.3652723407460983 + ], + [ + -1.8938424259250037, + 0.2222058367898172, + -0.4432359167816535, + 0.1600168568206305, + 0.725963418635073, + 1.1722739831544 + ], + [ + -2.05884976306496, + 0.16884952691065358, + -0.3796223857822312, + -0.024176948024017597, + -0.8027337019758805, + 0.926678482682401 + ], + [ + 2.430770006761189, + -1.8940028563747893, + -0.1967030118808607, + 0.034707280729925793, + 1.3056716617158965, + -0.1593594093549023 + ] + ], + "r_rand": -421.800493725681, + "r_ref": -111.6716779541736 + }, + { + "name": "env5", + "spec": { + "family": "delayed_pendulum", + "params": { + "mass": 0.7935115651298014, + "length": 0.9168861139062521, + "gravity": 11.117192513653004, + "damping": 0.13501986470515967, + "ctrl_cost": 0.026939883021298468, + "torque_frac": 0.27891996422572446, + "delay": 1.0 + }, + "q_rot": [ + [ + 0.4698144296459885, + 0.10213038445678488, + 0.11096730716776612, + 0.00832940060214007, + -0.6955578791632813, + -0.04147731740916445, + -0.4529232950903383, + -0.2565151491268994 + ], + [ + -0.19837302304600193, + 0.24308301361353926, + 0.10892524998946569, + -0.7550576326952524, + 0.12233089229969607, + 0.0891147140897557, + -0.4799926179030448, + 0.2574545799242404 + ], + [ + 0.04478182926330423, + 0.3956680856274861, + 0.3482912564861584, + 0.06300598177681574, + -0.35870064583821937, + 0.2979257254563763, + 0.427285457061041, + 0.5622864462798466 + ], + [ + 0.08108803357178085, + 0.7672893983193437, + -0.09803804666054075, + 0.14413064710266396, + 0.3063900632595362, + 0.27900958602457315, + -0.0054212757737080106, + -0.4500622155015385 + ], + [ + -0.13844012733462052, + -0.09955924932953368, + -0.46214411155910423, + -0.47565741342653184, + -0.37612116903688414, + 0.3071647936254944, + 0.4411485190796967, + -0.3172786978245886 + ], + [ + 0.7277567919568757, + -0.25885794692751174, + -0.15072182619460459, + -0.11386713474204214, + 0.33151846222749765, + 0.4661804148919893, + -0.008116087046913866, + 0.2009608939863823 + ], + [ + -0.22616645142973762, + 0.0883787282178627, + -0.6710366293267173, + 0.3583550106725001, + -0.16174147838908404, + 0.21071635515645368, + -0.36756451949009966, + 0.39580816177048245 + ], + [ + -0.36248445919127326, + -0.31695977329922415, + 0.39789305356916366, + 0.19349724086996326, + -0.03407983138537913, + 0.6838540347827511, + -0.22821866867779314, + -0.226891864382715 + ] + ], + "a_perm": [ + [ + 0.0, + 1.0 + ], + [ + -1.0, + 0.0 + ] + ] + }, + "eval_init": [ + [ + 3.6286067026099547, + 0.4555936590723749 + ], + [ + 3.682732927247236, + 0.06339380128861516 + ], + [ + 3.100291928224951, + -0.1268268126118962 + ], + [ + 2.7304472625449545, + -0.3909733472004645 + ], + [ + 3.0300043602293245, + 0.340955401638378 + ], + [ + 2.555708937335678, + 0.42784327181074444 + ], + [ + 2.5742796031374913, + 0.09428280664907651 + ], + [ + 3.2201982622038687, + 0.19242315206822225 + ], + [ + 3.676052352262008, + 0.4612518110963554 + ], + [ + 3.539207406786433, + -0.44699960323988386 + ], + [ + 3.5214134759887457, + -0.19864484724855125 + ], + [ + 2.987712977312655, + -0.3868802106383371 + ], + [ + 3.289668964075821, + 0.04607071937342355 + ], + [ + 2.8811761472400046, + 0.3204561693356406 + ], + [ + 3.4583618723654523, + -0.2745300293966313 + ], + [ + 2.6440142400917153, + 0.4472416205487527 + ], + [ + 2.727805259794832, + 0.16904270834239477 + ], + [ + 3.0017168502212312, + 0.2277246198250218 + ], + [ + 3.2373549344180503, + -0.4789470759325638 + ], + [ + 2.613917945624543, + 0.27703618507901606 + ], + [ + 3.0632864909957656, + 0.27840632436579227 + ], + [ + 2.556910688755685, + 0.1766080837652544 + ], + [ + 3.2044562035472777, + 0.20838027999617603 + ], + [ + 3.333784880978314, + 0.46106520852290434 + ], + [ + 3.529007770267463, + 0.23234266239444967 + ], + [ + 2.6059074032431395, + -0.23045228562958253 + ], + [ + 3.2843917701329333, + -0.24292326321378854 + ], + [ + 3.3491150279637405, + -0.2875162207144448 + ], + [ + 3.403576281413395, + -0.4244501877929444 + ], + [ + 3.3671175849704267, + 0.32431398895442787 + ], + [ + 2.747050480368633, + 0.27573786575312775 + ], + [ + 2.8396334765887628, + 0.054087920614868445 + ] + ], + "r_rand": -879.2228497695178, + "r_ref": -570.4917618040103 + } + ], + "run_seeds": [ + 2000, + 2001, + 2002, + 2003, + 2004, + 2005, + 2006, + 2007, + 2008, + 2009, + 2010, + 2011 + ] +} \ No newline at end of file diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/intermediate.sh b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..57630274676e76d4fc61cd7f6016ab87d92ed433 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +write_floor_reward_if_missing() { + [ -s /logs/verifier/reward.txt ] || printf '0\n' > /logs/verifier/reward.txt +} +trap write_floor_reward_if_missing EXIT + +chmod -R go-rwx /tests + +cd /tests +export GRADE_SPLIT=intermediate +/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +/usr/local/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/panel.py b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/panel.py new file mode 100644 index 0000000000000000000000000000000000000000..f2660d026ff84784ac9ad83f2907f2dce51ba082 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/panel.py @@ -0,0 +1,532 @@ +from __future__ import annotations + +import ctypes +import json +import os +import select +import shutil +import signal +import struct +import subprocess +import sys +import tempfile +import time +from dataclasses import dataclass +from typing import Any + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import envs as envs_mod + +N_ENVS = 64 +N_EVAL_STATES = 32 +TOTAL_ENV_STEPS = 400_000 +N_CHECKPOINTS = 40 +CPU_SECONDS = 45.0 +WALL_SECONDS = 150.0 + +_HDR = struct.Struct(" None: + """Unguarded write, used only for the handshake before any limit can bite.""" + buf = _HDR.pack(kind, len(payload)) + payload + while buf: + buf = buf[os.write(fd, buf) :] + + +def _stat_cpu(entry: str) -> tuple[int, float]: + """(parent pid, utime+stime+cutime+cstime in seconds) for one /proc entry.""" + with open(f"/proc/{entry}/stat", "rb") as fh: + fields = fh.read().rsplit(b")", 1)[1].split() + cpu = (int(fields[11]) + int(fields[12]) + int(fields[13]) + int(fields[14])) / _CLK + return int(fields[1]), cpu + + +def _child_cpu_seconds(pid: int) -> float: + """CPU consumed by the launched process itself, including reaped descendants.""" + try: + return _stat_cpu(str(pid))[1] + except (OSError, IndexError, ValueError): + return 0.0 + + +_PR_SET_CHILD_SUBREAPER = 36 + + +def _become_subreaper() -> None: + """Make this process the reaper for every orphan below it. + + A run's process that calls ``setsid`` or double-forks would otherwise be reparented to + init and vanish from any parent-chain walk; with this set it is reparented here instead, + so it stays inside :func:`_descendants` for both the CPU meter and the final SIGKILL. + """ + try: + ctypes.CDLL(None, use_errno=True).prctl(_PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) + except (OSError, AttributeError): + pass + + +def _descendants(root: int) -> dict[int, float]: + """{pid: cpu seconds} for every live process below ``root`` in the parent chain. + + The launched process is a privilege-dropping wrapper that forks, so reading its own + /proc entry alone would meter the wrapper and not the training procedure. Walking the + parent chain rather than matching a process-group id means a worker that leaves the + group (``os.setsid``) is still counted, and :func:`_become_subreaper` keeps double-forked + orphans in the walk too. + """ + ppid: dict[int, int] = {} + cpu: dict[int, float] = {} + try: + entries = os.listdir("/proc") + except OSError: + return {} + for entry in entries: + if not entry.isdigit(): + continue + try: + ppid[int(entry)], cpu[int(entry)] = _stat_cpu(entry) + except (OSError, IndexError, ValueError): + continue + kids: dict[int, list[int]] = {} + for pid, parent in ppid.items(): + kids.setdefault(parent, []).append(pid) + out: dict[int, float] = {} + stack = list(kids.get(root, [])) + while stack: + pid = stack.pop() + out[pid] = cpu[pid] + stack.extend(kids.get(pid, [])) + return out + + +def _subtree_cpu_seconds(root: int) -> float: + """CPU consumed by every live process below ``root``, reaped descendants included.""" + return sum(_descendants(root).values()) + + + + + + +_AUDIT_ARCH_X86_64 = 0xC000003E +_SECCOMP_DENY = ( + 29, 30, 31, 67, + 64, 65, 66, + 68, 69, 70, 71, + 240, 241, 242, 243, 244, 245, + 49, + 248, 249, 250, + 101, 310, 311, 438, + 129, 297, 424, +) + + +class _SockFilter(ctypes.Structure): + _fields_ = [("code", ctypes.c_uint16), ("jt", ctypes.c_uint8), ("jf", ctypes.c_uint8), ("k", ctypes.c_uint32)] + + +class _SockFprog(ctypes.Structure): + _fields_ = [("len", ctypes.c_uint16), ("filter", ctypes.POINTER(_SockFilter))] + + +def _install_syscall_filter() -> None: + """Refuse the cross-process IPC syscalls with EPERM; kill the process on a foreign ABI.""" + ld_w_abs, jeq_k, jge_k, ret_k = 0x20, 0x15, 0x35, 0x06 + allow, kill, eperm = 0x7FFF0000, 0x80000000, 0x00050000 | 1 + ins = [ + (ld_w_abs, 0, 0, 4), (jeq_k, 1, 0, _AUDIT_ARCH_X86_64), (ret_k, 0, 0, kill), + (ld_w_abs, 0, 0, 0), (jge_k, 0, 1, 0x40000000), (ret_k, 0, 0, kill), + ] + for nr in _SECCOMP_DENY: + ins += [(jeq_k, 0, 1, nr), (ret_k, 0, 0, eperm)] + ins.append((ret_k, 0, 0, allow)) + arr = (_SockFilter * len(ins))(*[_SockFilter(*i) for i in ins]) + prog = _SockFprog(len(ins), arr) + libc = ctypes.CDLL(None, use_errno=True) + + + if libc.prctl(38, 1, 0, 0, 0) != 0 or libc.prctl(22, 2, ctypes.byref(prog), 0, 0) != 0: + raise OSError(ctypes.get_errno(), "seccomp filter install failed") + + +def _decode_actions(payload: bytes, rows: int) -> np.ndarray: + want = rows * envs_mod.ACT_DIM * 4 + if len(payload) != want: + raise ProtocolError(f"action payload is {len(payload)} bytes, expected {want}") + a = np.frombuffer(payload, dtype=" 1.0 + 1e-4: + raise ProtocolError("action outside [-1, 1]") + return np.clip(a.astype(np.float64), -1.0, 1.0) + + +class _Session: + """One metered training run against one environment and one seed.""" + + def __init__( + self, + spec: envs_mod.EnvSpec, + run_seed: int, + budget: Budget, + eval_init: np.ndarray, + solution_dir: str, + harness_dir: str, + python_exe: str, + launcher: list[str] | None = None, + scratch_dir: str | None = None, + ): + self.spec = spec + self.budget = budget + self.train_env = envs_mod.VecEnv(spec, n_envs=N_ENVS, seed=run_seed) + self.eval_env = envs_mod.VecEnv( + spec, n_envs=eval_init.shape[0], seed=0, init_states=eval_init + ) + self.steps = 0 + self.per_ckpt = budget.total_env_steps // budget.n_checkpoints + self.next_ckpt = 1 + self.returns: list[float | None] = [None] * budget.n_checkpoints + self.policy_ready = False + self.status = "ok" + self.cpu_base = 0.0 + self._metered = False + self._cpu_seen = 0.0 + self._cpu_probe_t = 0.0 + self._group_probe_t = 0.0 + + c2p_r, c2p_w = os.pipe() + p2c_r, p2c_w = os.pipe() + cmd = list(launcher or []) + [ + python_exe, + os.path.join(harness_dir, "child_main.py"), + solution_dir, + str(p2c_r), + str(c2p_w), + ] + env = { + "PATH": "/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin", + + + + + + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", + "PYTHONHASHSEED": "0", + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONSAFEPATH": "1", + + + + + "TMPDIR": scratch_dir or solution_dir, + "HOME": scratch_dir or "/tmp", + } + _become_subreaper() + self.proc = subprocess.Popen( + cmd, + pass_fds=(p2c_r, c2p_w), + env=env, + cwd=scratch_dir or solution_dir, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + start_new_session=True, + preexec_fn=_install_syscall_filter, + ) + os.close(p2c_r) + os.close(c2p_w) + self.rx = c2p_r + self.tx = p2c_w + self.t0 = time.monotonic() + _write_blocking( + self.tx, + b"I", + json.dumps( + { + "n_envs": N_ENVS, + "obs_dim": envs_mod.OBS_DIM, + "act_dim": envs_mod.ACT_DIM, + "max_episode_steps": envs_mod.MAX_EPISODE_STEPS, + "total_env_steps": budget.total_env_steps, + "cpu_seconds": budget.cpu_seconds, + "n_checkpoints": budget.n_checkpoints, + "seed": int(run_seed), + } + ).encode(), + ) + + + + def _cpu_used(self) -> float: + """Monotone estimate of the run's CPU seconds, throttled to stay cheap.""" + now = time.monotonic() + if now - self._cpu_probe_t >= 0.05: + self._cpu_probe_t = now + seen = _child_cpu_seconds(self.proc.pid) + if now - self._group_probe_t >= 0.5: + self._group_probe_t = now + seen = max(seen, _subtree_cpu_seconds(os.getpid())) + self._cpu_seen = max(self._cpu_seen, seen) + return self._cpu_seen + + def _check_limits(self) -> None: + if time.monotonic() - self.t0 > self.budget.wall_seconds: + raise ProtocolError("wall-clock budget exhausted") + if self._cpu_used() - self.cpu_base > self.budget.cpu_seconds: + raise ProtocolError("cpu budget exhausted") + + + + def _send(self, kind: bytes, payload: bytes = b"") -> None: + buf = _HDR.pack(kind, len(payload)) + payload + while buf: + self._check_limits() + if not select.select([], [self.tx], [], 0.5)[1]: + continue + try: + buf = buf[os.write(self.tx, buf) :] + except OSError as exc: + raise ProtocolError(f"write to child failed: {exc}") from exc + + def _recv_exact(self, n: int) -> bytes: + out = bytearray() + while len(out) < n: + self._check_limits() + if not select.select([self.rx], [], [], 0.5)[0]: + continue + try: + chunk = os.read(self.rx, n - len(out)) + except OSError as exc: + raise ProtocolError(f"read from child failed: {exc}") from exc + if not chunk: + raise ProtocolError("child closed the pipe") + out += chunk + return bytes(out) + + def _recv(self) -> tuple[bytes, bytes]: + kind, length = _HDR.unpack(self._recv_exact(_HDR.size)) + if length > 1 << 22: + raise ProtocolError("oversized frame") + return kind, self._recv_exact(length) + + + + def _query_actions(self, obs: np.ndarray) -> np.ndarray: + self._send(b"Q", np.ascontiguousarray(obs, dtype=" float: + obs = self.eval_env.reset() + total = np.zeros(self.eval_env.n_envs, dtype=np.float64) + for _ in range(envs_mod.MAX_EPISODE_STEPS): + self._check_limits() + act = self._query_actions(obs) + obs, reward, _ = self.eval_env.step(act) + total += reward + return float(np.mean(total)) + + def _run_due_checkpoints(self) -> None: + while self.next_ckpt <= self.budget.n_checkpoints and self.steps >= self.next_ckpt * self.per_ckpt: + if self.policy_ready: + self.returns[self.next_ckpt - 1] = self._evaluate() + self.next_ckpt += 1 + + + + def run(self) -> dict[str, Any]: + try: + self._serve() + except ProtocolError as exc: + self.status = str(exc) + except Exception as exc: + self.status = f"harness error: {type(exc).__name__}: {exc}" + finally: + self._cpu_probe_t = 0.0 + self._group_probe_t = 0.0 + self.cpu = max(0.0, self._cpu_used() - self.cpu_base) + self._shutdown() + return { + "checkpoint_returns": self.returns, + "status": self.status, + "env_steps": self.steps, + "child_cpu_seconds": round(self.cpu, 3), + "wall_seconds": round(time.monotonic() - self.t0, 3), + } + + def _serve(self) -> None: + exhausted = False + while True: + kind, payload = self._recv() + first = not self._metered + if first: + + + + self._metered = True + self._cpu_probe_t = 0.0 + self._group_probe_t = 0.0 + self.cpu_base = self._cpu_used() + self.t0 = time.monotonic() + if kind == b"R": + if payload: + raise ProtocolError("reset takes no payload") + obs = self.train_env.reset() + self._send(b"O", np.ascontiguousarray(obs, dtype="= self.budget.total_env_steps: + exhausted = True + self._send(b"E") + continue + act = _decode_actions(payload, N_ENVS) + obs, reward, done = self.train_env.step(act) + self.steps += N_ENVS + body = ( + np.ascontiguousarray(obs, dtype=" None: + """SIGKILL every process below this one and reap what it adopted as subreaper. + + Repeats until the walk is empty, so a process forked between one snapshot and the + kill is caught on the next pass and nothing survives into, or is metered against, + the next run. + """ + deadline = time.monotonic() + 10.0 + while True: + pids = _descendants(os.getpid()) + if not pids: + return + for pid in pids: + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + try: + os.waitpid(pid, os.WNOHANG) + except ChildProcessError: + pass + if time.monotonic() > deadline: + return + time.sleep(0.01) + + def _shutdown(self) -> None: + try: + _write_blocking(self.tx, b"X") + except OSError: + pass + for fd in (self.tx, self.rx): + try: + os.close(fd) + except OSError: + pass + self._kill_subtree() + try: + self.stderr_tail = (self.proc.stderr.read() or b"")[-1500:].decode("utf-8", "replace") + except Exception: + self.stderr_tail = "" + finally: + try: + self.proc.stderr.close() + except Exception: + pass + try: + self.proc.wait(timeout=10) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def run_one( + spec: envs_mod.EnvSpec, + run_seed: int, + eval_init: np.ndarray, + solution_dir: str, + harness_dir: str, + python_exe: str = sys.executable, + budget: Budget | None = None, + launcher: list[str] | None = None, + scratch_dir: str | None = None, +) -> dict[str, Any]: + """Execute one metered training run and return its checkpoint return series. + + ``scratch_dir`` is the run's private working directory. When it is not supplied a fresh + one is created and removed here, so a run never inherits state from an earlier run. + """ + owned = scratch_dir is None + if owned: + scratch_dir = tempfile.mkdtemp(prefix="run_") + os.chmod(scratch_dir, 0o700) + session = _Session( + spec=spec, + run_seed=run_seed, + budget=budget or Budget(), + eval_init=eval_init, + solution_dir=solution_dir, + harness_dir=harness_dir, + python_exe=python_exe, + launcher=launcher, + scratch_dir=scratch_dir, + ) + try: + result = session.run() + finally: + if owned: + shutil.rmtree(scratch_dir, ignore_errors=True) + result["stderr_tail"] = getattr(session, "stderr_tail", "") + return result + + +def random_action_return(spec: envs_mod.EnvSpec, eval_init: np.ndarray, seed: int) -> float: + """Mean undiscounted return of uniform-random actions on the evaluation states.""" + env = envs_mod.VecEnv(spec, n_envs=eval_init.shape[0], seed=0, init_states=eval_init) + rng = np.random.default_rng(seed) + obs = env.reset() + total = np.zeros(env.n_envs) + for _ in range(envs_mod.MAX_EPISODE_STEPS): + obs, reward, _ = env.step(rng.uniform(-1.0, 1.0, size=(env.n_envs, envs_mod.ACT_DIM))) + total += reward + return float(np.mean(total)) diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/requirements-verifier.txt b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..a228fc89972b86b606ea7964c410bd5cd98bc770 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/requirements-verifier.txt @@ -0,0 +1,5 @@ +iniconfig==2.3.0 +packaging==26.3 +pluggy==1.6.0 +pytest==8.3.5 +pytest-json-ctrf==0.3.5 diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/requirements.txt b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..478c0b8d7225378df85e9d90edb728b7bbd17f44 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,12 @@ +--index-url https://download.pytorch.org/whl/cpu +--extra-index-url https://pypi.org/simple +filelock==3.32.3 +fsspec==2026.7.0 +Jinja2==3.1.6 +MarkupSafe==3.0.3 +mpmath==1.3.0 +networkx==3.6.1 +numpy==2.3.4 +sympy==1.14.0 +torch==2.9.1+cpu +typing_extensions==4.16.0 diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/run_panel.py b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/run_panel.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce01443fb350db92aee2d7e28bf5d9bcfb48927 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/run_panel.py @@ -0,0 +1,196 @@ +from __future__ import annotations + +import os +import shutil +import stat +import sys +import tempfile +import time +from concurrent.futures import ProcessPoolExecutor, as_completed +from typing import Any + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import numpy as np + +import envs as envs_mod +import panel as panel_mod + + + +RUN_UID_BASE = 2000 +MAX_SOLUTION_BYTES = 64 * 1024 * 1024 +MAX_SOLUTION_FILES = 2000 + + +class DeliverableError(RuntimeError): + """The submitted deliverable is missing or does not satisfy the stated contract.""" + + +def audit_solution_tree(src: str) -> None: + """Reject a submission we must not copy: symlinks, hard links, specials, or bulk.""" + if not os.path.isdir(src) or os.path.islink(src): + raise DeliverableError("/app/solution is missing or is not a real directory") + total = 0 + count = 0 + for root, dirs, files in os.walk(src, followlinks=False): + for name in dirs + files: + p = os.path.join(root, name) + st = os.lstat(p) + if stat.S_ISLNK(st.st_mode): + raise DeliverableError(f"symlink in the deliverable: {p}") + if stat.S_ISREG(st.st_mode): + if st.st_nlink > 1: + raise DeliverableError(f"hard link in the deliverable: {p}") + total += st.st_size + count += 1 + elif not stat.S_ISDIR(st.st_mode): + raise DeliverableError(f"special file in the deliverable: {p}") + if total > MAX_SOLUTION_BYTES: + raise DeliverableError(f"deliverable is {total} bytes, over the {MAX_SOLUTION_BYTES} cap") + if count > MAX_SOLUTION_FILES: + raise DeliverableError(f"deliverable holds {count} files, over the cap") + entry = os.path.join(src, "trainer.py") + if not os.path.isfile(entry) or os.path.getsize(entry) == 0: + raise DeliverableError("/app/solution/trainer.py is missing or empty") + import ast + + try: + tree = ast.parse(open(entry, "rb").read()) + except SyntaxError as exc: + raise DeliverableError(f"trainer.py does not parse: {exc}") from exc + for node in tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == "train": + if len(node.args.args) >= 4: + return + raise DeliverableError("train() must accept (env, seed, budget, report)") + raise DeliverableError("trainer.py defines no module-level function named 'train'") + + +def stage(src: str, workdir: str) -> tuple[str, str]: + """Copy the deliverable and the child-side harness into root-owned, read-only scratch.""" + audit_solution_tree(src) + sol = os.path.join(workdir, "solution") + shutil.copytree(src, sol, symlinks=True, ignore_dangling_symlinks=False) + harness = os.path.join(workdir, "harness") + os.makedirs(harness, exist_ok=True) + shutil.copy(os.path.join(os.path.dirname(os.path.abspath(__file__)), "child_main.py"), harness) + + + + + for root, dirs, files in os.walk(sol): + for name in files: + os.chmod(os.path.join(root, name), 0o444) + for name in dirs: + os.chmod(os.path.join(root, name), 0o555) + os.chmod(sol, 0o555) + if os.geteuid() == 0: + for root, dirs, files in os.walk(sol): + for name in dirs + files: + os.lchown(os.path.join(root, name), 0, 0) + os.chown(sol, 0, 0) + os.chmod(workdir, 0o755) + os.chmod(harness, 0o755) + os.chmod(os.path.join(harness, "child_main.py"), 0o644) + return sol, harness + + +def harden_shared_writable_paths() -> dict[str, str]: + """Close every world-writable path a run could use as a cross-run cache. + + Called by the root grader before any candidate code starts. Each run is handed a private + scratch directory; these are the paths that would otherwise persist between runs. + """ + out: dict[str, str] = {} + for path in ("/tmp", "/var/tmp", "/dev/shm", "/dev/mqueue", "/home/agent", "/run/lock"): + try: + os.chown(path, 0, 0) + os.chmod(path, 0o755) + out[path] = "sealed" + except OSError as exc: + out[path] = type(exc).__name__ + return out + + +def _job(args: tuple[Any, ...]) -> dict[str, Any]: + env_json, eval_init, run_seed, sol, harness, python_exe, launcher, name, uid = args + spec = envs_mod.EnvSpec.from_json(env_json) + scratch = tempfile.mkdtemp(prefix="run_") + try: + os.chmod(scratch, 0o700) + if os.geteuid() == 0: + os.chown(scratch, uid, uid) + res = panel_mod.run_one( + spec, + run_seed, + np.asarray(eval_init, dtype=np.float64), + sol, + harness, + python_exe=python_exe, + launcher=[a.format(uid=uid) for a in launcher], + scratch_dir=scratch, + ) + finally: + shutil.rmtree(scratch, ignore_errors=True) + res["env"] = name + res["seed"] = run_seed + return res + + +def execute_panel( + panel: dict[str, Any], + solution_src: str, + workdir: str | None = None, + workers: int = 8, + python_exe: str = "/usr/local/bin/python3", + launcher: tuple[str, ...] = (), + timeout: float | None = None, +) -> list[dict[str, Any]]: + """Run the whole panel. ``launcher`` may carry a ``{uid}`` placeholder, filled per run. ``timeout`` bounds the panel as a whole; each individual run is + already bounded by :mod:`panel`'s own CPU and wall meters. Runs that do not finish inside + the panel deadline are recorded with no checkpoints, which scores them as failures rather + than discarding the whole grade.""" + tmp = workdir or tempfile.mkdtemp(prefix="panel_") + try: + sol, harness = stage(solution_src, tmp) + jobs = [ + (env["spec"], env["eval_init"], seed, sol, harness, python_exe, launcher, env["name"], RUN_UID_BASE + i) + for i, (env, seed) in enumerate((e, s) for e in panel["envs"] for s in panel["run_seeds"]) + ] + out: list[dict[str, Any]] = [] + deadline = None if timeout is None else time.monotonic() + float(timeout) + ex = ProcessPoolExecutor(max_workers=workers) + try: + futures = {ex.submit(_job, j): j for j in jobs} + for fut in as_completed(futures, timeout=None): + r = fut.result() + r.pop("stderr_tail", None) + out.append(r) + if deadline is not None and time.monotonic() > deadline: + for other, job in futures.items(): + if other.done(): + continue + other.cancel() + out.append( + { + "checkpoint_returns": [None] * panel_mod.N_CHECKPOINTS, + "status": "panel deadline exceeded", + "env": job[7], + "seed": job[2], + "child_cpu_seconds": None, + } + ) + break + finally: + ex.shutdown(wait=False, cancel_futures=True) + return out + finally: + if workdir is None: + for root, dirs, files in os.walk(tmp): + for name in dirs: + try: + os.chmod(os.path.join(root, name), 0o700) + except OSError: + pass + shutil.rmtree(tmp, ignore_errors=True) diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/test.sh b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..61bda7e2dc4691a14011cb8d563eb617f3207c2e --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/test.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +write_floor_reward_if_missing() { + [ -s /logs/verifier/reward.txt ] || printf '0\n' > /logs/verifier/reward.txt +} +trap write_floor_reward_if_missing EXIT + +chmod -R go-rwx /tests + +cd /tests +export GRADE_SPLIT=final +/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +/usr/local/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/test_state.py b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c3adce27d180264bb7e540fa433dcf781f2944 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/are-grader-ctx/test_state.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import json +import os +import sys +import time +import traceback +from pathlib import Path + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import grader_core +import run_panel + +SOLUTION_SRC = os.environ.get("SOLUTION_DIR", "/app/solution") +GRADE_SPLIT = os.environ.get("GRADE_SPLIT", "final") +PANEL_PATH = f"/tests/hidden_data/{GRADE_SPLIT}/panel.json" +METRIC_PATH = Path("/logs/verifier/metric.json") +PYTHON = os.environ.get("PYTHON_BIN", "/usr/local/bin/python3") +WORKERS = 8 + + + + +PANEL_TIMEOUT_SEC = 2000.0 + +_RESULT: dict | None = None + + +def _privilege_drop() -> tuple[str, ...]: + """Resolve the tool that runs candidate code as an unprivileged, per-run uid. + + Fails closed: if the root verifier cannot drop privilege it must not run the + submission at all, because a root candidate could rewrite the reward channel. + ``{uid}`` is filled in per run by :func:`run_panel._job`; ``runuser`` is not used + because it needs a passwd entry and the per-run uids have none. + """ + if os.geteuid() != 0: + return () + for path in ("/usr/bin/setpriv", "/usr/sbin/setpriv"): + if os.path.exists(path): + return (path, "--reuid={uid}", "--regid={uid}", "--clear-groups", "--") + raise RuntimeError("no privilege-dropping tool in the verifier image") + + +def _grade() -> dict: + started = time.monotonic() + panel = grader_core.load_panel(PANEL_PATH) + launcher = _privilege_drop() + sealed_paths = run_panel.harden_shared_writable_paths() + results = run_panel.execute_panel( + panel, + SOLUTION_SRC, + workers=WORKERS, + python_exe=PYTHON, + launcher=launcher, + timeout=PANEL_TIMEOUT_SEC, + ) + scored = grader_core.score_panel(panel, results) + scored["valid"] = True + scored["reason"] = "" + scored["reward"] = grader_core.graded_reward(scored["metric"], True) + scored["grade_seconds"] = round(time.monotonic() - started, 1) + scored["sealed_shared_paths"] = sealed_paths + return scored + + +def result() -> dict: + global _RESULT + if _RESULT is None: + try: + _RESULT = _grade() + except run_panel.DeliverableError as exc: + _RESULT = {"valid": False, "reason": str(exc), "metric": 0.0, "reward": 0.0} + except Exception as exc: + _RESULT = { + "valid": False, + "reason": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc()[-2000:], + "metric": 0.0, + "reward": 0.0, + } + METRIC_PATH.parent.mkdir(parents=True, exist_ok=True) + METRIC_PATH.write_text(json.dumps(_RESULT, indent=1, sort_keys=True)) + return _RESULT + + +def test_deliverable_satisfies_the_stated_contract(): + """/app/solution/trainer.py exists, parses, and exposes train(env, seed, budget, report). + + A missing, unparseable or wrong-signature deliverable scores 0, which is the contract + instruction.md states. + """ + r = result() + assert r["valid"], r["reason"] + + +def test_every_panel_run_produced_a_checkpoint_series(): + """All 72 (environment, seed) runs completed the harness protocol. + + Runs may legitimately end early (budget exhausted, a crash inside the submitted code); + what this checks is that the harness itself produced a full record for each one, so the + metric is computed over the whole panel rather than a truncated slice. + """ + r = result() + assert r["valid"], r["reason"] + assert r["n_runs"] == 72, f"expected 72 runs, got {r['n_runs']}" + + +def test_metric_and_reward_are_recorded(): + """The raw metric and the mapped reward land in /logs/verifier/metric.json in range.""" + r = result() + assert METRIC_PATH.exists() + assert 0.0 <= float(r["reward"]) <= 1.0 + if r["valid"]: + assert 0.0 <= float(r["metric"]) <= 1.0 + + + + print( + "reliable_success_fraction=%.4f reliable=%d/%d" + % (r["metric"], r["n_reliable"], r["n_runs"]) + ) diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/environment/docker-compose.yaml b/tasks/reppo-reliable-onpolicy-control-trainer/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..90ba4120098f0a4a12d64189aa6e9521d60e97b3 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/environment/docker-compose.yaml @@ -0,0 +1,76 @@ +# ARE 1.1: grading lives in sidecars. Harbor configures `main` (build, limits, network). +services: + main: + depends_on: + grader: + condition: service_healthy + volumes: + - are-deliverable-0:/app/solution + + grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: val + platform: linux/amd64 + environment: + ARE_ROLE: val + ARE_PORT: "8000" + ARE_BUDGET_SEC: "86400" + ARE_ARTIFACT_PATHS: "/app/solution" + ARE_AGENT_UID: "1001" + ARE_GRADE_TIMEOUT_SEC: "2400" + volumes: + - are-deliverable-0:/run/are-deliverable/app/solution + - are-secret:/run/are-secret + expose: + - "8000" + cap_add: [SYS_ADMIN] + networks: [default, are-private] + cpus: 8 + mem_limit: 14336m + depends_on: + test-grader: + condition: service_healthy + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + + test-grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: test + platform: linux/amd64 + environment: + ARE_ROLE: test + ARE_PORT: "8001" + ARE_ARTIFACT_PATHS: "/app/solution" + ARE_GRADE_TIMEOUT_SEC: "2400" + expose: + - "8001" + volumes: + - are-secret:/run/are-secret + cap_add: [SYS_ADMIN] + networks: [are-private] + cpus: 8 + mem_limit: 14336m + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8001/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + +volumes: + are-deliverable-0: {} + are-secret: {} + +networks: + are-private: + internal: true diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/task.toml b/tasks/reppo-reliable-onpolicy-control-trainer/task.toml index 24b9992068bd98b3154b2a16e12cce742385cd1d..ede35b42e74b07f4a3f8a2ded551d81ae525856f 100644 --- a/tasks/reppo-reliable-onpolicy-control-trainer/task.toml +++ b/tasks/reppo-reliable-onpolicy-control-trainer/task.toml @@ -1,13 +1,20 @@ schema_version = "1.4" -artifacts = [ "/app/solution",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/reppo-reliable-onpolicy-control-trainer" -version = "1.0.0" +version = "1.1.0" description = "" -keywords = [ "autoresearch", "machine-learning", "benchmark",] -[[task.authors]] -name = "Bespoke Labs" +keywords = [ + "autoresearch", + "machine-learning", + "benchmark", +] +authors = [ + { name = "Bespoke Labs" }, +] [metadata] task_slug = "reppo-reliable-onpolicy-control-trainer" @@ -18,43 +25,45 @@ objective = "maximize" graded_deliverable = "/app/solution/trainer.py" device = "cpu" expert_time_estimate_hours = 12.0 +are_version = "1.1" +budget_seconds = 86400 [verifier] -timeout_sec = 2400.0 +timeout_sec = 600.0 environment_mode = "separate" -collect = [] -[verifier.env] +[[verifier.collect]] +service = "grader" +command = "/opt/are/venv/bin/python /opt/are/drain.py" +timeout_sec = 4800.0 [verifier.environment] network_mode = "no-network" -build_timeout_sec = 3600.0 -os = "linux" -cpus = 8 -memory_mb = 14336 -storage_mb = 153600 +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 gpus = 0 -mcp_servers = [] - -[verifier.environment.env] [agent] network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] -timeout_sec = 14400.0 +allowed_hosts = [ + "api.openai.com", + "api.anthropic.com", + "grader", +] +timeout_sec = 86400.0 user = "agent" [environment] -network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] +network_mode = "public" build_timeout_sec = 3600.0 os = "linux" cpus = 8 memory_mb = 14336 storage_mb = 153600 gpus = 0 -mcp_servers = [] +mcp_servers = [ + { name = "are", transport = "streamable-http", url = "http://grader:8000/mcp" }, +] [environment.env] - -[solution.env] diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/tests/Dockerfile b/tasks/reppo-reliable-onpolicy-control-trainer/tests/Dockerfile index eecf368ab2e270d72769fce908d380caafac46d0..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/reppo-reliable-onpolicy-control-trainer/tests/Dockerfile +++ b/tasks/reppo-reliable-onpolicy-control-trainer/tests/Dockerfile @@ -1,34 +1,2 @@ -FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb - -ENTRYPOINT [] -ENV PYTHONPATH= -ENV PYTHONSAFEPATH=1 -ENV DEBIAN_FRONTEND=noninteractive \ - PYTHONHASHSEED=0 \ - PIP_NO_CACHE_DIR=1 \ - PIP_DISABLE_PIP_VERSION_CHECK=1 \ - OMP_NUM_THREADS=1 \ - MKL_NUM_THREADS=1 \ - OPENBLAS_NUM_THREADS=1 - -RUN useradd --create-home --uid 1001 agent - -COPY ./requirements.txt /tmp/requirements.txt -COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt -RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ - -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ - && rm /tmp/requirements.txt /tmp/requirements-verifier.txt - -RUN mkdir -p /app/solution /logs/verifier - -COPY . /tests - -RUN chown -R root:root /tests \ - && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ - && chmod +x /tests/test.sh /tests/intermediate.sh \ - && find /tests -exec touch -d @1700000000 {} + - -WORKDIR /tests - -ENV HF_HUB_OFFLINE=1 -ENV TRANSFORMERS_OFFLINE=1 +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/tests/finalize.py b/tasks/reppo-reliable-onpolicy-control-trainer/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/reppo-reliable-onpolicy-control-trainer/tests/finalize.py @@ -0,0 +1,59 @@ +"""Final verifier: score the run from the grader ledger. + +reward hidden test score of the submission with the best validation score + (ties go to the earlier submission); 0 if nothing was submitted. +auarc area under the curve of that same quantity over the wall-clock budget, + using the time each validation score became available, divided by the + budget. 0 before the first graded submission. +""" + +import json +from pathlib import Path + +STATE = Path("/var/lib/are") +OUT = Path("/logs/verifier") +OUT.mkdir(parents=True, exist_ok=True) + +meta = json.loads((STATE / "meta.json").read_text()) if (STATE / "meta.json").exists() else {} +budget = float(meta.get("budget_seconds") or 1.0) + +subs: dict[int, dict] = {} +ledger = STATE / "ledger.jsonl" +for line in (ledger.read_text().splitlines() if ledger.exists() else []): + ev = json.loads(line) + s = subs.setdefault(ev["id"], {"id": ev["id"]}) + if ev["event"] == "submitted": + s["submitted_t"] = ev["t"] + elif ev["event"] == "val": + s["val"] = ev["score"] + s["val_t"] = ev["t"] + elif ev["event"] == "test": + s["test"] = ev["score"] + +graded = sorted((s for s in subs.values() if "val" in s), key=lambda s: s["val_t"]) + +# Step function of the hidden score of the best-validation pick over time. +auc, best, last_t, cur = 0.0, None, 0.0, 0.0 +timeline = [] +for s in graded: + t = min(s["val_t"], budget) + auc += cur * (t - last_t) + last_t = t + if best is None or s["val"] > best["val"] or (s["val"] == best["val"] and s["id"] < best["id"]): + best = s + cur = float(best.get("test") or 0.0) + timeline.append({"t": s["val_t"], "id": s["id"], "val": s["val"], "test": s.get("test"), + "pick": best["id"]}) +auc += cur * (budget - last_t) if last_t < budget else 0.0 + +reward = { + "reward": float(best.get("test") or 0.0) if best else 0.0, + "auarc": auc / budget, + "best_val": float(best["val"]) if best else 0.0, + "n_submissions": float(len(subs)), + "n_test_graded": float(sum(s.get("test") is not None for s in subs.values())), +} +(OUT / "reward.json").write_text(json.dumps(reward)) +(OUT / "timeline.json").write_text(json.dumps({"budget": budget, "selected": best and best["id"], + "submissions": timeline}, indent=1)) +print(json.dumps(reward, indent=1)) diff --git a/tasks/reppo-reliable-onpolicy-control-trainer/tests/test.sh b/tasks/reppo-reliable-onpolicy-control-trainer/tests/test.sh index 61bda7e2dc4691a14011cb8d563eb617f3207c2e..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/reppo-reliable-onpolicy-control-trainer/tests/test.sh +++ b/tasks/reppo-reliable-onpolicy-control-trainer/tests/test.sh @@ -1,21 +1,2 @@ #!/bin/bash -set -u - -mkdir -p /logs/verifier -chown root:root /logs/verifier 2>/dev/null || true -chmod 755 /logs/verifier 2>/dev/null || true -rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json - -write_floor_reward_if_missing() { - [ -s /logs/verifier/reward.txt ] || printf '0\n' > /logs/verifier/reward.txt -} -trap write_floor_reward_if_missing EXIT - -chmod -R go-rwx /tests - -cd /tests -export GRADE_SPLIT=final -/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA -/usr/local/bin/python3 /tests/compute_reward.py - -exit 0 +python3 /tests/finalize.py diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/.dockerignore b/tasks/sae-sparse-dict-nmse-frontier/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/Dockerfile b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9568764d237a800b5b76aaf9b7c525953f5c5b0e --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,41 @@ +FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV PYTHONHASHSEED=0 \ + PYTHONDONTWRITEBYTECODE=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 \ + NUMEXPR_NUM_THREADS=1 \ + CUBLAS_WORKSPACE_CONFIG=:4096:8 \ + TOKENIZERS_PARALLELISM=false \ + HF_HUB_DISABLE_PROGRESS_BARS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements-verifier.txt + +RUN /usr/bin/python3 -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='openai-community/gpt2', revision='607a30d783dfa663caf39e06633721c8d4cfcd7e', local_dir='/opt/assets/gpt2', allow_patterns=['config.json','generation_config.json','model.safetensors','tokenizer.json','tokenizer_config.json','vocab.json','merges.txt'])" \ + && rm -rf /opt/assets/gpt2/.cache + +RUN mkdir -p /app/output /logs/verifier + +COPY . /tests + +RUN /usr/bin/python3 /tests/prepare_hidden_data.py + +RUN chown -R root:root /tests \ + && chmod 700 /tests/hidden_data \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/Dockerfile.are b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..e1421b6d5236fd14d354a05377a3bf6a20f5ea1a --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,59 @@ +FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV PYTHONHASHSEED=0 \ + PYTHONDONTWRITEBYTECODE=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 \ + NUMEXPR_NUM_THREADS=1 \ + CUBLAS_WORKSPACE_CONFIG=:4096:8 \ + TOKENIZERS_PARALLELISM=false \ + HF_HUB_DISABLE_PROGRESS_BARS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements-verifier.txt + +RUN /usr/bin/python3 -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='openai-community/gpt2', revision='607a30d783dfa663caf39e06633721c8d4cfcd7e', local_dir='/opt/assets/gpt2', allow_patterns=['config.json','generation_config.json','model.safetensors','tokenizer.json','tokenizer_config.json','vocab.json','merges.txt'])" \ + && rm -rf /opt/assets/gpt2/.cache + +RUN mkdir -p /app/output /logs/verifier + +COPY . /tests + +RUN /usr/bin/python3 /tests/prepare_hidden_data.py + +RUN chown -R root:root /tests \ + && chmod 700 /tests/hidden_data \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 + + +# ---- ARE 1.1 grader layer (appended to the task's own verifier Dockerfile) ---- +ARG ARE_ROLE +# python.org images ship /usr/local/bin/python3; distro-python bases (kaggle GPU) lack +# ensurepip, so fall back to a pip-less venv filled by the base interpreter's pip. +RUN PY=$(command -v /usr/local/bin/python3 || command -v python3) \ + && if "$PY" -m venv /opt/are/venv; then \ + /opt/are/venv/bin/pip install --no-cache-dir "fastmcp==2.14.7"; \ + else rm -rf /opt/are/venv && "$PY" -m venv --without-pip /opt/are/venv \ + && "$PY" -m pip --python /opt/are/venv/bin/python install --no-cache-dir "fastmcp==2.14.7"; fi +COPY are/ /opt/are/ +# The val grader, whose output reaches the agent, never holds the private grader or its +# data. The test grader keeps everything; nothing from it reaches the agent. +RUN rm -rf /tests/are /tests/Dockerfile.are \ + && if [ "$ARE_ROLE" = "val" ]; then rm -rf /tests/test.sh ; fi +ENV ARE_ROLE=$ARE_ROLE +CMD ["/opt/are/venv/bin/python", "/opt/are/server.py"] diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/are/drain.py b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/are/drain.py @@ -0,0 +1,25 @@ +"""Verifier collect hook, run after the agent stops. + +Grades the final workspace as one last submission (unless it equals the last one), +then waits until every submission has both grades recorded. +""" + +import json +import time +import urllib.request +from pathlib import Path + +TOKEN = Path("/run/are-secret/token").read_text().strip() +H = {"x-are-token": TOKEN} + +req = urllib.request.Request("http://localhost:8000/final", method="POST", headers=H) +with urllib.request.urlopen(req, timeout=120) as resp: + print("final:", json.loads(resp.read()), flush=True) + +while True: + with urllib.request.urlopen(urllib.request.Request("http://localhost:8000/drain", headers=H), timeout=30) as resp: + state = json.loads(resp.read()) + print(state, flush=True) + if state["val_pending"] == 0 and state["test_pending"] == 0: + break + time.sleep(5) diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/are/server.py b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/are/server.py @@ -0,0 +1,538 @@ +"""ARE 1.1 grader sidecar. + +One image, two roles: + +- ARE_ROLE=val ("grader" service). Reachable from the agent. Serves MCP tools and a + REST fallback. On submit it snapshots the shared deliverable volume, grades the + snapshot with the task's public grader (intermediate.sh), and returns only that + score. Every snapshot is also sent to the test grader; the hidden score goes to a + root-only ledger and never back to the agent. +- ARE_ROLE=test ("test-grader" service). On a private network that only the val + grader can reach. Grades snapshots with the task's private grader (test.sh). +""" + +from __future__ import annotations + +import asyncio +import gzip +import hashlib +import io +import secrets +import json +import os +import queue +import shutil +import subprocess +import tarfile +import threading +import time +import urllib.request +from pathlib import Path + +from fastmcp import FastMCP +from starlette.requests import Request +from starlette.responses import JSONResponse, Response + +ROLE = os.environ.get("ARE_ROLE", "val") +PORT = int(os.environ.get("ARE_PORT", "8000")) +STATE = Path(os.environ.get("ARE_STATE_DIR", "/var/lib/are")) +ARTIFACT_PATHS = [p for p in os.environ.get("ARE_ARTIFACT_PATHS", "/app/output").split(":") if p] +# The shared deliverable volume. Its parent is root-only, so submitted code (which every +# task grader runs as the unprivileged agent user) cannot reach it to write back to the agent. +SUBMISSION_ROOT = Path(os.environ.get("ARE_SUBMISSION_ROOT", "/run/are-deliverable")) +AGENT_UID = int(os.environ.get("ARE_AGENT_UID", "1001")) +BUDGET_SEC = float(os.environ.get("ARE_BUDGET_SEC", "14400")) +GRADE_TIMEOUT_SEC = float(os.environ.get("ARE_GRADE_TIMEOUT_SEC", "1800")) +TEST_GRADER_URL = os.environ.get("ARE_TEST_GRADER_URL", "http://test-grader:8001") +FEEDBACK_TAIL = int(os.environ.get("ARE_FEEDBACK_TAIL_CHARS", "8192")) +SCRIPT = "/tests/intermediate.sh" if ROLE == "val" else "/tests/test.sh" +# Shared only by the two graders (a volume the agent's container never mounts). The test +# grader writes a fresh token at startup; every internal request must carry it, so the +# agent cannot reach the test grader or the internal endpoints even on a shared network. +TOKEN_FILE = Path(os.environ.get("ARE_TOKEN_FILE", "/run/are-secret/token")) +TOKEN = "" + + +def _authorized(request: Request) -> bool: + """Internal endpoints need the graders' token; an unset token never matches.""" + return bool(TOKEN) and secrets.compare_digest(request.headers.get("x-are-token", ""), TOKEN) + + +def _net_isolation_available() -> bool: + try: + return subprocess.run(["unshare", "-n", "true"], capture_output=True, timeout=10).returncode == 0 + except Exception: + return False + + +NET_ISOLATED = False # set at startup: grader scripts run in an empty network namespace + +T0 = time.time() +_lock = threading.Lock() + + +def _elapsed() -> float: + return round(time.time() - T0, 1) + + +def _ledger(event: dict) -> None: + event = {"t": _elapsed(), "wall": time.time(), **event} + for attempt in range(3): + try: + with _lock, open(STATE / "ledger.jsonl", "a") as fh: + fh.write(json.dumps(event) + "\n") + return + except OSError: + if attempt == 2: + raise + time.sleep(1) + + +def _kill_grading_processes(proc: subprocess.Popen) -> None: + """Kill everything a timed-out grade started, including processes that left its group.""" + try: + os.killpg(proc.pid, 9) + except ProcessLookupError: + pass + _kill_other_processes() + + +def _kill_other_processes() -> None: + """Kill every process run by the agent user. Every task grader runs submitted code as + that user, so this stops all graded code (detached or not) and nothing else: the grader + server, the task's own grader and Harbor's hooks run as root.""" + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + if entry.stat().st_uid == AGENT_UID: + os.kill(int(entry.name), 9) + except (ProcessLookupError, PermissionError, FileNotFoundError): + pass + + +# Places the agent user (who runs submitted code inside every task grader) can write. +_BASELINE: set[str] = set() # every path that existed when the grader started (its image) + + +def _walk_one_fs(base: Path): + """Every path under base on base's own filesystem (skips /proc, /sys and other mounts).""" + dev = base.stat().st_dev + for root, dirs, files in os.walk(base): + dirs[:] = [d for d in dirs if os.lstat(os.path.join(root, d)).st_dev == dev] + for name in dirs + files: + yield Path(root) / name + + +def _all_paths() -> set[str]: + out = set() + for base in (Path("/"), Path("/dev/shm")): + if base.is_dir(): + out.update(str(q) for q in _walk_one_fs(base)) + return out + + +def _protected(path: str) -> bool: + keep = [str(STATE), "/opt/are", str(TOKEN_FILE.parent)] + return any(path == k or path.startswith(k + "/") for k in keep) + + +def _fresh_state() -> None: + """Start every grade from the grader image's own files, as ARE 1.0's fresh verifier + container did. The grader container lives for the whole run, so before each grade + stop anything an earlier grade left running and delete every file it created, + whoever wrote it. The deliverable volume and the token are separate mounts and are + never walked; the grader's own state is kept.""" + _kill_other_processes() + # System V shared memory, semaphores and queues outlive processes; this server uses none. + subprocess.run(["ipcrm", "--all"], capture_output=True) + for path in sorted(_all_paths() - _BASELINE, key=lambda q: q.count("/"), reverse=True): + if _protected(path): + continue + try: + q = Path(path) + if q.is_dir() and not q.is_symlink(): + shutil.rmtree(q, ignore_errors=True) + else: + q.unlink() + except OSError: + pass + + +def grade_snapshot(tar_bytes: bytes, tag: str) -> dict: + """Extract a snapshot over the artifact paths and run this role's grader script.""" + _fresh_state() + for path in ARTIFACT_PATHS: + p = Path(path) + if p.exists(): + shutil.rmtree(p) + p.mkdir(parents=True) + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:gz") as tf: + tf.extractall("/", filter="tar") + logs = Path("/logs/verifier") + if logs.exists(): + shutil.rmtree(logs) + logs.mkdir(parents=True) + started = time.time() + # Submitted code runs with no network, as in ARE 1.0's verifier. + cmd = (["unshare", "-n"] if NET_ISOLATED else []) + ["bash", SCRIPT] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + cwd="/tests", start_new_session=True) + try: + out, err = proc.communicate(timeout=GRADE_TIMEOUT_SEC) + error = None + except subprocess.TimeoutExpired: + _kill_grading_processes(proc) + out, err = proc.communicate() + error = f"grader timed out after {GRADE_TIMEOUT_SEC:.0f}s" + output = (out or "") + (err or "") + # Nothing a grade started may keep running after it, not even detached processes. + _kill_other_processes() + score = 0.0 + reward_file = logs / "reward.txt" + if reward_file.exists(): + try: + score = float(reward_file.read_text().strip() or 0) + except ValueError: + error = error or "unparseable reward" + metric = None + if (logs / "metric.json").exists(): + try: + metric = json.loads((logs / "metric.json").read_text()) + except ValueError: + pass + (STATE / "logs").mkdir(exist_ok=True) + (STATE / "logs" / f"{tag}.log").write_text(output) + return { + "score": score, + "metric": metric, + "error": error, + "net_isolated": NET_ISOLATED, + "seconds": round(time.time() - started, 1), + # What the agent sees, as in ARE 1.0: the grader's stdout tail (not stderr). + "output_tail": (out or "")[-FEEDBACK_TAIL:], + } + + +mcp = FastMCP("are") + + +# ---------------------------------------------------------------- test role + + +_grade_lock = threading.Lock() + + +def _grade_one_at_a_time(tar_bytes: bytes, tag: str) -> dict: + # A request that timed out on the caller's side may still be grading; the next one + # waits for it rather than sharing /app/output and /logs/verifier with it. + with _grade_lock: + return grade_snapshot(tar_bytes, tag) + + +if ROLE == "test": + + @mcp.custom_route("/grade", methods=["POST"]) + async def http_grade(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + tag = request.query_params.get("tag", "x") + body = await request.body() + result = await asyncio.to_thread(_grade_one_at_a_time, body, f"{tag}-test") + return JSONResponse(result) + + +# ----------------------------------------------------------------- val role + + +class Board: + """Submissions and their grading state. Hidden scores are never stored here.""" + + def __init__(self) -> None: + self.subs: dict[int, dict] = {} + self.val_q: queue.Queue[int] = queue.Queue() + self.next_id = 1 + self.test_pending = 0 + self.last_digest: str | None = None + + def public(self, sid: int) -> dict: + s = self.subs[sid] + out = {k: s[k] for k in ("id", "note", "submitted_at_s", "status")} + if s["status"] == "graded": + v = s["val"] + out.update( + validation_score=v["score"], + error=v["error"], + grading_seconds=v["seconds"], + grader_output_tail=v["output_tail"], + ) + return out + + def best(self) -> dict | None: + graded = [s for s in self.subs.values() if s["status"] == "graded"] + if not graded: + return None + b = max(graded, key=lambda s: (s["val"]["score"], -s["id"])) + return {"id": b["id"], "validation_score": b["val"]["score"]} + + +board = Board() + + +def snapshot() -> bytes: + """Deterministic tar.gz of the deliverable: same content, same bytes (gzip mtime 0).""" + raw = io.BytesIO() + with tarfile.open(fileobj=raw, mode="w") as tf: + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + tf.add(str(src), arcname=path.lstrip("/")) + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as gz: + gz.write(raw.getvalue()) + return out.getvalue() + + +def do_submit(note: str, final: bool = False) -> dict: + with _lock: + pending = [s["id"] for s in board.subs.values() if s["status"] != "graded"] + if pending and not final: + return { + "error": f"Submission {pending[0]} is still being graded. One submission is " + f"graded at a time: check result({pending[0]}) and submit again " + "once it has its score.", + "pending_id": pending[0], + } + sid = board.next_id + board.next_id += 1 + board.subs[sid] = {"id": sid, "note": note[:500], "submitted_at_s": _elapsed(), + "status": "queued"} + try: + data = snapshot() + digest = hashlib.sha256(data).hexdigest() + (STATE / "snapshots" / f"{sid:04d}.tar.gz").write_bytes(data) + _ledger({"event": "submitted", "id": sid, "note": note[:500], "bytes": len(data), + "sha256": digest, "final": final}) + except Exception as exc: + with _lock: + board.subs.pop(sid, None) # release the slot; the id is not reused + return {"error": f"Could not snapshot the deliverable ({exc}). Nothing was submitted. " + "Make sure nothing is writing to it, then submit again."} + board.last_digest = digest + with _lock: + board.test_pending += 1 + board.val_q.put(sid) + return {"id": sid, "status": "queued", + "hint": "Grading has started. Check result(id) for the validation score."} + + +def final_submit() -> dict: + """After the agent stops: grade the final workspace unless it was already submitted.""" + try: + data = snapshot() + except Exception as exc: + return {"error": f"final snapshot failed: {exc}"} + if board.subs and hashlib.sha256(data).hexdigest() == board.last_digest: + return {"skipped": "final workspace equals the last submission"} + return do_submit("final workspace (automatic)", final=True) + + +def grade_worker() -> None: + """Grade each submission on val, then on test, one submission at a time. + + The val score is published as soon as it is ready. The next submission's val grade + waits until this test grade is done, so the two graders never run at the same time. + """ + while True: + sid = board.val_q.get() + board.subs[sid]["status"] = "grading" + data = b"" + try: + data = (STATE / "snapshots" / f"{sid:04d}.tar.gz").read_bytes() + res = grade_snapshot(data, f"{sid:04d}-val") + except Exception as exc: + res = {"score": 0.0, "metric": None, "error": f"grader failed: {exc}", + "net_isolated": NET_ISOLATED, "seconds": 0.0, "output_tail": ""} + board.subs[sid]["val"] = res + board.subs[sid]["status"] = "graded" + try: + _ledger({"event": "val", "id": sid, **{k: res[k] for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + test_grade(sid, data) + + +def test_grade(sid: int, data: bytes) -> None: + try: + _test_grade(sid, data) + finally: + with _lock: + board.test_pending -= 1 + + +def _test_grade(sid: int, data: bytes) -> None: + """Send one snapshot to the test grader. A failed request is retried (the same snapshot + is graded again, so a retry can only recover the honest score); a request that ran + past its timeout is not, since the grade itself already took the full time.""" + started = time.time() + for attempt in range(3): + try: + req = urllib.request.Request( + f"{TEST_GRADER_URL}/grade?tag={sid:04d}", data=data, method="POST", + headers={"x-are-token": TOKEN}, + ) + with urllib.request.urlopen(req, timeout=2 * GRADE_TIMEOUT_SEC + 300) as resp: + res = json.loads(resp.read()) + break + except Exception as exc: # recorded, never shown to the agent + res = {"score": None, "metric": None, "error": f"test grader: {exc}", + "seconds": round(time.time() - started, 1)} + if attempt == 2 or isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError): + break + time.sleep(5) + try: + _ledger({"event": "test", "id": sid, **{k: res.get(k) for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + + +def with_time(out: dict) -> dict: + """Wall-clock accounting on every reply, as the v1 harness gave each phase.""" + out["total_budget_seconds"] = BUDGET_SEC + out["time_remaining_seconds"] = round(max(0.0, BUDGET_SEC - _elapsed()), 1) + return out + + +def status_dict() -> dict: + return { + "submissions": len(board.subs), + "queued_or_grading": sum(s["status"] != "graded" for s in board.subs.values()), + "best": board.best(), + } + + +def current_result(sid: int) -> dict: + return board.public(sid) + + +if ROLE == "val": + + @mcp.tool + async def submit(note: str = "") -> dict: + """Submit the current deliverable for grading. + + Snapshots the deliverable directory right now (later edits do not affect this + submission) and starts grading it on the public validation split. Returns at + once with a submission id. One submission is graded at a time: check `result` + and submit again once the previous submission has its score. `note` is a short + description of what changed. + """ + return with_time(await asyncio.to_thread(do_submit, note)) + + @mcp.tool + async def result(id: int) -> dict: + """The current state of a submission: queued, grading, or graded with its + validation score and grader output. Returns immediately.""" + if id not in board.subs: + return {"error": f"unknown submission id {id}"} + return with_time(current_result(id)) + + @mcp.tool + async def status() -> dict: + """Submission count, whether one is being graded, the best validation score, + and the time budget and time remaining.""" + return with_time(status_dict()) + + @mcp.custom_route("/submit", methods=["POST"]) + async def http_submit(request: Request) -> Response: + note = request.query_params.get("note", "") + return JSONResponse(with_time(await asyncio.to_thread(do_submit, note))) + + @mcp.custom_route("/result/{sid}", methods=["GET"]) + async def http_result(request: Request) -> Response: + sid = int(request.path_params["sid"]) + if sid not in board.subs: + return JSONResponse({"error": f"unknown submission id {sid}"}, status_code=404) + return JSONResponse(with_time(current_result(sid))) + + @mcp.custom_route("/status", methods=["GET"]) + async def http_status(request: Request) -> Response: + return JSONResponse(with_time(status_dict())) + + @mcp.custom_route("/final", methods=["POST"]) + async def http_final(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Collect hook, after the agent has stopped. + return JSONResponse(await asyncio.to_thread(final_submit)) + + @mcp.custom_route("/drain", methods=["GET"]) + async def http_drain(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Used by the verifier collect hook after the agent has stopped. + pending = sum(s["status"] != "graded" for s in board.subs.values()) + return JSONResponse({"val_pending": pending, "test_pending": board.test_pending}) + + +def _gpus() -> list[str]: + try: + out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=20) + return [l for l in out.stdout.splitlines() if l.strip()] + except Exception: + return [] + + +@mcp.custom_route("/health", methods=["GET"]) +async def health(request: Request) -> Response: + return JSONResponse({"ok": True, "role": ROLE, "gpus": await asyncio.to_thread(_gpus)}) + + +def _setup_token() -> None: + global TOKEN + if ROLE == "test": + TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True) + os.chmod(TOKEN_FILE.parent, 0o700) + TOKEN = secrets.token_hex(32) + TOKEN_FILE.write_text(TOKEN) + os.chmod(TOKEN_FILE, 0o600) + else: + for _ in range(300): # the test grader is healthy before this one starts + if TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip(): + break + time.sleep(1) + TOKEN = TOKEN_FILE.read_text().strip() + if not TOKEN: + raise SystemExit("ARE: empty internal token; refusing to start") + + +def main() -> None: + global NET_ISOLATED + NET_ISOLATED = _net_isolation_available() + if not NET_ISOLATED: + # Graded code must never have a network path (for example back through /submit). + raise SystemExit("ARE grader: cannot run grades without network access " + "(needs `unshare -n`, i.e. CAP_SYS_ADMIN); refusing to start") + STATE.mkdir(parents=True, exist_ok=True) + _BASELINE.update(_all_paths()) + _setup_token() + STATE.mkdir(parents=True, exist_ok=True) + os.chmod(STATE, 0o700) + (STATE / "snapshots").mkdir(exist_ok=True) + if ROLE == "val": + # The deliverable volume starts empty and root-owned; hand it to the agent user. + SUBMISSION_ROOT.mkdir(parents=True, exist_ok=True) + os.chmod(SUBMISSION_ROOT, 0o700) + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + src.mkdir(parents=True, exist_ok=True) + os.chown(src, AGENT_UID, AGENT_UID) + (STATE / "meta.json").write_text(json.dumps( + {"t0_wall": T0, "budget_seconds": BUDGET_SEC, "artifact_paths": ARTIFACT_PATHS} + )) + threading.Thread(target=grade_worker, daemon=True).start() + mcp.run(transport="http", host="0.0.0.0", port=PORT, show_banner=False, + uvicorn_config={"timeout_keep_alive": 86400}) + + +if __name__ == "__main__": + main() diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/compute_reward.py b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..33897ce4d11bcbac8156f775e792611507c95841 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +import json +import math +from pathlib import Path + +REWARD_PATH = Path("/logs/verifier/reward.txt") + + +def clamp01(raw: object) -> float: + """Total map from any object at all onto a finite reward inside [0, 1]. + + Never raises, and never returns NaN, an infinity or a value outside the band. A + non-numeric, unparseable, overflowing or non-finite input degrades to the floor, 0.0, + which is exactly what an invalid submission scores. + """ + try: + value = float(raw) + except (TypeError, ValueError, OverflowError): + return 0.0 + if not math.isfinite(value): + return 0.0 + return min(1.0, max(0.0, value)) + + +def emit(raw: object) -> None: + """Clamp, write, then re-read: the file that lands must itself parse back into [0, 1]. + + A short or garbled write is the one way a clamped value could still reach the platform + out of band, so the readback is checked and anything unexpected is replaced by the floor. + """ + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + text = f"{clamp01(raw):.12g}" + REWARD_PATH.write_text(text + "\n") + if clamp01(REWARD_PATH.read_text().strip()) != float(text): + REWARD_PATH.write_text("0\n") + + +try: + record = json.loads(Path("/logs/verifier/metric.json").read_text()) + emit(record["reward"]) + print(f"reward={REWARD_PATH.read_text().strip()}") +except BaseException as exc: + try: + emit(0.0) + except BaseException: + try: + with open(REWARD_PATH, "w") as handle: + handle.write("0\n") + except BaseException: + pass + print(f"reward=0 (fallback: {exc})") diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/extract_acts.py b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/extract_acts.py new file mode 100644 index 0000000000000000000000000000000000000000..adc61677a9819c730e644fa06af25d564398b701 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/extract_acts.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +import argparse +import hashlib +import json +import os +import re + +os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") +os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") +os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error") + +import numpy as np +import pyarrow.parquet as pq +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +D_MODEL = 768 +HIDDEN_STATE_INDEX = 9 + + +def parse_args() -> argparse.Namespace: + p = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--parquet", required=True, help="path to an OpenWebText parquet shard") + p.add_argument("--doc-start", type=int, default=0, help="first document row, inclusive") + p.add_argument("--doc-end", type=int, required=True, help="last document row, exclusive") + p.add_argument("--max-tokens", type=int, required=True, help="stop after this many rows") + p.add_argument("--out", required=True, help="destination .npy path") + p.add_argument("--model-dir", default="/opt/assets/gpt2", help="pinned GPT-2 checkpoint") + p.add_argument("--ctx", type=int, default=64, help="window length in tokens") + p.add_argument("--batch-windows", type=int, default=256, help="windows per forward pass") + p.add_argument("--device", default="cuda") + p.add_argument("--doc-chunk", type=int, default=512, help="documents tokenized at a time") + p.add_argument("--exclude-doc-indices", default=None, + help="optional JSON file holding a list of parquet row indices to skip") + return p.parse_args() + + +def normalize_doc(text: str) -> str: + """Stable content fingerprint of a document, used for cross-shard duplicate removal.""" + return hashlib.sha256( + re.sub(r"\s+", " ", text.lower()).strip()[:2000].encode("utf-8")).hexdigest() + + +def iter_windows(texts, tokenizer, ctx, doc_chunk): + """Yield lists of int windows, document by document, in parquet row order.""" + for start in range(0, len(texts), doc_chunk): + chunk = texts[start:start + doc_chunk] + encoded = tokenizer(chunk, add_special_tokens=False)["input_ids"] + for ids in encoded: + n_windows = len(ids) // ctx + for w in range(n_windows): + yield ids[w * ctx:(w + 1) * ctx] + + +def main() -> None: + args = parse_args() + torch.manual_seed(0) + + device = torch.device(args.device) + tokenizer = AutoTokenizer.from_pretrained(args.model_dir, use_fast=True) + model = AutoModelForCausalLM.from_pretrained(args.model_dir, dtype=torch.float32) + model.eval().to(device) + for param in model.parameters(): + param.requires_grad_(False) + + excluded: set[int] = set() + if args.exclude_doc_indices: + with open(args.exclude_doc_indices) as fh: + excluded = {int(i) for i in json.load(fh)} + + table = pq.read_table(args.parquet, columns=["text"]) + all_texts = table.column("text").to_pylist() + texts = [t for i, t in enumerate(all_texts[args.doc_start:args.doc_end], args.doc_start) + if i not in excluded] + del table, all_texts + + out = np.empty((args.max_tokens, D_MODEL), dtype=np.float16) + written = 0 + batch: list[list[int]] = [] + + def flush(batch_windows): + nonlocal written + if not batch_windows: + return + ids = torch.tensor(batch_windows, dtype=torch.long, device=device) + with torch.no_grad(): + hidden = model(input_ids=ids, output_hidden_states=True, + use_cache=False).hidden_states[HIDDEN_STATE_INDEX] + acts = hidden.reshape(-1, D_MODEL).float() + acts = acts - acts.mean(dim=1, keepdim=True) + acts = acts / acts.norm(dim=1, keepdim=True).clamp_min(1e-12) + take = min(acts.shape[0], args.max_tokens - written) + out[written:written + take] = acts[:take].to(torch.float16).cpu().numpy() + written += take + + for window in iter_windows(texts, tokenizer, args.ctx, args.doc_chunk): + batch.append(window) + if len(batch) == args.batch_windows: + flush(batch) + batch = [] + if written >= args.max_tokens: + break + if written < args.max_tokens: + flush(batch) + + if written < args.max_tokens: + raise SystemExit( + f"only {written} activation rows available from {args.parquet} documents " + f"[{args.doc_start}, {args.doc_end}); asked for {args.max_tokens}") + + parent = os.path.dirname(os.path.abspath(args.out)) + if parent: + os.makedirs(parent, exist_ok=True) + np.save(args.out, out) + print(f"wrote {out.shape} float16 to {args.out}") + + +if __name__ == "__main__": + main() diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/grader_core.py b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..d226be55d376b58cab438f2e507fc85d213d91fb --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,563 @@ +from __future__ import annotations + +import json +import os +import pwd +import shutil +import signal +import stat +import subprocess +import sys +import tempfile +import time +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np +import torch + + + + +D_MODEL = 768 +N_SEALED = 1_048_576 +BATCH_ROWS = 8192 +MAX_ATOMS = 8192 +MAX_MEAN_L0 = 32.0 +ENCODE_BUDGET_S = 900.0 +CANDIDATE_UID = 1001 + + + +MAX_K = MAX_ATOMS +MAX_TOTAL_NONZERO = int(MAX_MEAN_L0 * N_SEALED) + + + +SUBPROCESS_TIMEOUT_S = ENCODE_BUDGET_S + 600.0 + + + + + + + +DEGENERATE_REWARD = 0.10 +M_FLOOR = 1.000370 +M0 = 0.540922 +BASELINE_SCORE = 0.19 +SIGMA = -1.0 + + +class SubmissionInvalid(Exception): + """Any contract violation. Always maps to reward exactly 0.""" + + def __init__(self, reason: str, detail: str = ""): + super().__init__(reason if not detail else f"{reason}: {detail}") + self.reason = reason + self.detail = detail + + +@dataclass +class GradeResult: + valid: bool + reason: str = "ok" + detail: str = "" + metric: float | None = None + reward: float = 0.0 + mean_l0: float | None = None + n_atoms: int | None = None + encode_seconds: float | None = None + numerator: float | None = None + denominator: float | None = None + extra: dict = field(default_factory=dict) + + def to_json(self) -> dict: + return { + "valid": self.valid, + "reason": self.reason, + "detail": self.detail, + "metric": self.metric, + "reward": self.reward, + "mean_l0": self.mean_l0, + "n_atoms": self.n_atoms, + "encode_seconds": self.encode_seconds, + "numerator": self.numerator, + "denominator": self.denominator, + **self.extra, + } + + + + + +def graded_reward(metric: float | None, valid: bool) -> float: + """rational_squash with a linear degenerate band below the strongest trivial baseline. + + Invalid submissions short-circuit to exactly 0 before any arithmetic runs. + """ + if not valid or metric is None: + return 0.0 + if not np.isfinite(metric): + return 0.0 + x = SIGMA * (metric - M0) + x_ref = SIGMA * (BASELINE_SCORE - M0) + assert x_ref > 0, "malformed task: the baseline score does not beat the trivial baseline" + g = SIGMA * (M0 - M_FLOOR) + c = DEGENERATE_REWARD + if g <= 0: + u = max(0.0, x) / x_ref + return u / (1.0 + u) + if x < 0: + v = max(0.0, SIGMA * (metric - M_FLOOR)) / g + return c * v + u = x / x_ref + return c + (1.0 - c) * (u / (1.0 + u)) + + + + + +def scan_submission_tree(root: Path) -> int: + """Reject symlinks and hard links anywhere in the submitted tree, at every depth. + + Runs BEFORE anything is copied. A read-only bind mount does not remove hard links that + are already in the submission, and a no-dereference copy still carries them. + """ + total_bytes = 0 + if not root.is_dir() or root.is_symlink(): + raise SubmissionInvalid("missing_submission_dir", str(root)) + stack = [root] + seen = 0 + while stack: + cur = stack.pop() + try: + entries = sorted(os.scandir(cur), key=lambda e: e.name) + except OSError as exc: + raise SubmissionInvalid("unreadable_submission_dir", f"{cur}: {exc}") from exc + for entry in entries: + seen += 1 + if seen > 20000: + raise SubmissionInvalid("submission_too_many_entries", str(cur)) + st = os.lstat(entry.path) + if stat.S_ISLNK(st.st_mode): + raise SubmissionInvalid("symlink_in_submission", entry.path) + if stat.S_ISDIR(st.st_mode): + stack.append(Path(entry.path)) + continue + if not stat.S_ISREG(st.st_mode): + raise SubmissionInvalid("non_regular_file_in_submission", entry.path) + if st.st_nlink != 1: + raise SubmissionInvalid("hard_link_in_submission", + f"{entry.path} st_nlink={st.st_nlink}") + total_bytes += st.st_size + return total_bytes + + +def stage_submission(src: Path, dst: Path) -> int: + """Scan, then copy without following links, then hand the copy to the candidate uid.""" + total_bytes = scan_submission_tree(src) + shutil.copytree(src, dst, symlinks=True) + gid = pwd.getpwuid(CANDIDATE_UID).pw_gid + for path in [dst, *dst.rglob("*")]: + os.lchown(path, CANDIDATE_UID, gid) + return total_bytes + + + + + +def load_dictionary(path: Path) -> tuple[torch.Tensor, torch.Tensor, int]: + if not path.is_file(): + raise SubmissionInvalid("missing_dictionary", str(path)) + try: + obj = torch.load(str(path), map_location="cpu", weights_only=True) + except Exception as exc: + raise SubmissionInvalid("unparseable_dictionary", repr(exc)) from exc + if not isinstance(obj, dict) or "W_dec" not in obj or "b_pre" not in obj: + raise SubmissionInvalid("dictionary_missing_keys", str(sorted(map(repr, obj)))[:200] + if isinstance(obj, dict) else type(obj).__name__) + w_dec, b_pre = obj["W_dec"], obj["b_pre"] + if not isinstance(w_dec, torch.Tensor) or not isinstance(b_pre, torch.Tensor): + raise SubmissionInvalid("dictionary_not_tensors", "") + if w_dec.dtype != torch.float32 or b_pre.dtype != torch.float32: + raise SubmissionInvalid("dictionary_wrong_dtype", + f"{w_dec.dtype} {b_pre.dtype}") + if w_dec.dim() != 2 or w_dec.shape[0] != D_MODEL: + raise SubmissionInvalid("dictionary_wrong_shape", str(tuple(w_dec.shape))) + n_atoms = int(w_dec.shape[1]) + if n_atoms < 1 or n_atoms > MAX_ATOMS: + raise SubmissionInvalid("dictionary_size_out_of_range", str(n_atoms)) + if b_pre.shape != (D_MODEL,): + raise SubmissionInvalid("offset_wrong_shape", str(tuple(b_pre.shape))) + if not bool(torch.isfinite(w_dec).all()) or not bool(torch.isfinite(b_pre).all()): + raise SubmissionInvalid("dictionary_not_finite", "") + return w_dec.contiguous(), b_pre.contiguous(), n_atoms + + + + + +CANDIDATE_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + +_PASSTHROUGH_ENV = ( + "NVIDIA_VISIBLE_DEVICES", + "NVIDIA_DRIVER_CAPABILITIES", + "NVIDIA_REQUIRE_CUDA", + "CUDA_VISIBLE_DEVICES", + "LD_LIBRARY_PATH", +) + + +def candidate_env() -> dict: + """The complete environment the deliverable runs under. Determinism pinned HERE, not + only in the Dockerfile: a hand-built env dict discards the image's ENV values.""" + env = { + "PATH": CANDIDATE_PATH, + "HOME": pwd.getpwuid(CANDIDATE_UID).pw_dir, + "USER": pwd.getpwuid(CANDIDATE_UID).pw_name, + "LANG": "C.UTF-8", + "TMPDIR": "/tmp", + + "PYTHONHASHSEED": "0", + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONNOUSERSITE": "1", + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", + "CUBLAS_WORKSPACE_CONFIG": ":4096:8", + + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + "HF_HUB_DISABLE_PROGRESS_BARS": "1", + "TOKENIZERS_PARALLELISM": "false", + } + for key in _PASSTHROUGH_ENV: + if key in os.environ: + env[key] = os.environ[key] + return env + + +def stage_runner(parent: Path) -> Path: + """Copy the trusted runner out of the sealed /tests tree as a root-owned 0444 file in a + 0755 parent, so uid 1001 can execute it without /tests ever becoming traversable.""" + src = Path(__file__).resolve().parent / "run_encoder.py" + dst = parent / "run_encoder.py" + shutil.copyfile(src, dst) + os.chown(dst, 0, 0) + os.chmod(dst, 0o444) + return dst + + +def stage_sealed_inputs(acts_path: Path, parent: Path) -> Path: + """Copy the sealed activation matrix into a candidate-readable staging path. + + The activations ARE the reconstruction target, so the deliverable must see them; the + grading signal is not a hidden label but how well a <=32-nonzero code over a submitted + <=8192-atom dictionary can reproduce them. Nothing else from /tests is staged. + """ + dst = parent / "sealed_acts.npy" + shutil.copyfile(acts_path, dst) + os.chown(dst, 0, 0) + os.chmod(dst, 0o444) + return dst + + +def run_candidate(submission_dir: Path, acts_path: Path, workdir: Path) -> tuple[Path, dict]: + """Execute the deliverable as uid 1001 in its own process group under a wall-clock cap.""" + parent = workdir / "candidate" + parent.mkdir(parents=True) + os.chown(parent, 0, 0) + os.chmod(parent, 0o755) + + staged_sub = parent / "submission" + stage_submission(submission_dir, staged_sub) + entry = staged_sub / "encoder.py" + if not entry.is_file() or entry.stat().st_size == 0: + raise SubmissionInvalid("missing_or_empty_entry_point", str(entry)) + + runner = stage_runner(parent) + staged_acts = stage_sealed_inputs(acts_path, parent) + + codes_dir = parent / "codes" + codes_dir.mkdir() + gid = pwd.getpwuid(CANDIDATE_UID).pw_gid + os.lchown(codes_dir, CANDIDATE_UID, gid) + os.chmod(codes_dir, 0o755) + + cmd = [ + "runuser", "-u", "agent", "--", + sys.executable, str(runner), + "--submission-dir", str(staged_sub), + "--acts", str(staged_acts), + "--out-dir", str(codes_dir), + "--batch-rows", str(BATCH_ROWS), + "--n-rows", str(N_SEALED), + "--budget", str(ENCODE_BUDGET_S), + "--max-k", str(MAX_K), + "--max-total-nonzero", str(MAX_TOTAL_NONZERO), + ] + started = time.monotonic() + + + proc = subprocess.Popen( + cmd, cwd=str(parent), env=candidate_env(), stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, start_new_session=True) + timed_out = False + try: + stdout, stderr = proc.communicate(timeout=SUBPROCESS_TIMEOUT_S) + except subprocess.TimeoutExpired: + timed_out = True + _kill_group(proc) + try: + stdout, stderr = proc.communicate(timeout=60) + except Exception: + stdout, stderr = "", "" + rc = proc.returncode + elapsed = time.monotonic() - started + if timed_out: + raise SubmissionInvalid( + "harness_timeout", + f"candidate did not exit within {SUBPROCESS_TIMEOUT_S}s: {stderr[-1500:]}") + + meta = {"returncode": rc, "wall_seconds": elapsed, + "stdout_tail": stdout[-4000:], "stderr_tail": stderr[-4000:]} + failure_path = codes_dir / "failure.json" + if failure_path.is_file(): + try: + payload = json.loads(failure_path.read_text()) + except Exception: + payload = {"reason": "candidate_failed", "detail": "unreadable failure record"} + meta["failure"] = payload + raise SubmissionInvalid(str(payload.get("reason", "candidate_failed")), + f"{payload.get('detail', '')} | stderr={stderr[-1500:]}") + if rc != 0: + raise SubmissionInvalid("candidate_nonzero_exit", + f"rc={rc} stderr={stderr[-1500:]}") + run_meta_path = codes_dir / "run_meta.json" + if not run_meta_path.is_file(): + raise SubmissionInvalid("candidate_wrote_no_run_meta", stderr[-1500:]) + try: + meta["run_meta"] = json.loads(run_meta_path.read_text()) + except Exception as exc: + raise SubmissionInvalid("unparseable_run_meta", repr(exc)) from exc + return codes_dir, meta + + +def _kill_group(proc: "subprocess.Popen") -> None: + """Reap the candidate's whole process group. The child called setsid(2) at launch, so + its pid is the group id and one killpg takes down everything it forked.""" + try: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + except (ProcessLookupError, PermissionError, OSError): + pass + try: + proc.kill() + except Exception: + pass + + + + + +def _load_batch_arrays(codes_dir: Path, b: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + try: + row = np.load(codes_dir / f"b{b:05d}_row.npy") + col = np.load(codes_dir / f"b{b:05d}_col.npy") + val = np.load(codes_dir / f"b{b:05d}_val.npy") + except Exception as exc: + raise SubmissionInvalid("unreadable_codes", f"batch {b}: {exc!r}") from exc + return row, col, val + + +def score_codes(codes_dir: Path, acts_path: Path, w_dec: torch.Tensor, + b_pre: torch.Tensor, n_atoms: int, device: torch.device) -> dict: + acts = np.load(acts_path, mmap_mode="r") + if acts.shape != (N_SEALED, D_MODEL): + raise SubmissionInvalid("sealed_split_wrong_shape", str(acts.shape)) + + w_dec_d = w_dec.to(device) + b_pre_d = b_pre.to(device) + + + mean_acc = torch.zeros(D_MODEL, dtype=torch.float64, device=device) + n_batches = N_SEALED // BATCH_ROWS + for b in range(n_batches): + x = torch.from_numpy(np.array( + acts[b * BATCH_ROWS:(b + 1) * BATCH_ROWS])).to(device).float() + mean_acc += x.double().sum(dim=0) + x_bar = (mean_acc / float(N_SEALED)).float() + + numerator = 0.0 + denominator = 0.0 + total_nonzero = 0 + for b in range(n_batches): + row, col, val = _load_batch_arrays(codes_dir, b) + if row.ndim != 1 or col.ndim != 1 or val.ndim != 1: + raise SubmissionInvalid("codes_wrong_rank", f"batch {b}") + if not (row.shape == col.shape == val.shape): + raise SubmissionInvalid("codes_length_mismatch", f"batch {b}") + if row.dtype != np.int32 or col.dtype != np.int32 or val.dtype != np.float32: + raise SubmissionInvalid("codes_wrong_dtype", f"batch {b}") + nnz = int(row.shape[0]) + total_nonzero += nnz + if total_nonzero > MAX_TOTAL_NONZERO: + raise SubmissionInvalid("nonzero_budget_exceeded", str(total_nonzero)) + if nnz: + if int(row.min()) < 0 or int(row.max()) >= BATCH_ROWS: + raise SubmissionInvalid("code_row_out_of_range", f"batch {b}") + if int(col.min()) < 0 or int(col.max()) >= n_atoms: + raise SubmissionInvalid("code_index_out_of_range", + f"batch {b}: index outside [0, {n_atoms})") + if not np.isfinite(val).all(): + raise SubmissionInvalid("code_value_not_finite", f"batch {b}") + if np.any(val == 0.0): + raise SubmissionInvalid("zero_valued_code_entry", f"batch {b}") + keys = row.astype(np.int64) * np.int64(n_atoms) + col.astype(np.int64) + if np.unique(keys).shape[0] != keys.shape[0]: + raise SubmissionInvalid("duplicate_index_in_row", f"batch {b}") + + x = torch.from_numpy(np.array( + acts[b * BATCH_ROWS:(b + 1) * BATCH_ROWS])).to(device).float() + code = torch.zeros((BATCH_ROWS, n_atoms), dtype=torch.float32, device=device) + if nnz: + code[torch.from_numpy(row.astype(np.int64)).to(device), + torch.from_numpy(col.astype(np.int64)).to(device)] = \ + torch.from_numpy(val).to(device) + x_hat = torch.addmm(b_pre_d, code, w_dec_d.t()) + numerator += float(((x - x_hat).double() ** 2).sum().item()) + denominator += float(((x - x_bar).double() ** 2).sum().item()) + del code, x, x_hat + + if denominator <= 0.0: + raise SubmissionInvalid("degenerate_sealed_split", "zero variance") + mean_l0 = total_nonzero / float(N_SEALED) + if mean_l0 > MAX_MEAN_L0: + raise SubmissionInvalid("mean_l0_exceeded", f"{mean_l0:.6f} > {MAX_MEAN_L0}") + return {"metric": numerator / denominator, "numerator": numerator, + "denominator": denominator, "mean_l0": mean_l0, + "total_nonzero": total_nonzero} + + + + + +SEALED_CACHE = Path("/tmp/sealed_acts") + + +def materialize_sealed(split_dir: Path) -> Path: + """Derive the sealed activations for one half, at grade time, on the GPU. + + `docker build` has no accelerator, so this cannot happen in the image. It runs here, in + the trusted root process, from the sealed shard the verifier image holds, using the same + pinned extractor the agent had -- byte-identical bytes, a different shard argument. The + result is cached for the life of the container so the shape assertions and the grade + share one extraction. + """ + spec = load_split_spec(split_dir) + SEALED_CACHE.mkdir(parents=True, exist_ok=True) + os.chmod(SEALED_CACHE, 0o700) + out = SEALED_CACHE / f"{split_dir.name}.npy" + if out.is_file(): + return out + shard = split_dir.parent / "sealed_shard.parquet" + if not shard.is_file(): + raise SubmissionInvalid("missing_sealed_shard", str(shard)) + excludes = split_dir.parent / "excluded_doc_indices.json" + extractor = Path(__file__).resolve().parent / "extract_acts.py" + cmd = [sys.executable, str(extractor), + "--parquet", str(shard), + "--doc-start", str(int(spec["doc_start"])), + "--doc-end", str(int(spec["doc_end"])), + "--max-tokens", str(int(spec["max_tokens"])), + "--ctx", str(int(spec["ctx"])), + "--device", "cuda" if torch.cuda.is_available() else "cpu", + "--exclude-doc-indices", str(excludes), + "--out", str(out)] + proc = subprocess.run(cmd, capture_output=True, text=True, + timeout=3600, check=False) + if proc.returncode != 0 or not out.is_file(): + raise SubmissionInvalid( + "sealed_extraction_failed", + f"rc={proc.returncode} stderr={proc.stderr[-2000:]}") + return out + + +def load_split_spec(split_dir: Path) -> dict: + spec_path = split_dir / "spec.json" + if not spec_path.is_file(): + raise SubmissionInvalid("missing_split_spec", str(spec_path)) + return json.loads(spec_path.read_text()) + + +def assert_split_disjoint(specs: list[dict], agent_shards: list[str]) -> dict: + """Group-level disjointness on the canonical key, which here is (shard, document index). + + Rows are 64-token windows of a document, so a row-level split would put windows of the + same document on both sides. The assertion is made while both partitions exist, and it + is re-run at grade time rather than trusted from build time. + """ + seen: dict[str, list[tuple[int, int]]] = {} + for spec in specs: + shard = spec["shard"] + if shard in agent_shards: + raise SubmissionInvalid("sealed_split_uses_agent_shard", shard) + lo, hi = int(spec["doc_start"]), int(spec["doc_end"]) + for other_lo, other_hi in seen.get(shard, []): + if lo < other_hi and other_lo < hi: + raise SubmissionInvalid( + "sealed_splits_overlap", f"{shard} [{lo},{hi}) vs [{other_lo},{other_hi})") + seen.setdefault(shard, []).append((lo, hi)) + return {"shards": sorted(seen), "ranges": {k: v for k, v in seen.items()}} + + + + + +def grade(split_dir: Path, submission_dir: Path, all_split_dirs: list[Path], + agent_shards: list[str]) -> GradeResult: + workdir = Path(tempfile.mkdtemp(prefix="grade_", dir="/tmp")) + os.chmod(workdir, 0o755) + try: + specs = [load_split_spec(d) for d in all_split_dirs] + integrity = assert_split_disjoint(specs, agent_shards) + + acts_path = materialize_sealed(split_dir) + + dict_path = submission_dir / "dictionary.pt" + w_dec, b_pre, n_atoms = load_dictionary(dict_path) + + codes_dir, meta = run_candidate(submission_dir, acts_path, workdir) + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + scored = score_codes(codes_dir, acts_path, w_dec, b_pre, n_atoms, device) + + try: + encode_seconds = float(meta["run_meta"]["encode_seconds"]) + except (KeyError, TypeError, ValueError) as exc: + raise SubmissionInvalid("unparseable_run_meta", + f"encode_seconds: {exc!r}") from exc + if encode_seconds > ENCODE_BUDGET_S: + raise SubmissionInvalid("encode_budget_exceeded", + f"{encode_seconds:.1f}s > {ENCODE_BUDGET_S}s") + metric = scored["metric"] + return GradeResult( + valid=True, reason="ok", metric=metric, + reward=graded_reward(metric, True), mean_l0=scored["mean_l0"], + n_atoms=n_atoms, encode_seconds=encode_seconds, + numerator=scored["numerator"], denominator=scored["denominator"], + extra={"split": split_dir.name, "split_integrity": integrity, + "torch_device": str(device), + "cuda_device_count": torch.cuda.device_count(), + "candidate_wall_seconds": meta.get("wall_seconds"), + "candidate_stderr_tail": meta.get("stderr_tail", "")[-1500:], + "candidate_stdout_tail": meta.get("stdout_tail", "")[-1500:]}) + except SubmissionInvalid as exc: + return GradeResult(valid=False, reason=exc.reason, detail=exc.detail[:4000], + reward=0.0, extra={"split": split_dir.name}) + except Exception as exc: + return GradeResult(valid=False, reason="grader_internal_error", + detail=f"{type(exc).__name__}: {exc}"[:4000], reward=0.0, + extra={"split": split_dir.name}) + finally: + shutil.rmtree(workdir, ignore_errors=True) diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/hidden_data/README.md b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/hidden_data/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3df5fb21ed960c86674c3acd64a554456f4f7630 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/hidden_data/README.md @@ -0,0 +1,6 @@ +Sealed evaluation material. + +This directory is empty in the task source tree and is populated during the verifier image +build by `tests/prepare_hidden_data.py`, which writes `intermediate/` and `final/` -- two +document-disjoint halves of an OpenWebText shard that is not present in the agent image. +It is mode 0700 root-owned inside the verifier and is never copied into the agent image. diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/intermediate.sh b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..6c48beee31aacdca552142232acbc21d2ae8899c --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json \ + /logs/verifier/ctrf.json /logs/verifier/metric.json + +trap '[ -s /logs/verifier/reward.txt ] || printf "0\n" > /logs/verifier/reward.txt' EXIT + +chmod -R go-rwx /tests + +cd /tests +export GRADED_SPLIT=intermediate +/usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +/usr/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/prepare_hidden_data.py b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/prepare_hidden_data.py new file mode 100644 index 0000000000000000000000000000000000000000..01adb4cf53f3224208c26c99bae4538c2ad43f61 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/prepare_hidden_data.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import json +import os +import shutil +import sys +from pathlib import Path + +os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") + +import pyarrow.parquet as pq +from huggingface_hub import hf_hub_download + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from extract_acts import normalize_doc + +OWT_REPO = "Skylion007/openwebtext" +OWT_REVISION = "79d93d786212f7344586290adb811d4ae6a1762c" +SEALED_SHARD = "plain_text/train-00079-of-00080.parquet" +AGENT_SHARDS = [ + "plain_text/train-00000-of-00080.parquet", + "plain_text/train-00001-of-00080.parquet", +] +N_SEALED = 1_048_576 +SPLITS = { + "intermediate": (0, 20000), + "final": (20000, 40000), +} +HIDDEN = Path(__file__).resolve().parent / "hidden_data" +SCRATCH = Path("/tmp/hidden_prepare") + + +def main() -> None: + SCRATCH.mkdir(parents=True, exist_ok=True) + HIDDEN.mkdir(parents=True, exist_ok=True) + + sealed_src = hf_hub_download(repo_id=OWT_REPO, repo_type="dataset", + revision=OWT_REVISION, filename=SEALED_SHARD, + local_dir=str(SCRATCH / "owt")) + agent_paths = [hf_hub_download(repo_id=OWT_REPO, repo_type="dataset", + revision=OWT_REVISION, filename=f, + local_dir=str(SCRATCH / "owt")) for f in AGENT_SHARDS] + + agent_hashes: set[str] = set() + for path in agent_paths: + texts = pq.read_table(path, columns=["text"]).column("text").to_pylist() + agent_hashes.update(normalize_doc(t) for t in texts) + del texts + print(f"agent-visible document fingerprints: {len(agent_hashes)}") + + sealed_texts = pq.read_table(sealed_src, columns=["text"]).column("text").to_pylist() + lo = min(a for a, _ in SPLITS.values()) + hi = max(b for _, b in SPLITS.values()) + excluded: list[int] = [] + seen: set[str] = set() + cross_shard_dups = 0 + within_sealed_dups = 0 + for i in range(lo, hi): + h = normalize_doc(sealed_texts[i]) + if h in agent_hashes: + excluded.append(i) + cross_shard_dups += 1 + elif h in seen: + excluded.append(i) + within_sealed_dups += 1 + else: + seen.add(h) + del sealed_texts, agent_hashes + + sealed_dst = HIDDEN / "sealed_shard.parquet" + shutil.move(sealed_src, sealed_dst) + (HIDDEN / "excluded_doc_indices.json").write_text(json.dumps(excluded)) + + for name, (doc_start, doc_end) in SPLITS.items(): + out_dir = HIDDEN / name + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "spec.json").write_text(json.dumps({ + "shard": SEALED_SHARD, + "revision": OWT_REVISION, + "doc_start": doc_start, + "doc_end": doc_end, + "max_tokens": N_SEALED, + "ctx": 64, + "excluded_doc_indices": [i for i in excluded if doc_start <= i < doc_end], + }, indent=2, sort_keys=True)) + + (HIDDEN / "dedup_report.json").write_text(json.dumps({ + "sealed_shard": SEALED_SHARD, + "documents_scanned": hi - lo, + "cross_shard_duplicates_removed": cross_shard_dups, + "within_sealed_duplicates_removed": within_sealed_dups, + }, indent=2, sort_keys=True)) + + shutil.rmtree(SCRATCH, ignore_errors=True) + print(json.dumps({"cross_shard_duplicates_removed": cross_shard_dups, + "within_sealed_duplicates_removed": within_sealed_dups, + "sealed_shard_bytes": sealed_dst.stat().st_size})) + + +if __name__ == "__main__": + main() diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/requirements-verifier.txt b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..04676c89520bf969f2cb861ad1811f46d8370700 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/requirements-verifier.txt @@ -0,0 +1,2 @@ +pytest==8.3.5 +pytest-json-ctrf==0.3.5 diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/run_encoder.py b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/run_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..203416da092440399d7c9ab3029d6118c8ba3bba --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/run_encoder.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import random +import sys +import time +import traceback +from pathlib import Path + +import numpy as np +import torch + +EXIT_CANDIDATE_FAILURE = 3 + + +def pin_determinism() -> None: + random.seed(0) + np.random.seed(0) + torch.manual_seed(0) + torch.cuda.manual_seed_all(0) + torch.set_num_threads(1) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + + + torch.use_deterministic_algorithms(True, warn_only=True) + + +def fail(out_dir: Path, reason: str, detail: str) -> None: + (out_dir / "failure.json").write_text(json.dumps( + {"reason": reason, "detail": detail[:4000]})) + sys.stderr.write(f"{reason}: {detail[:4000]}\n") + sys.exit(EXIT_CANDIDATE_FAILURE) + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--submission-dir", required=True) + ap.add_argument("--acts", required=True) + ap.add_argument("--out-dir", required=True) + ap.add_argument("--batch-rows", type=int, required=True) + ap.add_argument("--n-rows", type=int, required=True) + ap.add_argument("--budget", type=float, required=True) + ap.add_argument("--max-k", type=int, required=True) + ap.add_argument("--max-total-nonzero", type=int, required=True) + args = ap.parse_args() + + out_dir = Path(args.out_dir) + pin_determinism() + + device_str = "cuda" if torch.cuda.is_available() else "cpu" + device = torch.device(device_str) + + sys.path.insert(0, args.submission_dir) + spent = 0.0 + try: + t0 = time.monotonic() + import encoder + if not hasattr(encoder, "load"): + spent += time.monotonic() - t0 + fail(out_dir, "encoder_missing_load", "module defines no load(device)") + model = encoder.load(device_str) + spent += time.monotonic() - t0 + except SystemExit: + raise + except BaseException: + fail(out_dir, "encoder_load_failed", traceback.format_exc()) + + if not hasattr(model, "encode"): + fail(out_dir, "encoder_missing_encode", "load() returned an object with no encode()") + + acts = np.load(args.acts, mmap_mode="r") + if acts.shape != (args.n_rows, 768): + fail(out_dir, "runner_bad_inputs", str(acts.shape)) + + n_batches = args.n_rows // args.batch_rows + total_nonzero = 0 + for b in range(n_batches): + lo = b * args.batch_rows + x = torch.from_numpy(np.array( + acts[lo:lo + args.batch_rows])).to(device).float() + t0 = time.monotonic() + try: + ret = model.encode(x) + if device_str == "cuda": + torch.cuda.synchronize() + except BaseException: + spent += time.monotonic() - t0 + fail(out_dir, "encode_raised", f"batch {b}\n{traceback.format_exc()}") + spent += time.monotonic() - t0 + if spent > args.budget: + fail(out_dir, "encode_budget_exceeded", + f"{spent:.2f}s of the {args.budget:.0f}s budget after batch {b}") + + if not (isinstance(ret, tuple) and len(ret) == 2): + fail(out_dir, "encode_bad_return", f"batch {b}: expected a 2-tuple, got {type(ret)}") + idx, val = ret + if not isinstance(idx, torch.Tensor) or not isinstance(val, torch.Tensor): + fail(out_dir, "encode_bad_return", f"batch {b}: entries must be torch tensors") + if idx.dim() != 2 or val.dim() != 2 or idx.shape != val.shape: + fail(out_dir, "encode_bad_shape", + f"batch {b}: idx {tuple(idx.shape)} val {tuple(val.shape)}") + if idx.shape[0] != args.batch_rows: + fail(out_dir, "encode_bad_shape", + f"batch {b}: first dimension {idx.shape[0]} != {args.batch_rows}") + k = int(idx.shape[1]) + if k > args.max_k: + fail(out_dir, "encode_k_too_large", f"batch {b}: K={k}") + if idx.dtype not in (torch.int16, torch.int32, torch.int64): + fail(out_dir, "encode_bad_dtype", f"batch {b}: idx dtype {idx.dtype}") + if val.dtype not in (torch.float16, torch.float32, torch.float64): + fail(out_dir, "encode_bad_dtype", f"batch {b}: val dtype {val.dtype}") + + idx_np = idx.detach().to("cpu").to(torch.int64).numpy() + val_np = val.detach().to("cpu").to(torch.float32).numpy() + keep = val_np != 0.0 + rows = np.nonzero(keep)[0].astype(np.int32) + cols = idx_np[keep].astype(np.int64) + vals = val_np[keep].astype(np.float32) + if cols.size and (cols.min() < -(1 << 31) or cols.max() > (1 << 31) - 1): + fail(out_dir, "encode_index_out_of_range", f"batch {b}") + total_nonzero += int(rows.size) + if total_nonzero > args.max_total_nonzero: + fail(out_dir, "nonzero_budget_exceeded", f"batch {b}: {total_nonzero}") + np.save(out_dir / f"b{b:05d}_row.npy", rows) + np.save(out_dir / f"b{b:05d}_col.npy", cols.astype(np.int32)) + np.save(out_dir / f"b{b:05d}_val.npy", vals) + del x, idx, val, ret + + (out_dir / "run_meta.json").write_text(json.dumps({ + "encode_seconds": spent, + "total_nonzero": total_nonzero, + "n_batches": n_batches, + "device": device_str, + "cuda_device_count": torch.cuda.device_count(), + "uid": os.getuid(), + })) + print(f"encode_seconds={spent:.3f} total_nonzero={total_nonzero} uid={os.getuid()} " + f"device={device_str} cuda_devices={torch.cuda.device_count()}") + + +if __name__ == "__main__": + main() diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/test.sh b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3326a11914fb52a04c089fe88f0e51f3b75e3ee9 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json \ + /logs/verifier/ctrf.json /logs/verifier/metric.json + +trap '[ -s /logs/verifier/reward.txt ] || printf "0\n" > /logs/verifier/reward.txt' EXIT + +chmod -R go-rwx /tests + +cd /tests +export GRADED_SPLIT=final +/usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +/usr/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/test_state.py b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..6b13b7e431277e2ecd9a2442f3fe9a8d0df91cce --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/are-grader-ctx/test_state.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import json +import os +import random +import sys +from pathlib import Path + +import numpy as np +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import grader_core + +TESTS_DIR = Path(__file__).resolve().parent +HIDDEN = TESTS_DIR / "hidden_data" +SPLITS = ["intermediate", "final"] +AGENT_SHARDS = [ + "plain_text/train-00000-of-00080.parquet", + "plain_text/train-00001-of-00080.parquet", +] +SUBMISSION_DIR = Path("/app/output") +METRIC_PATH = Path("/logs/verifier/metric.json") + + +def _pin_determinism() -> None: + random.seed(0) + np.random.seed(0) + torch.manual_seed(0) + torch.set_num_threads(1) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.use_deterministic_algorithms(True, warn_only=True) + + +def _write_metric(payload: dict) -> None: + METRIC_PATH.parent.mkdir(parents=True, exist_ok=True) + METRIC_PATH.write_text(json.dumps(payload, indent=2, sort_keys=True, default=str)) + + +def test_sealed_splits_are_group_disjoint() -> None: + """The sealed halves must be disjoint on the canonical group key -- (shard, document + index) -- not on rows, because every row is a 64-token window OF a document. Asserted + while both partitions exist, and re-asserted here rather than trusted from build time. + A duplicate-key fixture is injected so the check cannot pass merely because the real + ranges happen to be unique.""" + specs = [grader_core.load_split_spec(HIDDEN / s) for s in SPLITS] + integrity = grader_core.assert_split_disjoint(specs, AGENT_SHARDS) + assert set(integrity["shards"]).isdisjoint(AGENT_SHARDS) + + duplicated = specs + [dict(specs[0])] + try: + grader_core.assert_split_disjoint(duplicated, AGENT_SHARDS) + except grader_core.SubmissionInvalid as exc: + assert exc.reason == "sealed_splits_overlap" + else: + raise AssertionError("duplicate group keys were not rejected") + + leaked = [dict(specs[0], shard=AGENT_SHARDS[0])] + try: + grader_core.assert_split_disjoint(leaked, AGENT_SHARDS) + except grader_core.SubmissionInvalid as exc: + assert exc.reason == "sealed_split_uses_agent_shard" + else: + raise AssertionError("an agent-visible shard was accepted as a sealed split") + + +def test_sealed_split_is_derived_at_the_declared_shape() -> None: + """The graded half derives to exactly the declared shape from the sealed shard, and the + duplicate scrub that ran at image-build time left a record. A missing or mis-shaped half + is a task defect and fails closed: grade() raises and the reward is 0.""" + report = json.loads((HIDDEN / "dedup_report.json").read_text()) + assert report["documents_scanned"] > 0 + assert report["cross_shard_duplicates_removed"] >= 0 + split = os.environ.get("GRADED_SPLIT", "final") + acts = np.load(grader_core.materialize_sealed(HIDDEN / split), mmap_mode="r") + assert acts.shape == (grader_core.N_SEALED, grader_core.D_MODEL), (split, acts.shape) + assert acts.dtype == np.float16 + + +def test_reward_map_endpoints() -> None: + """The reward map honours its contract: invalid is exactly 0, the no-effort floor is + exactly 0, the strongest trivial baseline is exactly the degenerate constant, the + baseline score reward is 0.55, and the map is monotone with no cutoff.""" + gr = grader_core.graded_reward + xs = [1.2, 1.0, 0.8, 0.6, 0.45, 0.30, 0.19, 0.12, 0.05, 0.01] + rewards = [gr(x, True) for x in xs] + + + checks = { + "invalid_none_is_zero": gr(None, False) == 0.0, + "invalid_value_is_zero": gr(0.05, False) == 0.0, + "floor_is_zero": gr(grader_core.M_FLOOR, True) == 0.0, + "worse_than_floor_is_zero": gr(grader_core.M_FLOOR + 0.5, True) == 0.0, + "trivial_baseline_is_c": + abs(gr(grader_core.M0, True) - grader_core.DEGENERATE_REWARD) < 1e-12, + "baseline_score_reward_is_0.55": abs(gr(grader_core.BASELINE_SCORE, True) - 0.55) < 1e-9, + "monotone": all(b >= a for a, b in zip(rewards, rewards[1:])), + "bounded": all(0.0 <= r <= 1.0 for r in rewards), + "no_saturation_at_one": rewards[-1] < 1.0, + } + failed = sorted(k for k, ok in checks.items() if not ok) + assert not failed, f"reward map violates: {failed}" + + +def test_grade_submission() -> None: + """Run the agent's deliverable on the sealed split and write the grade record. + + Every failure path -- missing directory, symlink or hard link in the submitted tree, + unloadable dictionary, contract violation, crash, timeout, malformed codes -- lands on + reward exactly 0 through the same record, so no exception can escape and leave + /logs/verifier/metric.json unwritten. + """ + _pin_determinism() + split = os.environ.get("GRADED_SPLIT", "final") + assert split in SPLITS, f"unknown GRADED_SPLIT={split!r}" + try: + result = grader_core.grade( + split_dir=HIDDEN / split, + submission_dir=SUBMISSION_DIR, + all_split_dirs=[HIDDEN / s for s in SPLITS], + agent_shards=AGENT_SHARDS, + ) + payload = result.to_json() + except BaseException as exc: + payload = {"valid": False, "reason": "grader_internal_error", + "detail": f"{type(exc).__name__}: {exc}"[:4000], "reward": 0.0, + "metric": None, "split": split} + payload["graded_split"] = split + _write_metric(payload) + print(json.dumps({k: v for k, v in payload.items() + if k in ("valid", "reason", "metric", "reward", "mean_l0", + "n_atoms", "encode_seconds", "graded_split")}, + indent=2, default=str)) + assert 0.0 <= float(payload["reward"]) <= 1.0 diff --git a/tasks/sae-sparse-dict-nmse-frontier/environment/docker-compose.yaml b/tasks/sae-sparse-dict-nmse-frontier/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..155ad2d3426c09ba00a36812b83c1b0f8efa2166 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/environment/docker-compose.yaml @@ -0,0 +1,94 @@ +# ARE 1.1: grading lives in sidecars. Harbor configures `main` (build, limits, network). +services: + main: + depends_on: + grader: + condition: service_healthy + volumes: + - are-deliverable-0:/app/output + + grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: val + platform: linux/amd64 + environment: + ARE_ROLE: val + ARE_PORT: "8000" + ARE_BUDGET_SEC: "86400" + ARE_ARTIFACT_PATHS: "/app/output" + ARE_AGENT_UID: "1001" + ARE_GRADE_TIMEOUT_SEC: "7200" + volumes: + - are-deliverable-0:/run/are-deliverable/app/output + - are-secret:/run/are-secret + expose: + - "8000" + cap_add: [SYS_ADMIN] + networks: [default, are-private] + cpus: 4 + mem_limit: 32768m + deploy: + resources: + reservations: + devices: + - driver: nvidia + # GPU 0 is shared with the agent (works on any 1-GPU host). On a host with a + # spare GPU, export ARE_GRADER_GPU=1 to give grading its own, as in ARE 1.0. + device_ids: ["${ARE_GRADER_GPU:-0}"] + capabilities: [gpu] + depends_on: + test-grader: + condition: service_healthy + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + + test-grader: + build: + context: ./are-grader-ctx + dockerfile: Dockerfile.are + args: + ARE_ROLE: test + platform: linux/amd64 + environment: + ARE_ROLE: test + ARE_PORT: "8001" + ARE_ARTIFACT_PATHS: "/app/output" + ARE_GRADE_TIMEOUT_SEC: "7200" + expose: + - "8001" + volumes: + - are-secret:/run/are-secret + cap_add: [SYS_ADMIN] + networks: [are-private] + cpus: 4 + mem_limit: 32768m + deploy: + resources: + reservations: + devices: + - driver: nvidia + # GPU 0 is shared with the agent (works on any 1-GPU host). On a host with a + # spare GPU, export ARE_GRADER_GPU=1 to give grading its own, as in ARE 1.0. + device_ids: ["${ARE_GRADER_GPU:-0}"] + capabilities: [gpu] + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8001/health', timeout=2)"] + interval: 2s + timeout: 5s + retries: 60 + start_period: 5s + +volumes: + are-deliverable-0: {} + are-secret: {} + +networks: + are-private: + internal: true diff --git a/tasks/sae-sparse-dict-nmse-frontier/task.toml b/tasks/sae-sparse-dict-nmse-frontier/task.toml index 2ea070409255a829eebc9f573eca40690283693b..c25fa22ce3b9ae65c63fcd8f9a66fda4731bdf03 100644 --- a/tasks/sae-sparse-dict-nmse-frontier/task.toml +++ b/tasks/sae-sparse-dict-nmse-frontier/task.toml @@ -1,46 +1,74 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/sae-sparse-dict-nmse-frontier" -version = "1.0.0" +version = "1.1.0" description = "" -keywords = [ "autoresearch", "machine-learning", "benchmark",] -[[task.authors]] -name = "Bespoke Labs" +keywords = [ + "autoresearch", + "machine-learning", + "benchmark", +] +authors = [ + { name = "Bespoke Labs" }, +] [metadata] category = "Machine Learning and AI" subcategory = "Unsupervised and representation learning" -task_objective = [ "Optimize", "Implement",] -artifact_type = [ "Single script or program", "Generated output artifact",] +task_objective = [ + "Optimize", + "Implement", +] +artifact_type = [ + "Single script or program", + "Generated output artifact", +] expert_time_estimate_hours = 6.0 +are_version = "1.1" +budget_seconds = 86400 [verifier] -network_mode = "no-network" -timeout_sec = 7200.0 +timeout_sec = 600.0 environment_mode = "separate" -collect = [] -[verifier.env] +[[verifier.collect]] +service = "grader" +command = "/opt/are/venv/bin/python /opt/are/drain.py" +timeout_sec = 14400.0 + +[verifier.environment] +network_mode = "no-network" +build_timeout_sec = 600.0 +cpus = 1 +memory_mb = 1024 +gpus = 0 [agent] network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] -timeout_sec = 21600.0 +allowed_hosts = [ + "api.openai.com", + "api.anthropic.com", + "grader", +] +timeout_sec = 86400.0 [environment] -network_mode = "allowlist" -allowed_hosts = [ "api.openai.com", "api.anthropic.com",] +network_mode = "public" build_timeout_sec = 10800.0 os = "linux" cpus = 4 memory_mb = 32768 storage_mb = 307200 gpus = 1 -gpu_types = [ "H100",] -mcp_servers = [] +gpu_types = [ + "H100", +] +mcp_servers = [ + { name = "are", transport = "streamable-http", url = "http://grader:8000/mcp" }, +] [environment.env] - -[solution.env] diff --git a/tasks/sae-sparse-dict-nmse-frontier/tests/Dockerfile b/tasks/sae-sparse-dict-nmse-frontier/tests/Dockerfile index 9568764d237a800b5b76aaf9b7c525953f5c5b0e..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/sae-sparse-dict-nmse-frontier/tests/Dockerfile +++ b/tasks/sae-sparse-dict-nmse-frontier/tests/Dockerfile @@ -1,41 +1,2 @@ -FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 - -ENTRYPOINT [] -ENV PYTHONPATH= -ENV PYTHONSAFEPATH=1 -ENV PYTHONHASHSEED=0 \ - PYTHONDONTWRITEBYTECODE=1 \ - PIP_NO_CACHE_DIR=1 \ - PIP_DISABLE_PIP_VERSION_CHECK=1 \ - OMP_NUM_THREADS=1 \ - MKL_NUM_THREADS=1 \ - OPENBLAS_NUM_THREADS=1 \ - NUMEXPR_NUM_THREADS=1 \ - CUBLAS_WORKSPACE_CONFIG=:4096:8 \ - TOKENIZERS_PARALLELISM=false \ - HF_HUB_DISABLE_PROGRESS_BARS=1 - -RUN useradd --create-home --uid 1001 agent - -COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt -RUN /usr/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements-verifier.txt \ - && rm /tmp/requirements-verifier.txt - -RUN /usr/bin/python3 -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='openai-community/gpt2', revision='607a30d783dfa663caf39e06633721c8d4cfcd7e', local_dir='/opt/assets/gpt2', allow_patterns=['config.json','generation_config.json','model.safetensors','tokenizer.json','tokenizer_config.json','vocab.json','merges.txt'])" \ - && rm -rf /opt/assets/gpt2/.cache - -RUN mkdir -p /app/output /logs/verifier - -COPY . /tests - -RUN /usr/bin/python3 /tests/prepare_hidden_data.py - -RUN chown -R root:root /tests \ - && chmod 700 /tests/hidden_data \ - && chmod +x /tests/test.sh /tests/intermediate.sh \ - && find /tests -exec touch -d @1700000000 {} + - -WORKDIR /tests - -ENV HF_HUB_OFFLINE=1 -ENV TRANSFORMERS_OFFLINE=1 +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/sae-sparse-dict-nmse-frontier/tests/finalize.py b/tasks/sae-sparse-dict-nmse-frontier/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/sae-sparse-dict-nmse-frontier/tests/finalize.py @@ -0,0 +1,59 @@ +"""Final verifier: score the run from the grader ledger. + +reward hidden test score of the submission with the best validation score + (ties go to the earlier submission); 0 if nothing was submitted. +auarc area under the curve of that same quantity over the wall-clock budget, + using the time each validation score became available, divided by the + budget. 0 before the first graded submission. +""" + +import json +from pathlib import Path + +STATE = Path("/var/lib/are") +OUT = Path("/logs/verifier") +OUT.mkdir(parents=True, exist_ok=True) + +meta = json.loads((STATE / "meta.json").read_text()) if (STATE / "meta.json").exists() else {} +budget = float(meta.get("budget_seconds") or 1.0) + +subs: dict[int, dict] = {} +ledger = STATE / "ledger.jsonl" +for line in (ledger.read_text().splitlines() if ledger.exists() else []): + ev = json.loads(line) + s = subs.setdefault(ev["id"], {"id": ev["id"]}) + if ev["event"] == "submitted": + s["submitted_t"] = ev["t"] + elif ev["event"] == "val": + s["val"] = ev["score"] + s["val_t"] = ev["t"] + elif ev["event"] == "test": + s["test"] = ev["score"] + +graded = sorted((s for s in subs.values() if "val" in s), key=lambda s: s["val_t"]) + +# Step function of the hidden score of the best-validation pick over time. +auc, best, last_t, cur = 0.0, None, 0.0, 0.0 +timeline = [] +for s in graded: + t = min(s["val_t"], budget) + auc += cur * (t - last_t) + last_t = t + if best is None or s["val"] > best["val"] or (s["val"] == best["val"] and s["id"] < best["id"]): + best = s + cur = float(best.get("test") or 0.0) + timeline.append({"t": s["val_t"], "id": s["id"], "val": s["val"], "test": s.get("test"), + "pick": best["id"]}) +auc += cur * (budget - last_t) if last_t < budget else 0.0 + +reward = { + "reward": float(best.get("test") or 0.0) if best else 0.0, + "auarc": auc / budget, + "best_val": float(best["val"]) if best else 0.0, + "n_submissions": float(len(subs)), + "n_test_graded": float(sum(s.get("test") is not None for s in subs.values())), +} +(OUT / "reward.json").write_text(json.dumps(reward)) +(OUT / "timeline.json").write_text(json.dumps({"budget": budget, "selected": best and best["id"], + "submissions": timeline}, indent=1)) +print(json.dumps(reward, indent=1)) diff --git a/tasks/sae-sparse-dict-nmse-frontier/tests/test.sh b/tasks/sae-sparse-dict-nmse-frontier/tests/test.sh index 3326a11914fb52a04c089fe88f0e51f3b75e3ee9..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/sae-sparse-dict-nmse-frontier/tests/test.sh +++ b/tasks/sae-sparse-dict-nmse-frontier/tests/test.sh @@ -1,19 +1,2 @@ #!/bin/bash -set -u - -mkdir -p /logs/verifier -chown root:root /logs/verifier 2>/dev/null || true -chmod 755 /logs/verifier 2>/dev/null || true -rm -f /logs/verifier/reward.txt /logs/verifier/reward.json \ - /logs/verifier/ctrf.json /logs/verifier/metric.json - -trap '[ -s /logs/verifier/reward.txt ] || printf "0\n" > /logs/verifier/reward.txt' EXIT - -chmod -R go-rwx /tests - -cd /tests -export GRADED_SPLIT=final -/usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA -/usr/bin/python3 /tests/compute_reward.py - -exit 0 +python3 /tests/finalize.py diff --git a/tasks/shortest-valid-ci-l2-ece/environment/.dockerignore b/tasks/shortest-valid-ci-l2-ece/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/Dockerfile b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b277d2f2206e6fede1be762a297a8408ce255517 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,41 @@ +FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONHASHSEED=0 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 \ + NUMEXPR_NUM_THREADS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements.txt /tmp/requirements.txt +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ + -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements.txt /tmp/requirements-verifier.txt + +RUN mkdir -p /app/output /logs/verifier /opt/candrun + +COPY . /tests + +RUN cp /tests/run_call.py /opt/candrun/run_call.py \ + && chown root:root /opt/candrun /opt/candrun/run_call.py \ + && chmod 755 /opt/candrun \ + && chmod 444 /opt/candrun/run_call.py \ + && chown -R root:root /tests /home/agent \ + && chmod 755 /home/agent \ + && chmod 755 /tmp /var/tmp \ + && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/Dockerfile.are b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..d3b0abeff0a75b40d843bdac79ebf45087a61c83 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,59 @@ +FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONHASHSEED=0 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + OMP_NUM_THREADS=1 \ + MKL_NUM_THREADS=1 \ + OPENBLAS_NUM_THREADS=1 \ + NUMEXPR_NUM_THREADS=1 + +RUN useradd --create-home --uid 1001 agent + +COPY ./requirements.txt /tmp/requirements.txt +COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt +RUN /usr/local/bin/python3 -m pip install --no-cache-dir \ + -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \ + && rm /tmp/requirements.txt /tmp/requirements-verifier.txt + +RUN mkdir -p /app/output /logs/verifier /opt/candrun + +COPY . /tests + +RUN cp /tests/run_call.py /opt/candrun/run_call.py \ + && chown root:root /opt/candrun /opt/candrun/run_call.py \ + && chmod 755 /opt/candrun \ + && chmod 444 /opt/candrun/run_call.py \ + && chown -R root:root /tests /home/agent \ + && chmod 755 /home/agent \ + && chmod 755 /tmp /var/tmp \ + && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests -exec touch -d @1700000000 {} + + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 + + +# ---- ARE 1.1 grader layer (appended to the task's own verifier Dockerfile) ---- +ARG ARE_ROLE +# python.org images ship /usr/local/bin/python3; distro-python bases (kaggle GPU) lack +# ensurepip, so fall back to a pip-less venv filled by the base interpreter's pip. +RUN PY=$(command -v /usr/local/bin/python3 || command -v python3) \ + && if "$PY" -m venv /opt/are/venv; then \ + /opt/are/venv/bin/pip install --no-cache-dir "fastmcp==2.14.7"; \ + else rm -rf /opt/are/venv && "$PY" -m venv --without-pip /opt/are/venv \ + && "$PY" -m pip --python /opt/are/venv/bin/python install --no-cache-dir "fastmcp==2.14.7"; fi +COPY are/ /opt/are/ +# The val grader, whose output reaches the agent, never holds the private grader or its +# data. The test grader keeps everything; nothing from it reaches the agent. +RUN rm -rf /tests/are /tests/Dockerfile.are \ + && if [ "$ARE_ROLE" = "val" ]; then rm -rf /tests/test.sh /tests/hidden_data/final; fi +ENV ARE_ROLE=$ARE_ROLE +CMD ["/opt/are/venv/bin/python", "/opt/are/server.py"] diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/are/drain.py b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/are/drain.py @@ -0,0 +1,25 @@ +"""Verifier collect hook, run after the agent stops. + +Grades the final workspace as one last submission (unless it equals the last one), +then waits until every submission has both grades recorded. +""" + +import json +import time +import urllib.request +from pathlib import Path + +TOKEN = Path("/run/are-secret/token").read_text().strip() +H = {"x-are-token": TOKEN} + +req = urllib.request.Request("http://localhost:8000/final", method="POST", headers=H) +with urllib.request.urlopen(req, timeout=120) as resp: + print("final:", json.loads(resp.read()), flush=True) + +while True: + with urllib.request.urlopen(urllib.request.Request("http://localhost:8000/drain", headers=H), timeout=30) as resp: + state = json.loads(resp.read()) + print(state, flush=True) + if state["val_pending"] == 0 and state["test_pending"] == 0: + break + time.sleep(5) diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/are/server.py b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/are/server.py @@ -0,0 +1,538 @@ +"""ARE 1.1 grader sidecar. + +One image, two roles: + +- ARE_ROLE=val ("grader" service). Reachable from the agent. Serves MCP tools and a + REST fallback. On submit it snapshots the shared deliverable volume, grades the + snapshot with the task's public grader (intermediate.sh), and returns only that + score. Every snapshot is also sent to the test grader; the hidden score goes to a + root-only ledger and never back to the agent. +- ARE_ROLE=test ("test-grader" service). On a private network that only the val + grader can reach. Grades snapshots with the task's private grader (test.sh). +""" + +from __future__ import annotations + +import asyncio +import gzip +import hashlib +import io +import secrets +import json +import os +import queue +import shutil +import subprocess +import tarfile +import threading +import time +import urllib.request +from pathlib import Path + +from fastmcp import FastMCP +from starlette.requests import Request +from starlette.responses import JSONResponse, Response + +ROLE = os.environ.get("ARE_ROLE", "val") +PORT = int(os.environ.get("ARE_PORT", "8000")) +STATE = Path(os.environ.get("ARE_STATE_DIR", "/var/lib/are")) +ARTIFACT_PATHS = [p for p in os.environ.get("ARE_ARTIFACT_PATHS", "/app/output").split(":") if p] +# The shared deliverable volume. Its parent is root-only, so submitted code (which every +# task grader runs as the unprivileged agent user) cannot reach it to write back to the agent. +SUBMISSION_ROOT = Path(os.environ.get("ARE_SUBMISSION_ROOT", "/run/are-deliverable")) +AGENT_UID = int(os.environ.get("ARE_AGENT_UID", "1001")) +BUDGET_SEC = float(os.environ.get("ARE_BUDGET_SEC", "14400")) +GRADE_TIMEOUT_SEC = float(os.environ.get("ARE_GRADE_TIMEOUT_SEC", "1800")) +TEST_GRADER_URL = os.environ.get("ARE_TEST_GRADER_URL", "http://test-grader:8001") +FEEDBACK_TAIL = int(os.environ.get("ARE_FEEDBACK_TAIL_CHARS", "8192")) +SCRIPT = "/tests/intermediate.sh" if ROLE == "val" else "/tests/test.sh" +# Shared only by the two graders (a volume the agent's container never mounts). The test +# grader writes a fresh token at startup; every internal request must carry it, so the +# agent cannot reach the test grader or the internal endpoints even on a shared network. +TOKEN_FILE = Path(os.environ.get("ARE_TOKEN_FILE", "/run/are-secret/token")) +TOKEN = "" + + +def _authorized(request: Request) -> bool: + """Internal endpoints need the graders' token; an unset token never matches.""" + return bool(TOKEN) and secrets.compare_digest(request.headers.get("x-are-token", ""), TOKEN) + + +def _net_isolation_available() -> bool: + try: + return subprocess.run(["unshare", "-n", "true"], capture_output=True, timeout=10).returncode == 0 + except Exception: + return False + + +NET_ISOLATED = False # set at startup: grader scripts run in an empty network namespace + +T0 = time.time() +_lock = threading.Lock() + + +def _elapsed() -> float: + return round(time.time() - T0, 1) + + +def _ledger(event: dict) -> None: + event = {"t": _elapsed(), "wall": time.time(), **event} + for attempt in range(3): + try: + with _lock, open(STATE / "ledger.jsonl", "a") as fh: + fh.write(json.dumps(event) + "\n") + return + except OSError: + if attempt == 2: + raise + time.sleep(1) + + +def _kill_grading_processes(proc: subprocess.Popen) -> None: + """Kill everything a timed-out grade started, including processes that left its group.""" + try: + os.killpg(proc.pid, 9) + except ProcessLookupError: + pass + _kill_other_processes() + + +def _kill_other_processes() -> None: + """Kill every process run by the agent user. Every task grader runs submitted code as + that user, so this stops all graded code (detached or not) and nothing else: the grader + server, the task's own grader and Harbor's hooks run as root.""" + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + if entry.stat().st_uid == AGENT_UID: + os.kill(int(entry.name), 9) + except (ProcessLookupError, PermissionError, FileNotFoundError): + pass + + +# Places the agent user (who runs submitted code inside every task grader) can write. +_BASELINE: set[str] = set() # every path that existed when the grader started (its image) + + +def _walk_one_fs(base: Path): + """Every path under base on base's own filesystem (skips /proc, /sys and other mounts).""" + dev = base.stat().st_dev + for root, dirs, files in os.walk(base): + dirs[:] = [d for d in dirs if os.lstat(os.path.join(root, d)).st_dev == dev] + for name in dirs + files: + yield Path(root) / name + + +def _all_paths() -> set[str]: + out = set() + for base in (Path("/"), Path("/dev/shm")): + if base.is_dir(): + out.update(str(q) for q in _walk_one_fs(base)) + return out + + +def _protected(path: str) -> bool: + keep = [str(STATE), "/opt/are", str(TOKEN_FILE.parent)] + return any(path == k or path.startswith(k + "/") for k in keep) + + +def _fresh_state() -> None: + """Start every grade from the grader image's own files, as ARE 1.0's fresh verifier + container did. The grader container lives for the whole run, so before each grade + stop anything an earlier grade left running and delete every file it created, + whoever wrote it. The deliverable volume and the token are separate mounts and are + never walked; the grader's own state is kept.""" + _kill_other_processes() + # System V shared memory, semaphores and queues outlive processes; this server uses none. + subprocess.run(["ipcrm", "--all"], capture_output=True) + for path in sorted(_all_paths() - _BASELINE, key=lambda q: q.count("/"), reverse=True): + if _protected(path): + continue + try: + q = Path(path) + if q.is_dir() and not q.is_symlink(): + shutil.rmtree(q, ignore_errors=True) + else: + q.unlink() + except OSError: + pass + + +def grade_snapshot(tar_bytes: bytes, tag: str) -> dict: + """Extract a snapshot over the artifact paths and run this role's grader script.""" + _fresh_state() + for path in ARTIFACT_PATHS: + p = Path(path) + if p.exists(): + shutil.rmtree(p) + p.mkdir(parents=True) + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:gz") as tf: + tf.extractall("/", filter="tar") + logs = Path("/logs/verifier") + if logs.exists(): + shutil.rmtree(logs) + logs.mkdir(parents=True) + started = time.time() + # Submitted code runs with no network, as in ARE 1.0's verifier. + cmd = (["unshare", "-n"] if NET_ISOLATED else []) + ["bash", SCRIPT] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + cwd="/tests", start_new_session=True) + try: + out, err = proc.communicate(timeout=GRADE_TIMEOUT_SEC) + error = None + except subprocess.TimeoutExpired: + _kill_grading_processes(proc) + out, err = proc.communicate() + error = f"grader timed out after {GRADE_TIMEOUT_SEC:.0f}s" + output = (out or "") + (err or "") + # Nothing a grade started may keep running after it, not even detached processes. + _kill_other_processes() + score = 0.0 + reward_file = logs / "reward.txt" + if reward_file.exists(): + try: + score = float(reward_file.read_text().strip() or 0) + except ValueError: + error = error or "unparseable reward" + metric = None + if (logs / "metric.json").exists(): + try: + metric = json.loads((logs / "metric.json").read_text()) + except ValueError: + pass + (STATE / "logs").mkdir(exist_ok=True) + (STATE / "logs" / f"{tag}.log").write_text(output) + return { + "score": score, + "metric": metric, + "error": error, + "net_isolated": NET_ISOLATED, + "seconds": round(time.time() - started, 1), + # What the agent sees, as in ARE 1.0: the grader's stdout tail (not stderr). + "output_tail": (out or "")[-FEEDBACK_TAIL:], + } + + +mcp = FastMCP("are") + + +# ---------------------------------------------------------------- test role + + +_grade_lock = threading.Lock() + + +def _grade_one_at_a_time(tar_bytes: bytes, tag: str) -> dict: + # A request that timed out on the caller's side may still be grading; the next one + # waits for it rather than sharing /app/output and /logs/verifier with it. + with _grade_lock: + return grade_snapshot(tar_bytes, tag) + + +if ROLE == "test": + + @mcp.custom_route("/grade", methods=["POST"]) + async def http_grade(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + tag = request.query_params.get("tag", "x") + body = await request.body() + result = await asyncio.to_thread(_grade_one_at_a_time, body, f"{tag}-test") + return JSONResponse(result) + + +# ----------------------------------------------------------------- val role + + +class Board: + """Submissions and their grading state. Hidden scores are never stored here.""" + + def __init__(self) -> None: + self.subs: dict[int, dict] = {} + self.val_q: queue.Queue[int] = queue.Queue() + self.next_id = 1 + self.test_pending = 0 + self.last_digest: str | None = None + + def public(self, sid: int) -> dict: + s = self.subs[sid] + out = {k: s[k] for k in ("id", "note", "submitted_at_s", "status")} + if s["status"] == "graded": + v = s["val"] + out.update( + validation_score=v["score"], + error=v["error"], + grading_seconds=v["seconds"], + grader_output_tail=v["output_tail"], + ) + return out + + def best(self) -> dict | None: + graded = [s for s in self.subs.values() if s["status"] == "graded"] + if not graded: + return None + b = max(graded, key=lambda s: (s["val"]["score"], -s["id"])) + return {"id": b["id"], "validation_score": b["val"]["score"]} + + +board = Board() + + +def snapshot() -> bytes: + """Deterministic tar.gz of the deliverable: same content, same bytes (gzip mtime 0).""" + raw = io.BytesIO() + with tarfile.open(fileobj=raw, mode="w") as tf: + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + tf.add(str(src), arcname=path.lstrip("/")) + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as gz: + gz.write(raw.getvalue()) + return out.getvalue() + + +def do_submit(note: str, final: bool = False) -> dict: + with _lock: + pending = [s["id"] for s in board.subs.values() if s["status"] != "graded"] + if pending and not final: + return { + "error": f"Submission {pending[0]} is still being graded. One submission is " + f"graded at a time: check result({pending[0]}) and submit again " + "once it has its score.", + "pending_id": pending[0], + } + sid = board.next_id + board.next_id += 1 + board.subs[sid] = {"id": sid, "note": note[:500], "submitted_at_s": _elapsed(), + "status": "queued"} + try: + data = snapshot() + digest = hashlib.sha256(data).hexdigest() + (STATE / "snapshots" / f"{sid:04d}.tar.gz").write_bytes(data) + _ledger({"event": "submitted", "id": sid, "note": note[:500], "bytes": len(data), + "sha256": digest, "final": final}) + except Exception as exc: + with _lock: + board.subs.pop(sid, None) # release the slot; the id is not reused + return {"error": f"Could not snapshot the deliverable ({exc}). Nothing was submitted. " + "Make sure nothing is writing to it, then submit again."} + board.last_digest = digest + with _lock: + board.test_pending += 1 + board.val_q.put(sid) + return {"id": sid, "status": "queued", + "hint": "Grading has started. Check result(id) for the validation score."} + + +def final_submit() -> dict: + """After the agent stops: grade the final workspace unless it was already submitted.""" + try: + data = snapshot() + except Exception as exc: + return {"error": f"final snapshot failed: {exc}"} + if board.subs and hashlib.sha256(data).hexdigest() == board.last_digest: + return {"skipped": "final workspace equals the last submission"} + return do_submit("final workspace (automatic)", final=True) + + +def grade_worker() -> None: + """Grade each submission on val, then on test, one submission at a time. + + The val score is published as soon as it is ready. The next submission's val grade + waits until this test grade is done, so the two graders never run at the same time. + """ + while True: + sid = board.val_q.get() + board.subs[sid]["status"] = "grading" + data = b"" + try: + data = (STATE / "snapshots" / f"{sid:04d}.tar.gz").read_bytes() + res = grade_snapshot(data, f"{sid:04d}-val") + except Exception as exc: + res = {"score": 0.0, "metric": None, "error": f"grader failed: {exc}", + "net_isolated": NET_ISOLATED, "seconds": 0.0, "output_tail": ""} + board.subs[sid]["val"] = res + board.subs[sid]["status"] = "graded" + try: + _ledger({"event": "val", "id": sid, **{k: res[k] for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + test_grade(sid, data) + + +def test_grade(sid: int, data: bytes) -> None: + try: + _test_grade(sid, data) + finally: + with _lock: + board.test_pending -= 1 + + +def _test_grade(sid: int, data: bytes) -> None: + """Send one snapshot to the test grader. A failed request is retried (the same snapshot + is graded again, so a retry can only recover the honest score); a request that ran + past its timeout is not, since the grade itself already took the full time.""" + started = time.time() + for attempt in range(3): + try: + req = urllib.request.Request( + f"{TEST_GRADER_URL}/grade?tag={sid:04d}", data=data, method="POST", + headers={"x-are-token": TOKEN}, + ) + with urllib.request.urlopen(req, timeout=2 * GRADE_TIMEOUT_SEC + 300) as resp: + res = json.loads(resp.read()) + break + except Exception as exc: # recorded, never shown to the agent + res = {"score": None, "metric": None, "error": f"test grader: {exc}", + "seconds": round(time.time() - started, 1)} + if attempt == 2 or isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError): + break + time.sleep(5) + try: + _ledger({"event": "test", "id": sid, **{k: res.get(k) for k in ("score", "metric", "error", "seconds", "net_isolated")}}) + except OSError as exc: # keep grading later submissions + print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True) + + +def with_time(out: dict) -> dict: + """Wall-clock accounting on every reply, as the v1 harness gave each phase.""" + out["total_budget_seconds"] = BUDGET_SEC + out["time_remaining_seconds"] = round(max(0.0, BUDGET_SEC - _elapsed()), 1) + return out + + +def status_dict() -> dict: + return { + "submissions": len(board.subs), + "queued_or_grading": sum(s["status"] != "graded" for s in board.subs.values()), + "best": board.best(), + } + + +def current_result(sid: int) -> dict: + return board.public(sid) + + +if ROLE == "val": + + @mcp.tool + async def submit(note: str = "") -> dict: + """Submit the current deliverable for grading. + + Snapshots the deliverable directory right now (later edits do not affect this + submission) and starts grading it on the public validation split. Returns at + once with a submission id. One submission is graded at a time: check `result` + and submit again once the previous submission has its score. `note` is a short + description of what changed. + """ + return with_time(await asyncio.to_thread(do_submit, note)) + + @mcp.tool + async def result(id: int) -> dict: + """The current state of a submission: queued, grading, or graded with its + validation score and grader output. Returns immediately.""" + if id not in board.subs: + return {"error": f"unknown submission id {id}"} + return with_time(current_result(id)) + + @mcp.tool + async def status() -> dict: + """Submission count, whether one is being graded, the best validation score, + and the time budget and time remaining.""" + return with_time(status_dict()) + + @mcp.custom_route("/submit", methods=["POST"]) + async def http_submit(request: Request) -> Response: + note = request.query_params.get("note", "") + return JSONResponse(with_time(await asyncio.to_thread(do_submit, note))) + + @mcp.custom_route("/result/{sid}", methods=["GET"]) + async def http_result(request: Request) -> Response: + sid = int(request.path_params["sid"]) + if sid not in board.subs: + return JSONResponse({"error": f"unknown submission id {sid}"}, status_code=404) + return JSONResponse(with_time(current_result(sid))) + + @mcp.custom_route("/status", methods=["GET"]) + async def http_status(request: Request) -> Response: + return JSONResponse(with_time(status_dict())) + + @mcp.custom_route("/final", methods=["POST"]) + async def http_final(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Collect hook, after the agent has stopped. + return JSONResponse(await asyncio.to_thread(final_submit)) + + @mcp.custom_route("/drain", methods=["GET"]) + async def http_drain(request: Request) -> Response: + if not _authorized(request): + return JSONResponse({"error": "forbidden"}, status_code=403) + # Used by the verifier collect hook after the agent has stopped. + pending = sum(s["status"] != "graded" for s in board.subs.values()) + return JSONResponse({"val_pending": pending, "test_pending": board.test_pending}) + + +def _gpus() -> list[str]: + try: + out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=20) + return [l for l in out.stdout.splitlines() if l.strip()] + except Exception: + return [] + + +@mcp.custom_route("/health", methods=["GET"]) +async def health(request: Request) -> Response: + return JSONResponse({"ok": True, "role": ROLE, "gpus": await asyncio.to_thread(_gpus)}) + + +def _setup_token() -> None: + global TOKEN + if ROLE == "test": + TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True) + os.chmod(TOKEN_FILE.parent, 0o700) + TOKEN = secrets.token_hex(32) + TOKEN_FILE.write_text(TOKEN) + os.chmod(TOKEN_FILE, 0o600) + else: + for _ in range(300): # the test grader is healthy before this one starts + if TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip(): + break + time.sleep(1) + TOKEN = TOKEN_FILE.read_text().strip() + if not TOKEN: + raise SystemExit("ARE: empty internal token; refusing to start") + + +def main() -> None: + global NET_ISOLATED + NET_ISOLATED = _net_isolation_available() + if not NET_ISOLATED: + # Graded code must never have a network path (for example back through /submit). + raise SystemExit("ARE grader: cannot run grades without network access " + "(needs `unshare -n`, i.e. CAP_SYS_ADMIN); refusing to start") + STATE.mkdir(parents=True, exist_ok=True) + _BASELINE.update(_all_paths()) + _setup_token() + STATE.mkdir(parents=True, exist_ok=True) + os.chmod(STATE, 0o700) + (STATE / "snapshots").mkdir(exist_ok=True) + if ROLE == "val": + # The deliverable volume starts empty and root-owned; hand it to the agent user. + SUBMISSION_ROOT.mkdir(parents=True, exist_ok=True) + os.chmod(SUBMISSION_ROOT, 0o700) + for path in ARTIFACT_PATHS: + src = SUBMISSION_ROOT / path.lstrip("/") + src.mkdir(parents=True, exist_ok=True) + os.chown(src, AGENT_UID, AGENT_UID) + (STATE / "meta.json").write_text(json.dumps( + {"t0_wall": T0, "budget_seconds": BUDGET_SEC, "artifact_paths": ARTIFACT_PATHS} + )) + threading.Thread(target=grade_worker, daemon=True).start() + mcp.run(transport="http", host="0.0.0.0", port=PORT, show_banner=False, + uvicorn_config={"timeout_keep_alive": 86400}) + + +if __name__ == "__main__": + main() diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/compute_reward.py b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..54501469dc5d13d792fb0b43fb9c9875e26c9f7d --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,17 @@ +import json +import math +from pathlib import Path + +REWARD_PATH = Path("/logs/verifier/reward.txt") + +try: + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + value = float(json.loads(Path("/logs/verifier/metric.json").read_text())["reward"]) + if not math.isfinite(value): + raise ValueError("non-finite reward") + reward = f"{min(1.0, max(0.0, value)):.12g}" + REWARD_PATH.write_text(reward + "\n") + print(f"reward={reward}") +except Exception as exc: + REWARD_PATH.write_text("0\n") + print(f"reward=0 (fallback: {exc})") diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/grader_core.py b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..2d6bc7ed1e52f63a786c71abd8b6cab8cbaa5203 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import json +import math +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import panel + +ALPHA = 0.10 +REPLICATIONS = 2000 +COVERAGE_GATE = 0.88 +PER_CALL_CAP_SEC = 2.0 + +M0 = 0.0593 +M_REF = 0.0095 + + +def graded_reward(metric: float | None) -> float: + """Map the metric (lower is better) to a reward in [0, 1]. + + Two-anchor log-ratio squash on the improvement factor rho = M0 / metric: + u = max(0, log(rho)) / log(M0 / M_REF), reward = u / (1 + u). + The strongest degenerate predictor earns exactly 0, anything worse also earns 0, + the reference construction earns about 0.5, and the reward keeps rising without a + cutoff, approaching 1 asymptotically. + """ + if metric is None or not math.isfinite(metric): + return 0.0 + if metric <= 1e-12: + return 1.0 + rho = M0 / metric + if rho <= 1.0: + return 0.0 + u = math.log(rho) / math.log(M0 / M_REF) + return u / (1.0 + u) + + + + +def load_panel(directory: str | Path) -> dict: + doc = json.loads((Path(directory) / "panel.json").read_text()) + return doc + + +def replication_rngs(master_seed: int, setting_index: int, rep: int): + """Deterministic (data rng, candidate seed) for one replication.""" + data_ss = np.random.SeedSequence(entropy=master_seed, spawn_key=(setting_index, rep, 0)) + cand_ss = np.random.SeedSequence(entropy=master_seed, spawn_key=(setting_index, rep, 1)) + cand_seed = int(cand_ss.generate_state(1, dtype=np.uint32)[0]) + return np.random.default_rng(data_ss), cand_seed + + +def theta_only(spec: dict, master_seed: int, setting_index: int, rep: int) -> float: + """The true squared calibration error of a replication, without drawing its data.""" + rng, _ = replication_rngs(master_seed, setting_index, rep) + return float(panel.theta_for(spec, rng)) + + +def make_replication(spec: dict, master_seed: int, setting_index: int, rep: int): + """Draw one replication: returns (Z, Y, theta_true, candidate_seed).""" + rng, cand_seed = replication_rngs(master_seed, setting_index, rep) + theta = panel.theta_for(spec, rng) + Z, Y = panel.draw_replication(spec, theta, rng) + return Z, Y, float(theta), cand_seed + + + + +def _length_and_cover(entry, k: int, theta: float): + """Relative-length contribution and coverage flag for one replication. + + Any invalid outcome - a failed import, an exception, a timeout, a non-finite or + mis-ordered return, or a value outside [0, k] - contributes the trivial length k + and does not cover. + """ + if not isinstance(entry, dict) or entry.get("status") != "ok": + return float(k), False, entry.get("status", "missing") if isinstance(entry, dict) else "missing" + lo, hi = entry.get("lo"), entry.get("hi") + if not (isinstance(lo, (int, float)) and isinstance(hi, (int, float))): + return float(k), False, "not_a_number" + lo, hi = float(lo), float(hi) + if not (math.isfinite(lo) and math.isfinite(hi)): + return float(k), False, "non_finite" + if not (0.0 <= lo <= hi <= float(k)): + return float(k), False, "out_of_range" + return hi - lo, bool(lo <= theta <= hi), "ok" + + +def score_panel(settings: list[dict], thetas: dict, results: dict, replications: int) -> dict: + """Aggregate per-setting coverage and relative length into the metric. + + `results[(si, rep)]` is the dict a candidate call produced (or is missing). + """ + per_setting = [] + status_counts: dict[str, int] = {} + for si, spec in enumerate(settings): + k = int(spec["k"]) + total_len = 0.0 + covered = 0 + for rep in range(replications): + entry = results.get((si, rep)) + length, cover, status = _length_and_cover(entry, k, thetas[(si, rep)]) + total_len += length + covered += int(cover) + status_counts[status] = status_counts.get(status, 0) + 1 + coverage = covered / replications + rel_len = total_len / (replications * k) + valid = coverage >= COVERAGE_GATE + per_setting.append( + { + "index": si, + "coverage": coverage, + "relative_length": rel_len, + "coverage_gate_met": bool(valid), + "score": rel_len if valid else 1.0, + } + ) + metric = float(np.mean([s["score"] for s in per_setting])) + return { + "metric": metric, + "per_setting": per_setting, + "status_counts": status_counts, + "replications": replications, + "coverage_gate": COVERAGE_GATE, + } diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/hidden_data/final/panel.json b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/hidden_data/final/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..507b6105ae8efe478f490680c77f174846f41bc8 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/hidden_data/final/panel.json @@ -0,0 +1,575 @@ +{ + "master_seed": 424242002, + "settings": [ + { + "id": "s08", + "K": 5, + "k": 3, + "n": 10000, + "z_family": { + "kind": "logitnormal", + "w_unif": 0.4243, + "mu": [ + 1.7395, + 0.2585, + -0.6922, + 2.9611, + -0.3482 + ], + "sigma": 1.5137 + }, + "pert": { + "kind": "fourier", + "sign": [ + -1.0, + 1.0, + -1.0 + ], + "freq": [ + [ + 0.277, + 1.2764, + -0.9554 + ], + [ + 1.3725, + -0.1977, + -0.9869 + ], + [ + 1.1711, + 0.5377, + -0.1804 + ] + ], + "phase": [ + 0.0121, + 0.0072, + 0.9607 + ] + }, + "A": 0.3011769533901411, + "A_se": 8.990401601359815e-05, + "theta_grid": [ + 0.039967071538931566, + 0.04196542511587814, + 0.04396377869282472, + 0.0459621322697713, + 0.047960485846717874, + 0.049958839423664456, + 0.05195719300061103, + 0.053955546577557606, + 0.05595390015450419, + 0.05795225373145077, + 0.059950607308397345, + 0.06194896088534392, + 0.0639473144622905, + 0.06594566803923707, + 0.06794402161618365, + 0.06994237519313024, + 0.07194072877007682, + 0.07393908234702339, + 0.07593743592396997, + 0.07793578950091654, + 0.07993414307786312, + 0.0819324966548097, + 0.08393085023175628, + 0.08592920380870286, + 0.08792755738564943, + 0.089925910962596, + 0.09192426453954258, + 0.09392261811648916, + 0.09592097169343575, + 0.09791932527038233, + 0.0999176788473289, + 0.10191603242427548, + 0.10391438600122205, + 0.10591273957816863, + 0.10791109315511521, + 0.1099094467320618, + 0.11190780030900838, + 0.11390615388595493, + 0.11590450746290151, + 0.1179028610398481, + 0.11990121461679469 + ], + "sigma0": 0.07530679767583752, + "region_volume": 0.021839916666666667, + "fast_scale": 0.001998353576946578, + "regime": "high", + "ref_bin_side": 35 + }, + { + "id": "s09", + "K": 5, + "k": 1, + "n": 2000, + "z_family": { + "kind": "dirichlet_sparse", + "w_unif": 0.3813, + "alpha": [ + 0.1755, + 0.2933, + 0.321, + 0.3133, + 0.4387 + ] + }, + "pert": { + "kind": "mono", + "sign": [ + -1.0 + ], + "b": [ + 2.7578 + ], + "c": [ + 0.4266 + ] + }, + "A": 0.21603574603552408, + "A_se": 7.922324290636855e-05, + "theta_grid": [ + 0.0, + 0.0001737288856163897, + 0.0003474577712327794, + 0.0005211866568491691, + 0.0006949155424655589, + 0.0008686444280819486, + 0.0010423733136983382, + 0.001216102199314728, + 0.0013898310849311177, + 0.0015635599705475073, + 0.0017372888561638972, + 0.0019110177417802868, + 0.0020847466273966764, + 0.0022584755130130663, + 0.002432204398629456, + 0.0026059332842458456, + 0.0027796621698622354, + 0.0029533910554786253, + 0.0031271199410950147, + 0.0033008488267114045, + 0.0034745777123277944, + 0.0036483065979441838, + 0.0038220354835605736, + 0.003995764369176963, + 0.004169493254793353, + 0.004343222140409743, + 0.004516951026026133, + 0.0046906799116425224, + 0.004864408797258912, + 0.005038137682875301, + 0.005211866568491691, + 0.005385595454108081, + 0.005559324339724471, + 0.005733053225340861, + 0.0059067821109572505, + 0.00608051099657364, + 0.006254239882190029, + 0.006427968767806419, + 0.006601697653422809, + 0.006775426539039199, + 0.006949155424655589 + ], + "sigma0": 0.2506530613159527, + "region_volume": 0.8003755, + "fast_scale": 0.0011581925707759315, + "regime": "low", + "ref_bin_side": 52 + }, + { + "id": "s10", + "K": 5, + "k": 2, + "n": 2000, + "z_family": { + "kind": "logitnormal", + "w_unif": 0.3477, + "mu": [ + 0.0129, + -0.7774, + -0.8517, + -0.2735, + -0.1584 + ], + "sigma": 1.6526 + }, + "pert": { + "kind": "fourier", + "sign": [ + -1.0, + -1.0 + ], + "freq": [ + [ + 1.4078, + 1.1415 + ], + [ + 0.9354, + -0.8707 + ] + ], + "phase": [ + 0.6063, + 0.5918 + ] + }, + "A": 0.035488287475108495, + "A_se": 1.3538823147367263e-05, + "theta_grid": [ + 0.0, + 0.0006103059111362515, + 0.001220611822272503, + 0.0018309177334087546, + 0.002441223644545006, + 0.003051529555681258, + 0.003661835466817509, + 0.0042721413779537604, + 0.004882447289090012, + 0.005492753200226264, + 0.006103059111362516, + 0.0067133650224987665, + 0.007323670933635018, + 0.007933976844771269, + 0.008544282755907521, + 0.009154588667043773, + 0.009764894578180024, + 0.010375200489316276, + 0.010985506400452528, + 0.01159581231158878, + 0.012206118222725031, + 0.012816424133861281, + 0.013426730044997533, + 0.014037035956133785, + 0.014647341867270037, + 0.015257647778406288, + 0.015867953689542538, + 0.01647825960067879, + 0.017088565511815042, + 0.017698871422951293, + 0.018309177334087545, + 0.018919483245223797, + 0.01952978915636005, + 0.0201400950674963, + 0.020750400978632552, + 0.021360706889768804, + 0.021971012800905056, + 0.022581318712041307, + 0.02319162462317756, + 0.02380193053431381, + 0.024412236445450063 + ], + "sigma0": 0.2048276270245583, + "region_volume": 0.210011, + "fast_scale": 0.004068706074241677, + "regime": "low", + "ref_bin_side": 31 + }, + { + "id": "s06", + "K": 3, + "k": 1, + "n": 10000, + "z_family": { + "kind": "logitnormal", + "w_unif": 0.3403, + "mu": [ + 0.1211, + 0.3651, + -0.5537 + ], + "sigma": 1.4558 + }, + "pert": { + "kind": "fourier", + "sign": [ + 1.0 + ], + "freq": [ + [ + -0.8121 + ] + ], + "phase": [ + 0.7061 + ] + }, + "A": 0.12132542294787756, + "A_se": 3.3642046320104586e-05, + "theta_grid": [ + 0.0017649367256828852, + 0.001867891368014387, + 0.0019708460103458887, + 0.00207380065267739, + 0.0021767552950088917, + 0.0022797099373403932, + 0.002382664579671895, + 0.0024856192220033967, + 0.002588573864334898, + 0.0026915285066664, + 0.0027944831489979016, + 0.002897437791329403, + 0.003000392433660905, + 0.0031033470759924066, + 0.003206301718323908, + 0.00330925636065541, + 0.0034122110029869116, + 0.003515165645318413, + 0.003618120287649915, + 0.0037210749299814165, + 0.003824029572312918, + 0.00392698421464442, + 0.004029938856975921, + 0.004132893499307423, + 0.004235848141638925, + 0.004338802783970426, + 0.004441757426301928, + 0.00454471206863343, + 0.004647666710964931, + 0.004750621353296433, + 0.004853575995627935, + 0.004956530637959436, + 0.005059485280290938, + 0.00516243992262244, + 0.005265394564953941, + 0.005368349207285443, + 0.005471303849616945, + 0.005574258491948446, + 0.005677213134279948, + 0.00578016777661145, + 0.005883122418942951 + ], + "sigma0": 0.22953124076762743, + "region_volume": 0.666585, + "fast_scale": 0.00029415612094714754, + "regime": "mid", + "ref_bin_side": 100 + }, + { + "id": "s05", + "K": 3, + "k": 2, + "n": 500, + "z_family": { + "kind": "logitnormal", + "w_unif": 0.287, + "mu": [ + -0.6317, + -0.5316, + 0.0428 + ], + "sigma": 1.6895 + }, + "pert": { + "kind": "mono", + "sign": [ + -1.0, + 1.0 + ], + "b": [ + 5.6775, + 3.1757 + ], + "c": [ + 0.5226, + 0.8486 + ] + }, + "A": 0.37866111406380726, + "A_se": 0.00010686538994703823, + "theta_grid": [ + 0.054240197370597196, + 0.057404208883882035, + 0.06056822039716687, + 0.06373223191045171, + 0.06689624342373654, + 0.07006025493702138, + 0.07322426645030622, + 0.07638827796359106, + 0.0795522894768759, + 0.08271630099016072, + 0.08588031250344556, + 0.0890443240167304, + 0.09220833553001524, + 0.09537234704330008, + 0.09853635855658491, + 0.10170037006986975, + 0.10486438158315459, + 0.10802839309643943, + 0.11119240460972427, + 0.11435641612300909, + 0.11752042763629393, + 0.12068443914957877, + 0.12384845066286361, + 0.12701246217614845, + 0.1301764736894333, + 0.13334048520271813, + 0.13650449671600295, + 0.13966850822928778, + 0.14283251974257263, + 0.1459965312558575, + 0.1491605427691423, + 0.15232455428242714, + 0.15548856579571196, + 0.15865257730899682, + 0.16181658882228167, + 0.1649806003355665, + 0.16814461184885132, + 0.17130862336213615, + 0.174472634875421, + 0.17763664638870585, + 0.18080065790199065 + ], + "sigma0": 0.17634937871692144, + "region_volume": 0.13893075, + "fast_scale": 0.009040032895099533, + "regime": "mid", + "ref_bin_side": 20 + }, + { + "id": "s04", + "K": 50, + "k": 3, + "n": 2000, + "z_family": { + "kind": "logitnormal", + "w_unif": 0.3386, + "mu": [ + -0.5162, + -0.3077, + -0.0915, + 1.0738, + -1.4862, + -0.097, + -1.3919, + 0.1632, + 0.6965, + 1.6474, + -0.0566, + -1.442, + -0.1812, + -0.1148, + 0.241, + 0.0782, + -0.7595, + 0.227, + -0.3292, + -1.1795, + -0.0578, + -0.1771, + -0.0932, + 0.8326, + -0.5224, + 0.2237, + -0.7205, + 1.1674, + -0.2521, + -0.3124, + 0.5067, + 0.4601, + -2.0911, + 0.8246, + 0.3563, + -0.9799, + 0.4667, + -0.2132, + 1.2873, + 0.3487, + -0.4711, + 0.1974, + 0.4042, + 0.0624, + -0.422, + -0.5466, + 0.6929, + 0.0363, + 0.9233, + -1.2884 + ], + "sigma": 5.6217 + }, + "pert": { + "kind": "fourier", + "sign": [ + -1.0, + -1.0, + -1.0 + ], + "freq": [ + [ + 0.5679, + -0.848, + 0.0108 + ], + [ + -1.4672, + 0.7814, + 1.0336 + ], + [ + -0.579, + 0.552, + -0.1469 + ] + ], + "phase": [ + 0.8318, + 0.3887, + 0.1696 + ] + }, + "A": 0.2658506114727243, + "A_se": 0.00010871253666267831, + "theta_grid": [ + 0.031618964252479086, + 0.0334634038338737, + 0.03530784341526831, + 0.03715228299666293, + 0.03899672257805754, + 0.04084116215945215, + 0.04268560174084676, + 0.04453004132224138, + 0.046374480903635995, + 0.04821892048503061, + 0.05006336006642522, + 0.05190779964781983, + 0.053752239229214446, + 0.05559667881060906, + 0.05744111839200368, + 0.05928555797339829, + 0.0611299975547929, + 0.06297443713618751, + 0.06481887671758213, + 0.06666331629897673, + 0.06850775588037136, + 0.07035219546176597, + 0.07219663504316058, + 0.0740410746245552, + 0.0758855142059498, + 0.07772995378734443, + 0.07957439336873903, + 0.08141883295013365, + 0.08326327253152827, + 0.08510771211292287, + 0.0869521516943175, + 0.0887965912757121, + 0.09064103085710672, + 0.09248547043850133, + 0.09432991001989594, + 0.09617434960129057, + 0.09801878918268517, + 0.09986322876407977, + 0.1017076683454744, + 0.103552107926869, + 0.10539654750826362 + ], + "sigma0": 0.07969962502807346, + "region_volume": 0.0277425, + "fast_scale": 0.005269827375413181, + "regime": "mid", + "ref_bin_side": 22 + } + ] +} \ No newline at end of file diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/hidden_data/intermediate/panel.json b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/hidden_data/intermediate/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..0856ec9281e31c63f752001e81630dba8b0e0867 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/hidden_data/intermediate/panel.json @@ -0,0 +1,610 @@ +{ + "master_seed": 424242001, + "settings": [ + { + "id": "s11", + "K": 2, + "k": 1, + "n": 10000, + "z_family": { + "kind": "dirichlet", + "w_unif": 0.4878, + "alpha": [ + 1.8528, + 1.0515 + ] + }, + "pert": { + "kind": "mixed", + "sign": [ + -1.0 + ], + "b": [ + 6.98 + ], + "c": [ + 0.1873 + ], + "freq": [ + [ + -0.9939 + ] + ], + "phase": [ + 0.3621 + ] + }, + "A": 0.28368569049515535, + "A_se": 8.068139008595342e-05, + "theta_grid": [ + 0.004677387718037825, + 0.004911257103939717, + 0.005145126489841608, + 0.005378995875743499, + 0.00561286526164539, + 0.0058467346475472816, + 0.006080604033449172, + 0.0063144734193510636, + 0.006548342805252955, + 0.006782212191154846, + 0.007016081577056738, + 0.007249950962958628, + 0.00748382034886052, + 0.007717689734762411, + 0.007951559120664302, + 0.008185428506566193, + 0.008419297892468085, + 0.008653167278369976, + 0.008887036664271868, + 0.009120906050173759, + 0.00935477543607565, + 0.009588644821977542, + 0.009822514207879432, + 0.010056383593781323, + 0.010290252979683214, + 0.010524122365585106, + 0.010757991751486997, + 0.010991861137388887, + 0.011225730523290779, + 0.01145959990919267, + 0.011693469295094561, + 0.011927338680996453, + 0.012161208066898344, + 0.012395077452800236, + 0.012628946838702127, + 0.012862816224604019, + 0.01309668561050591, + 0.0133305549964078, + 0.013564424382309691, + 0.013798293768211583, + 0.014032163154113474 + ], + "sigma0": 0.18248925145864694, + "region_volume": 0.499271, + "fast_scale": 0.00023386938590189125, + "regime": "high", + "ref_bin_side": 100 + }, + { + "id": "s03", + "K": 50, + "k": 1, + "n": 200, + "z_family": { + "kind": "dirichlet", + "w_unif": 0.3001, + "alpha": [ + 0.4223, + 0.4793, + 0.2221, + 0.3475, + 0.2387, + 0.3633, + 0.4965, + 0.1622, + 0.3972, + 0.4194, + 0.2028, + 0.1674, + 0.2841, + 0.1349, + 0.2818, + 0.4851, + 0.1652, + 0.3091, + 0.294, + 0.2298, + 0.4803, + 0.3303, + 0.2475, + 0.2658, + 0.2838, + 0.2915, + 0.1594, + 0.3056, + 0.3763, + 0.3467, + 0.3705, + 0.4196, + 0.2138, + 0.2197, + 0.2323, + 0.2252, + 0.4451, + 0.3273, + 0.2667, + 0.2913, + 0.4576, + 0.2736, + 0.2708, + 0.461, + 0.2681, + 0.2271, + 0.2054, + 0.1477, + 0.2764, + 0.3506 + ] + }, + "pert": { + "kind": "fourier", + "sign": [ + 1.0 + ], + "freq": [ + [ + -1.0538 + ] + ], + "phase": [ + 0.1611 + ] + }, + "A": 0.23555839768644987, + "A_se": 5.39890153486689e-05, + "theta_grid": [ + 0.0, + 0.001137199432324356, + 0.002274398864648712, + 0.0034115982969730677, + 0.004548797729297424, + 0.00568599716162178, + 0.0068231965939461355, + 0.007960396026270493, + 0.009097595458594848, + 0.010234794890919203, + 0.01137199432324356, + 0.012509193755567916, + 0.013646393187892271, + 0.014783592620216628, + 0.015920792052540985, + 0.01705799148486534, + 0.018195190917189696, + 0.01933239034951405, + 0.020469589781838406, + 0.021606789214162765, + 0.02274398864648712, + 0.023881188078811476, + 0.02501838751113583, + 0.026155586943460186, + 0.027292786375784542, + 0.0284299858081089, + 0.029567185240433256, + 0.03070438467275761, + 0.03184158410508197, + 0.032978783537406325, + 0.03411598296973068, + 0.035253182402055036, + 0.03639038183437939, + 0.03752758126670375, + 0.0386647806990281, + 0.03980198013135246, + 0.04093917956367681, + 0.04207637899600117, + 0.04321357842832553, + 0.044350777860649886, + 0.04548797729297424 + ], + "sigma0": 0.2581841860770113, + "region_volume": 0.979944, + "fast_scale": 0.007581329548829041, + "regime": "low", + "ref_bin_side": 21 + }, + { + "id": "s01", + "K": 10, + "k": 2, + "n": 200, + "z_family": { + "kind": "dirichlet", + "w_unif": 0.3717, + "alpha": [ + 1.3174, + 1.3872, + 0.9239, + 0.7544, + 1.3018, + 1.4937, + 1.1409, + 0.5614, + 1.298, + 0.4215 + ] + }, + "pert": { + "kind": "mono", + "sign": [ + 1.0, + 1.0 + ], + "b": [ + 2.8662, + 7.7452 + ], + "c": [ + 0.7777, + 0.1666 + ] + }, + "A": 0.023802935258912413, + "A_se": 3.024677443928444e-06, + "theta_grid": [ + 0.0, + 0.0005355660433255293, + 0.0010711320866510585, + 0.0016066981299765878, + 0.002142264173302117, + 0.0026778302166276463, + 0.0032133962599531756, + 0.003748962303278705, + 0.004284528346604234, + 0.004820094389929763, + 0.005355660433255293, + 0.005891226476580822, + 0.006426792519906351, + 0.0069623585632318805, + 0.00749792460655741, + 0.00803349064988294, + 0.008569056693208468, + 0.009104622736533997, + 0.009640188779859527, + 0.010175754823185057, + 0.010711320866510585, + 0.011246886909836114, + 0.011782452953161644, + 0.012318018996487174, + 0.012853585039812702, + 0.01338915108313823, + 0.013924717126463761, + 0.014460283169789291, + 0.01499584921311482, + 0.015531415256440348, + 0.01606698129976588, + 0.016602547343091408, + 0.017138113386416937, + 0.017673679429742465, + 0.018209245473067993, + 0.018744811516393525, + 0.019280377559719054, + 0.019815943603044582, + 0.020351509646370114, + 0.020887075689695642, + 0.02142264173302117 + ], + "sigma0": 0.21014307984681518, + "region_volume": 0.23961675, + "fast_scale": 0.020198189472453745, + "regime": "low", + "ref_bin_side": 15 + }, + { + "id": "s00", + "K": 10, + "k": 3, + "n": 2000, + "z_family": { + "kind": "dirichlet", + "w_unif": 0.3236, + "alpha": [ + 0.7203, + 0.6408, + 1.0308, + 1.3166, + 0.8034, + 0.9347, + 0.8276, + 1.2486, + 1.4434, + 0.7038 + ] + }, + "pert": { + "kind": "mono", + "sign": [ + -1.0, + -1.0, + -1.0 + ], + "b": [ + 5.5614, + 4.7767, + 3.4502 + ], + "c": [ + 0.464, + 0.3759, + 0.373 + ] + }, + "A": 0.01242784840091184, + "A_se": 1.0897006471425923e-05, + "theta_grid": [ + 0.0, + 0.0002796265890205164, + 0.0005592531780410328, + 0.0008388797670615491, + 0.0011185063560820655, + 0.001398132945102582, + 0.0016777595341230982, + 0.001957386123143615, + 0.002237012712164131, + 0.0025166393011846473, + 0.002796265890205164, + 0.00307589247922568, + 0.0033555190682461964, + 0.003635145657266713, + 0.00391477224628723, + 0.004194398835307746, + 0.004474025424328262, + 0.004753652013348778, + 0.005033278602369295, + 0.005312905191389812, + 0.005592531780410328, + 0.005872158369430844, + 0.00615178495845136, + 0.006431411547471877, + 0.006711038136492393, + 0.00699066472551291, + 0.007270291314533426, + 0.007549917903553942, + 0.00782954449257446, + 0.008109171081594976, + 0.008388797670615492, + 0.008668424259636008, + 0.008948050848656524, + 0.00922767743767704, + 0.009507304026697557, + 0.009786930615718073, + 0.01006655720473859, + 0.010346183793759105, + 0.010625810382779623, + 0.01090543697180014, + 0.011185063560820656 + ], + "sigma0": 0.07952868826654959, + "region_volume": 0.02705608333333333, + "fast_scale": 0.005258524847640615, + "regime": "low", + "ref_bin_side": 22 + }, + { + "id": "s07", + "K": 10, + "k": 1, + "n": 10000, + "z_family": { + "kind": "logitnormal", + "w_unif": 0.417, + "mu": [ + -0.5983, + -1.6036, + 0.0086, + 0.5413, + -0.2954, + -0.6088, + 0.6709, + 1.0987, + 0.2814, + 1.5618 + ], + "sigma": 2.1663 + }, + "pert": { + "kind": "mono", + "sign": [ + 1.0 + ], + "b": [ + 6.3267 + ], + "c": [ + 0.2522 + ] + }, + "A": 0.1628764947600675, + "A_se": 2.9599886511179304e-05, + "theta_grid": [ + 0.0019770025481029227, + 0.00209232769674226, + 0.0022076528453815972, + 0.0023229779940209345, + 0.0024383031426602714, + 0.0025536282912996086, + 0.002668953439938946, + 0.002784278588578283, + 0.00289960373721762, + 0.0030149288858569573, + 0.0031302540344962946, + 0.003245579183135632, + 0.003360904331774969, + 0.0034762294804143064, + 0.0035915546290536437, + 0.0037068797776929805, + 0.0038222049263323178, + 0.0039375300749716555, + 0.004052855223610992, + 0.004168180372250329, + 0.004283505520889666, + 0.004398830669529004, + 0.004514155818168341, + 0.004629480966807678, + 0.0047448061154470155, + 0.004860131264086352, + 0.00497545641272569, + 0.0050907815613650265, + 0.005206106710004365, + 0.005321431858643701, + 0.005436757007283038, + 0.0055520821559223756, + 0.005667407304561713, + 0.00578273245320105, + 0.005898057601840387, + 0.006013382750479725, + 0.006128707899119062, + 0.006244033047758399, + 0.006359358196397736, + 0.006474683345037073, + 0.00659000849367641 + ], + "sigma0": 0.25711054751339485, + "region_volume": 0.900073, + "fast_scale": 0.0003295004246838205, + "regime": "mid", + "ref_bin_side": 100 + }, + { + "id": "s02", + "K": 50, + "k": 2, + "n": 2000, + "z_family": { + "kind": "dirichlet", + "w_unif": 0.4859, + "alpha": [ + 0.385, + 0.3783, + 0.2613, + 0.1601, + 0.3942, + 0.2367, + 0.4174, + 0.1779, + 0.3254, + 0.2951, + 0.2968, + 0.4159, + 0.1578, + 0.4187, + 0.3256, + 0.1382, + 0.3024, + 0.2688, + 0.474, + 0.1947, + 0.4077, + 0.1387, + 0.3615, + 0.3051, + 0.321, + 0.4611, + 0.3687, + 0.2556, + 0.14, + 0.2014, + 0.2479, + 0.1763, + 0.2776, + 0.4165, + 0.3925, + 0.2495, + 0.2847, + 0.33, + 0.4898, + 0.3466, + 0.4379, + 0.4666, + 0.4191, + 0.481, + 0.3551, + 0.4029, + 0.2569, + 0.2656, + 0.1987, + 0.4551 + ] + }, + "pert": { + "kind": "fourier", + "sign": [ + -1.0, + 1.0 + ], + "freq": [ + [ + 1.3118, + 0.6525 + ], + [ + -1.2607, + 0.4396 + ] + ], + "phase": [ + 0.9013, + 0.4828 + ] + }, + "A": 0.12442805499071366, + "A_se": 6.4773795027943835e-06, + "theta_grid": [ + 0.02512681789459541, + 0.02659254893844681, + 0.02805827998229821, + 0.029524011026149606, + 0.030989742070001006, + 0.032455473113852405, + 0.033921204157703805, + 0.035386935201555204, + 0.036852666245406604, + 0.038318397289258004, + 0.0397841283331094, + 0.0412498593769608, + 0.0427155904208122, + 0.044181321464663595, + 0.045647052508515, + 0.047112783552366394, + 0.0485785145962178, + 0.05004424564006919, + 0.0515099766839206, + 0.05297570772777199, + 0.0544414387716234, + 0.05590716981547479, + 0.0573729008593262, + 0.05883863190317759, + 0.06030436294702898, + 0.06177009399088039, + 0.06323582503473178, + 0.06470155607858319, + 0.06616728712243458, + 0.06763301816628599, + 0.06909874921013738, + 0.07056448025398879, + 0.07203021129784018, + 0.07349594234169159, + 0.07496167338554298, + 0.07642740442939439, + 0.07789313547324578, + 0.07935886651709718, + 0.08082459756094858, + 0.08229032860479998, + 0.08375605964865138 + ], + "sigma0": 0.21082322775009082, + "region_volume": 0.2496525, + "fast_scale": 0.0041878029824325685, + "regime": "mid", + "ref_bin_side": 31 + } + ] +} \ No newline at end of file diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/intermediate.sh b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..92c69d62caf52f8190fcf8930cea9634abe1d38c --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +trap 'if [ ! -s /logs/verifier/reward.txt ]; then echo "0" > /logs/verifier/reward.txt; fi' EXIT + +chmod -R go-rwx /tests + +export GRADE_SPLIT=intermediate +cd /tests +/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +/usr/local/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/panel.py b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/panel.py new file mode 100644 index 0000000000000000000000000000000000000000..adb05af06ad883f53929cf0495cce01741de9a86 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/panel.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +import math + +import numpy as np + +Z_FAMILIES = ("dirichlet", "dirichlet_sparse", "logitnormal") +PERT_FAMILIES = ("mono", "fourier", "mixed") + + + + +def draw_z(spec: dict, n: int, rng: np.random.Generator) -> np.ndarray: + """Draw n rows of predicted probability vectors, shape (n, K), rows sum to 1.""" + K = int(spec["K"]) + fam = spec["z_family"] + w_unif = float(fam["w_unif"]) + is_unif = rng.random(n) < w_unif + out = np.empty((n, K), dtype=np.float64) + + n_u = int(is_unif.sum()) + if n_u: + out[is_unif] = rng.dirichlet(np.ones(K), size=n_u) + n_c = n - n_u + if n_c: + kind = fam["kind"] + if kind in ("dirichlet", "dirichlet_sparse"): + alpha = np.asarray(fam["alpha"], dtype=np.float64) + out[~is_unif] = rng.dirichlet(alpha, size=n_c) + elif kind == "logitnormal": + mu = np.asarray(fam["mu"], dtype=np.float64) + sigma = float(fam["sigma"]) + v = mu + sigma * rng.standard_normal((n_c, K)) + v -= v.max(axis=1, keepdims=True) + np.exp(v, out=v) + out[~is_unif] = v / v.sum(axis=1, keepdims=True) + else: + raise ValueError(f"unknown z family {kind!r}") + return out + + + + +def perturbation(spec: dict, zt: np.ndarray) -> np.ndarray: + """Smooth shape function h(z_(1:k)) with values in [0, 1], shape (n, k).""" + p = spec["pert"] + kind = p["kind"] + if kind == "mono": + b = np.asarray(p["b"], dtype=np.float64) + c = np.asarray(p["c"], dtype=np.float64) + return 0.5 * (1.0 + np.tanh(b * (zt - c))) + if kind == "fourier": + freq = np.asarray(p["freq"], dtype=np.float64) + phase = np.asarray(p["phase"], dtype=np.float64) + return 0.5 * (1.0 + np.sin(2.0 * np.pi * (zt @ freq.T + phase))) + if kind == "mixed": + b = np.asarray(p["b"], dtype=np.float64) + c = np.asarray(p["c"], dtype=np.float64) + freq = np.asarray(p["freq"], dtype=np.float64) + phase = np.asarray(p["phase"], dtype=np.float64) + mono = 0.5 * (1.0 + np.tanh(b * (zt - c))) + four = 0.5 * (1.0 + np.sin(2.0 * np.pi * (zt @ freq.T + phase))) + return 0.5 * mono + 0.5 * four + raise ValueError(f"unknown perturbation family {kind!r}") + + +def _top_k(Z: np.ndarray, k: int): + order = np.argsort(-Z, axis=1, kind="stable") + zt = np.take_along_axis(Z, order[:, :k], axis=1) + return order, zt + + +def scale_factor(zt: np.ndarray, signs: np.ndarray) -> np.ndarray: + """Per-rank cap c_j(z), shape (n, k). + + Understating rank j (sigma_j = -1) may take away at most its own probability z_j; + overstating it may add at most an equal share r = (1 - s)/k of the mass the + non-top classes hold. Both caps hold simultaneously for every eps in [0, 1], so + eta is always a valid conditional distribution. + """ + r = np.maximum((1.0 - zt.sum(axis=1)) / zt.shape[1], 0.0)[:, None] + return np.where(signs[None, :] < 0.0, zt, np.broadcast_to(r, zt.shape)) + + +def a_integrand(spec: dict, Z: np.ndarray) -> np.ndarray: + """The integrand whose mean is A: sum_j c_j(z)^2 h_j(z)^2.""" + _, zt = _top_k(Z, int(spec["k"])) + h = perturbation(spec, zt) + c = scale_factor(zt, np.asarray(spec["pert"]["sign"], dtype=np.float64)) + return ((c * h) ** 2).sum(axis=1) + + +def estimate_a(spec: dict, n_draws: int, seed: int, block: int = 500_000): + """Monte-Carlo estimate of A and its standard error, with a fixed seed.""" + rng = np.random.default_rng(seed) + total = 0.0 + total_sq = 0.0 + done = 0 + while done < n_draws: + m = min(block, n_draws - done) + vals = a_integrand(spec, draw_z(spec, m, rng)) + total += float(vals.sum()) + total_sq += float((vals * vals).sum()) + done += m + mean = total / n_draws + var = max(total_sq / n_draws - mean * mean, 0.0) + return mean, float(np.sqrt(var / n_draws)) + + +def sigma0_sq(K: int, k: int, n_draws: int = 4_000_000, seed: int = 20240819): + """sigma_0^2 = 2 * int_{Delta(K,k)} (||z||_2^2 - 2||z||_3^3 + ||z||_2^4) dz. + + Monte Carlo over the enclosing box [0,1]^k restricted to the truncated Weyl + chamber; the Lebesgue measure of the region is estimated by the same draws. + """ + rng = np.random.default_rng(seed) + total = 0.0 + total_sq = 0.0 + count = 0 + done = 0 + block = 200_000 + while done < n_draws: + m = min(block, n_draws - done) + z = rng.random((m, k)) + z = -np.sort(-z, axis=1) + s = z.sum(axis=1) + keep = (s >= k / K) & (s <= 1.0) + zz = z[keep] + val = (zz * zz).sum(1) - 2.0 * (zz**3).sum(1) + ((zz * zz).sum(1)) ** 2 + total += float(val.sum()) + total_sq += float((val * val).sum()) + count += int(keep.sum()) + done += m + fact = float(math.factorial(k)) + volume = count / n_draws / fact + integral = 2.0 * (total / n_draws) / fact + se = 2.0 * float(np.sqrt(max(total_sq / n_draws - (total / n_draws) ** 2, 0.0)) / np.sqrt(n_draws)) / fact + return integral, volume, se + + + + +def draw_replication(spec: dict, theta: float, rng: np.random.Generator): + """Draw one calibration data set whose true ECE^2_{1:k} equals `theta`. + + Returns (Z, Y) with Z of shape (n, K), C-contiguous float64, rows summing to 1, + and Y of shape (n,), int64, holding realised class indices in [0, K). + """ + K = int(spec["K"]) + k = int(spec["k"]) + n = int(spec["n"]) + A = float(spec["A"]) + theta = float(theta) + eps = 0.0 if theta <= 0.0 else float(np.sqrt(theta / A)) + if not (0.0 <= eps <= 1.0): + raise ValueError(f"eps={eps} outside [0, 1]; theta={theta} too large for A={A}") + + Z = draw_z(spec, n, rng) + order, zt = _top_k(Z, k) + signs = np.asarray(spec["pert"]["sign"], dtype=np.float64) + h = perturbation(spec, zt) + eta_top = zt + eps * signs[None, :] * scale_factor(zt, signs) * h + + P = np.zeros((n, K), dtype=np.float64) + rows = np.arange(n) + for j in range(k): + P[rows, order[:, j]] = eta_top[:, j] + rest_idx = order[:, k:] + z_rest = np.take_along_axis(Z, rest_idx, axis=1) + denom = z_rest.sum(axis=1) + frac = np.where( + denom[:, None] > 0.0, + z_rest / np.maximum(denom, 1e-300)[:, None], + 1.0 / max(K - k, 1), + ) + remainder = np.maximum(1.0 - eta_top.sum(axis=1), 0.0) + np.put_along_axis(P, rest_idx, frac * remainder[:, None], axis=1) + + np.clip(P, 0.0, 1.0, out=P) + P /= P.sum(axis=1, keepdims=True) + cdf = np.cumsum(P, axis=1) + u = rng.random((n, 1)) + Y = (u > cdf).sum(axis=1).astype(np.int64) + np.clip(Y, 0, K - 1, out=Y) + return np.ascontiguousarray(Z), Y + + +def theta_for(spec: dict, rep_rng: np.random.Generator) -> float: + """Pick this replication's true squared calibration error from the setting grid.""" + grid = np.asarray(spec["theta_grid"], dtype=np.float64) + return float(grid[rep_rng.integers(grid.size)]) diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/requirements-verifier.txt b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..04676c89520bf969f2cb861ad1811f46d8370700 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/requirements-verifier.txt @@ -0,0 +1,2 @@ +pytest==8.3.5 +pytest-json-ctrf==0.3.5 diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/requirements.txt b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b2c8174712815cd13bff215d4cd4238b180df145 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,2 @@ +numpy==2.5.2 +scipy==1.18.0 diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/run_call.py b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/run_call.py new file mode 100644 index 0000000000000000000000000000000000000000..313331d15ccbf4c735736fdd0466585547f89ccc --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/run_call.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +import importlib.util +import json +import pickle +import signal +import sys +import time + + +class _CallTimeout(Exception): + pass + + +def _on_alarm(signum, frame): + raise _CallTimeout() + + +def _load(module_dir: str, module_file: str): + sys.path.insert(0, module_dir) + spec = importlib.util.spec_from_file_location("candidate_interval", module_file) + if spec is None or spec.loader is None: + raise ImportError(f"cannot load {module_file}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def main() -> int: + batch = pickle.load(sys.stdin.buffer) + cap = float(batch["cap"]) + out = {"import_error": None, "results": []} + + try: + import numpy as np + + mod = _load(batch["module_dir"], batch["module_file"]) + fn = getattr(mod, "ece2_interval") + if not callable(fn): + raise TypeError("ece2_interval is not callable") + except BaseException as exc: + out["import_error"] = f"{type(exc).__name__}: {exc}"[:200] + sys.stdout.write(json.dumps(out)) + return 0 + + signal.signal(signal.SIGALRM, _on_alarm) + for call in batch["calls"]: + rec = {"key": call["key"]} + rng = np.random.default_rng(int(call["seed"])) + started = time.monotonic() + signal.setitimer(signal.ITIMER_REAL, cap) + try: + lo, hi = fn(call["Z"], call["Y"], int(call["k"]), float(call["alpha"]), rng) + rec.update(status="ok", lo=float(lo), hi=float(hi)) + except _CallTimeout: + rec.update(status="timeout") + except BaseException as exc: + rec.update(status="error", detail=f"{type(exc).__name__}: {exc}"[:120]) + finally: + signal.setitimer(signal.ITIMER_REAL, 0.0) + rec["elapsed"] = time.monotonic() - started + if rec.get("status") == "ok" and rec["elapsed"] > cap: + rec["status"] = "timeout" + out["results"].append(rec) + + sys.stdout.write(json.dumps(out)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/test.sh b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..98bb47dace72460c20d2baaa9984d641904a5c9d --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/test.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -u + +mkdir -p /logs/verifier +chown root:root /logs/verifier 2>/dev/null || true +chmod 755 /logs/verifier 2>/dev/null || true +rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json + +trap 'if [ ! -s /logs/verifier/reward.txt ]; then echo "0" > /logs/verifier/reward.txt; fi' EXIT + +chmod -R go-rwx /tests + +export GRADE_SPLIT=final +cd /tests +/usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +/usr/local/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/test_state.py b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..276929adeec5dbc7e378c46f061c70684ad90469 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/environment/are-grader-ctx/test_state.py @@ -0,0 +1,337 @@ +from __future__ import annotations + +import functools +import json +import multiprocessing as mp +import os +import pickle +import shutil +import stat +import subprocess +import sys +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import grader_core as gc + +PY = sys.executable +RUN_CALL = "/opt/candrun/run_call.py" +ARTIFACT_DIR = Path("/app/output") +ENTRY_NAME = "interval.py" +STAGING = Path("/run/candidate_src") +SANDBOX_ROOT = Path("/var/tmp/candidate_sandbox") +METRIC_PATH = Path("/logs/verifier/metric.json") +AGENT_UID = 1001 +AGENT_GID = 1001 + +HALF = os.environ.get("GRADE_SPLIT", "final") +HIDDEN_DIR = Path(os.environ.get("GRADER_HIDDEN_DIR", + str(Path(__file__).resolve().parent / "hidden_data" / HALF))) +WORKERS = int(os.environ.get("GRADER_WORKERS", "8")) +GRADE_DEADLINE_SEC = float(os.environ.get("GRADER_DEADLINE_SEC", "1200")) +REPLICATIONS = int(os.environ.get("GRADER_REPLICATIONS", str(gc.REPLICATIONS))) +SEED_OFFSET = int(os.environ.get("GRADER_SEED_OFFSET", "0")) + +CHILD_ENV_BASE = { + "PATH": "/usr/local/bin:/usr/bin:/bin", + "LC_ALL": "C", + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", + "PYTHONHASHSEED": "0", + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONNOUSERSITE": "1", + "PYTHONSAFEPATH": "1", +} + + + + +def _reject_unsafe(root: Path) -> list[str]: + """Every submitted path is hostile: refuse symlinks, hard links and specials. + + A privileged copy that followed a submitted symlink would materialise verifier + files into a directory the score is computed from, so the whole tree is checked + at every depth BEFORE anything is copied, and the copy itself never follows + links (`symlinks=True`). + """ + problems: list[str] = [] + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in list(dirnames) + list(filenames): + p = Path(dirpath) / name + st = p.lstat() + if stat.S_ISLNK(st.st_mode): + problems.append(f"symlink: {p}") + elif stat.S_ISDIR(st.st_mode): + continue + elif not stat.S_ISREG(st.st_mode): + problems.append(f"not a regular file: {p}") + elif st.st_nlink > 1: + problems.append(f"hard link: {p}") + return problems + + +def stage_deliverable() -> dict: + """Copy the deliverable to a root-owned read-only tree and seal the original.""" + info: dict = {"entry_point": str(ARTIFACT_DIR / ENTRY_NAME)} + if STAGING.exists(): + shutil.rmtree(STAGING) + if not ARTIFACT_DIR.is_dir(): + info["error"] = "missing_artifact_dir" + return info + problems = _reject_unsafe(ARTIFACT_DIR) + if problems: + info["error"] = "unsafe_paths" + info["detail"] = problems[:5] + return info + + shutil.copytree(ARTIFACT_DIR, STAGING, symlinks=True) + entry = STAGING / ENTRY_NAME + if not entry.is_file() or entry.stat().st_size == 0: + info["error"] = "missing_or_empty_entry_point" + info["deliverable_bytes"] = entry.stat().st_size if entry.exists() else 0 + return info + info["deliverable_bytes"] = entry.stat().st_size + + for path in [STAGING, *STAGING.rglob("*")]: + os.chown(path, 0, 0) + os.chmod(path, 0o555 if path.is_dir() else 0o444) + for path in [ARTIFACT_DIR, *ARTIFACT_DIR.rglob("*")]: + try: + os.chown(path, 0, 0) + os.chmod(path, 0o555 if path.is_dir() else 0o444) + except OSError: + pass + return info + + +def prepare_sandboxes(n: int) -> list[Path]: + if SANDBOX_ROOT.exists(): + shutil.rmtree(SANDBOX_ROOT) + SANDBOX_ROOT.mkdir(parents=True) + os.chmod(SANDBOX_ROOT, 0o755) + out = [] + for i in range(n): + d = SANDBOX_ROOT / f"w{i}" + d.mkdir() + os.chown(d, AGENT_UID, AGENT_GID) + os.chmod(d, 0o700) + out.append(d) + return out + + + + +@functools.lru_cache(maxsize=1) +def _launcher() -> list[str]: + """Drop privileges with runuser; fall back to a setresuid preexec if absent.""" + for candidate in ("/usr/sbin/runuser", "/sbin/runuser", "/usr/bin/runuser"): + if os.path.exists(candidate): + return [candidate, "-u", "agent", "--"] + found = shutil.which("runuser") + return [found, "-u", "agent", "--"] if found else [] + + +def _drop_privileges(): + os.setgroups([AGENT_GID]) + os.setresgid(AGENT_GID, AGENT_GID, AGENT_GID) + os.setresuid(AGENT_UID, AGENT_UID, AGENT_UID) + + +def run_batch(calls: list[dict], sandbox: Path, wall_budget: float) -> dict: + """Run one batch of candidate calls in a fresh unprivileged process.""" + blob = pickle.dumps( + { + "module_dir": str(STAGING), + "module_file": str(STAGING / ENTRY_NAME), + "cap": gc.PER_CALL_CAP_SEC, + "calls": calls, + }, + protocol=pickle.HIGHEST_PROTOCOL, + ) + env = dict(CHILD_ENV_BASE) + env["HOME"] = str(sandbox) + env["TMPDIR"] = str(sandbox) + + launcher = _launcher() + argv = [*launcher, PY, RUN_CALL] if launcher else [PY, RUN_CALL] + preexec = None if launcher else _drop_privileges + proc = subprocess.Popen( + argv, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=str(sandbox), + env=env, + start_new_session=True, + preexec_fn=preexec, + ) + try: + out, _err = proc.communicate(input=blob, timeout=wall_budget) + payload = json.loads(out.decode("utf-8", "replace")) if out.strip() else {} + except subprocess.TimeoutExpired: + payload = {"import_error": "batch_timeout"} + except Exception as exc: + payload = {"import_error": f"unparseable_child_output: {type(exc).__name__}"} + finally: + try: + os.killpg(os.getpgid(proc.pid), 9) + except (ProcessLookupError, PermissionError, OSError): + pass + try: + proc.wait(timeout=10) + except Exception: + pass + for child in sandbox.iterdir(): + shutil.rmtree(child, ignore_errors=True) if child.is_dir() else child.unlink(missing_ok=True) + return payload + + + + +_WORKER_STATE: dict = {} + + +def _worker_init(settings, master_seed, sandbox_paths): + idx = int(mp.current_process().name.rsplit("-", 1)[-1]) - 1 + _WORKER_STATE["settings"] = settings + _WORKER_STATE["master_seed"] = master_seed + _WORKER_STATE["sandbox"] = sandbox_paths[idx % len(sandbox_paths)] + + +def _worker_replication(rep: int): + settings = _WORKER_STATE["settings"] + master_seed = _WORKER_STATE["master_seed"] + sandbox = _WORKER_STATE["sandbox"] + calls = [] + thetas = {} + for si, spec in enumerate(settings): + Z, Y, theta, seed = gc.make_replication(spec, master_seed, si, rep) + thetas[si] = theta + calls.append( + {"key": si, "Z": Z, "Y": Y, "k": int(spec["k"]), "alpha": gc.ALPHA, "seed": seed} + ) + budget = gc.PER_CALL_CAP_SEC * len(calls) + 25.0 + payload = run_batch(calls, sandbox, budget) + records = {} + import_error = payload.get("import_error") + by_key = {r.get("key"): r for r in payload.get("results", []) if isinstance(r, dict)} + for si in range(len(settings)): + rec = by_key.get(si) + if import_error is not None or rec is None: + records[si] = {"status": import_error or "no_result"} + else: + records[si] = rec + return rep, records, thetas + + +def _grade() -> dict: + started = time.monotonic() + doc = gc.load_panel(HIDDEN_DIR) + settings = doc["settings"] + master_seed = int(doc["master_seed"]) + SEED_OFFSET + + staged = stage_deliverable() + if "error" in staged: + return { + "status": "invalid", + "reason": staged["error"], + "detail": staged.get("detail"), + "metric": None, + "reward": 0.0, + "half": HALF, + } + + sandboxes = prepare_sandboxes(WORKERS) + results: dict = {} + thetas: dict = {} + truncated_at = None + ctx = mp.get_context("fork") + with ctx.Pool(WORKERS, initializer=_worker_init, initargs=(settings, master_seed, sandboxes)) as pool: + for rep, recs, ths in pool.imap_unordered(_worker_replication, range(REPLICATIONS), chunksize=4): + for si, rec in recs.items(): + results[(si, rep)] = rec + for si, th in ths.items(): + thetas[(si, rep)] = th + if time.monotonic() - started > GRADE_DEADLINE_SEC: + truncated_at = len(results) + pool.terminate() + break + + for si, spec in enumerate(settings): + for rep in range(REPLICATIONS): + if (si, rep) not in thetas: + thetas[(si, rep)] = gc.theta_only(spec, master_seed, si, rep) + results.setdefault((si, rep), {"status": "not_run"}) + + scored = gc.score_panel(settings, thetas, results, REPLICATIONS) + scored.update( + status="graded", + half=HALF, + reward=gc.graded_reward(scored["metric"]), + deliverable_bytes=staged.get("deliverable_bytes"), + wall_clock_sec=round(time.monotonic() - started, 1), + truncated_at=truncated_at, + workers=WORKERS, + ) + return scored + + +@functools.lru_cache(maxsize=1) +def grade_once() -> dict: + METRIC_PATH.parent.mkdir(parents=True, exist_ok=True) + try: + result = _grade() + except BaseException as exc: + result = {"status": "error", "reason": f"{type(exc).__name__}: {exc}"[:300], + "metric": None, "reward": 0.0, "half": HALF} + METRIC_PATH.write_text(json.dumps(result, indent=1, sort_keys=True)) + return result + + +def _summary(result: dict) -> str: + lines = [f"half={result.get('half')} status={result.get('status')}"] + if result.get("status") == "graded": + for row in result["per_setting"]: + lines.append( + f" setting {row['index']}: coverage={row['coverage']:.4f} " + f"relative_length={row['relative_length']:.5f} " + f"coverage_ok={row['coverage_gate_met']} score={row['score']:.5f}" + ) + lines.append(f" call outcomes: {result['status_counts']}") + lines.append(f" metric (mean relative length, lower is better) = {result['metric']:.6f}") + lines.append(f" wall clock {result.get('wall_clock_sec')}s over {result.get('workers')} workers") + else: + lines.append(f" reason={result.get('reason')} detail={result.get('detail')}") + return "\n".join(lines) + + + + +def test_deliverable_runs(): + """The submitted entry point must exist, import, and produce usable intervals. + + Measures real behaviour: it is satisfied only if calls returned intervals inside + the disclosed contract, not by the file existing. + """ + result = grade_once() + print(_summary(result)) + assert result["status"] == "graded", f"deliverable not gradeable: {result.get('reason')}" + ok = result["status_counts"].get("ok", 0) + assert ok > 0, f"no call returned a valid interval: {result['status_counts']}" + + +def test_panel_metric_recorded(): + """The coverage-constrained mean relative length is recorded for the reward map.""" + result = grade_once() + assert METRIC_PATH.is_file(), "metric.json was not written" + assert result.get("metric") is not None, "no metric computed" + print(f"metric={result['metric']:.6f}") + + +if __name__ == "__main__": + res = grade_once() + print(_summary(res)) + print(json.dumps({k: v for k, v in res.items() if k != "per_setting"}, indent=1))