diff --git a/tasks/shortest-valid-ci-l2-ece/environment/docker-compose.yaml b/tasks/shortest-valid-ci-l2-ece/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9883cfae52b5004d6fd749b42b16a3c9b9299121 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/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/shortest-valid-ci-l2-ece/task.toml b/tasks/shortest-valid-ci-l2-ece/task.toml index 87e88623bd6ac11197fe20880163a1127d5cb672..0eaaf087efc90045d7e849000a701fb450b1f6f5 100644 --- a/tasks/shortest-valid-ci-l2-ece/task.toml +++ b/tasks/shortest-valid-ci-l2-ece/task.toml @@ -1,56 +1,70 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/shortest-valid-ci-l2-ece" -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 = "Model evaluation and benchmarking" -task_objective = [ "Implement", "Optimize",] -artifact_type = [ "Single script or program",] +task_objective = [ + "Implement", + "Optimize", +] +artifact_type = [ + "Single script or program", +] expert_time_estimate_hours = 6.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 = 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 = 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/shortest-valid-ci-l2-ece/tests/Dockerfile b/tasks/shortest-valid-ci-l2-ece/tests/Dockerfile index b277d2f2206e6fede1be762a297a8408ce255517..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/shortest-valid-ci-l2-ece/tests/Dockerfile +++ b/tasks/shortest-valid-ci-l2-ece/tests/Dockerfile @@ -1,41 +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 \ - 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 +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/shortest-valid-ci-l2-ece/tests/finalize.py b/tasks/shortest-valid-ci-l2-ece/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/shortest-valid-ci-l2-ece/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/shortest-valid-ci-l2-ece/tests/test.sh b/tasks/shortest-valid-ci-l2-ece/tests/test.sh index 98bb47dace72460c20d2baaa9984d641904a5c9d..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/shortest-valid-ci-l2-ece/tests/test.sh +++ b/tasks/shortest-valid-ci-l2-ece/tests/test.sh @@ -1,18 +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 - -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 +python3 /tests/finalize.py diff --git a/tasks/sketched-newton-cov-estimator/environment/.dockerignore b/tasks/sketched-newton-cov-estimator/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b5a4bb6526d3299406eeff96b12dda06f7527a97 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,31 @@ +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 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 diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile.are b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..929db15130097af5f7c9df3e1727949262d00dd0 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,49 @@ +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 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 + + +# ---- 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/sketched-newton-cov-estimator/environment/are-grader-ctx/are/drain.py b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/sketched-newton-cov-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/sketched-newton-cov-estimator/environment/are-grader-ctx/are/server.py b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/sketched-newton-cov-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/sketched-newton-cov-estimator/environment/are-grader-ctx/compute_reward.py b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..8233986f06026ee40725e08b95982288aef591f6 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,19 @@ +import json +import math +from pathlib import Path + +REWARD_PATH = Path("/logs/verifier/reward.txt") +METRIC_PATH = Path("/logs/verifier/metric.json") + +try: + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + value = float(json.loads(METRIC_PATH.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.parent.mkdir(parents=True, exist_ok=True) + REWARD_PATH.write_text("0\n") + print(f"reward=0 (fallback: {exc})") diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/grader_core.py b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..52bf567b599865c2d19d3fab161ff21070daf9e8 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,268 @@ +import json +import math +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import oracle + +TESTS_DIR = Path(__file__).resolve().parent + +ENTRY_POINT = "estimator.py" +REPLICATIONS = int(os.environ.get("GRADER_REPLICATIONS", "20")) +REPLICATION_TIMEOUT_S = 90.0 +TRIVIAL_ERROR = 1.0 +RUN_AS_UID = int(os.environ.get("GRADER_RUN_AS_UID", "1001")) +WORKERS = int(os.environ.get("GRADER_WORKERS", "8")) +GLOBAL_DEADLINE_S = float(os.environ.get("GRADER_DEADLINE_S", "1200")) + +M0 = 1.0 +BASELINE_SCORE = 0.013 + + +def reward_from_metric(metric): + """log-ratio squash: 0 at the trivial baseline, 0.5 at the reference, -> 1, no cutoff.""" + if metric is None: + return 0.0 + m = float(metric) + if not math.isfinite(m) or m < 0.0: + return 0.0 + if m == 0.0: + return 1.0 + u = math.log(M0 / m) / math.log(M0 / BASELINE_SCORE) + if u <= 0.0: + return 0.0 + return u / (1.0 + u) + + +def load_instances(split_dir): + paths = sorted(Path(split_dir).glob("inst_*.json")) + if not paths: + raise RuntimeError(f"no instances under {split_dir}") + return [json.loads(p.read_text()) for p in paths] + + +def instance_covariance(inst): + d = int(inst["d"]) + Sigma = np.full((d, d), float(inst["equi_r"])) + np.fill_diagonal(Sigma, 1.0) + return Sigma + + +def true_functional(inst): + """w' Xi* w for one instance, from the closed form. Never leaves this process.""" + d = int(inst["d"]) + Xi = oracle.xi_star(instance_covariance(inst), float(inst["sigma"]) ** 2, int(inst["tau"])) + w = np.full(d, 1.0 / d) + return float(w @ Xi @ w) + + +def draw_samples(inst, seed): + """The realized samples of one replication. The only thing the child is given.""" + d, T = int(inst["d"]), int(inst["T"]) + L = np.linalg.cholesky(instance_covariance(inst)) + rng = np.random.default_rng(seed) + A = rng.standard_normal((T, d)) @ L.T + b = A @ np.asarray(inst["x_star"], dtype=np.float64) + rng.standard_normal(T) * float(inst["sigma"]) + return A, b + + +def _launch(workdir, timeout_s): + """Run the deliverable in its own session as an unprivileged uid, hard-killed on time. + + Output goes to a file rather than a pipe, so an agent that prints without bound cannot + grow the trusted process's memory; only the last 2 kB is ever read back. + """ + py = sys.executable + script = str(workdir / "run_one.py") + argv = [py, script, "--workdir", str(workdir)] + kwargs = dict(cwd=str(workdir / "out"), start_new_session=True, + user=RUN_AS_UID, group=RUN_AS_UID, env={ + "PATH": "/usr/local/bin:/usr/bin:/bin", + "HOME": str(workdir / "out"), "TMPDIR": str(workdir / "out"), + "OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", "NUMEXPR_NUM_THREADS": "1", + "PYTHONHASHSEED": "0", "PYTHONDONTWRITEBYTECODE": "1"}) + + log = workdir / "child.log" + with open(log, "wb") as fh: + proc = subprocess.Popen(argv, stdout=fh, stderr=subprocess.STDOUT, **kwargs) + try: + proc.communicate(timeout=timeout_s) + rc = proc.returncode + except subprocess.TimeoutExpired: + try: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + except Exception: + proc.kill() + proc.communicate() + rc = "timeout" + tail = "" + try: + with open(log, "rb") as fh: + fh.seek(max(0, log.stat().st_size - 2000)) + tail = fh.read().decode("utf-8", "replace") + except Exception: + pass + return rc, tail + + +def run_replication(inst, rep, solution_dir, workroot, timeout_s): + """Prepare a scratch dir, run one replication, return the raw functional or a failure.""" + out = {"instance": inst["name"], "rep": rep, "status": "error", "v_hat": None, "detail": ""} + if timeout_s <= 1.0: + out["status"] = "deadline" + return out + work = Path(tempfile.mkdtemp(dir=workroot, prefix=f"{inst['name']}_r{rep}_")) + try: + shutil.copy2(TESTS_DIR / "run_one.py", work / "run_one.py") + shutil.copytree(TESTS_DIR / "harness", work / "harness") + shutil.copytree(solution_dir, work / "solution", symlinks=True) + seed = int(inst["seed_base"]) + 2 * rep + A, b = draw_samples(inst, seed) + np.save(work / "samples_a.npy", A, allow_pickle=False) + np.save(work / "samples_b.npy", b, allow_pickle=False) + (work / "job.json").write_text(json.dumps( + {"d": int(inst["d"]), "T": int(inst["T"]), "tau": int(inst["tau"]), + "alg_seed": seed + 1})) + del A, b + for p in [work] + list(work.rglob("*")): + os.chmod(p, 0o755 if p.is_dir() else 0o644) + (work / "out").mkdir() + os.chown(work / "out", RUN_AS_UID, RUN_AS_UID) + os.chmod(work / "out", 0o700) + + rc, err = _launch(work, timeout_s) + if rc == "timeout": + out["status"] = "timeout" + out["detail"] = f"exceeded {timeout_s:.0f}s" + return out + if rc != 0: + out["status"] = "crashed" + out["detail"] = err.strip()[-600:] + return out + + res = work / "out" / "result.npy" + if not res.exists(): + out["status"] = "no_output" + return out + try: + M = np.load(res, allow_pickle=False) + except Exception as exc: + out["status"] = "unparseable" + out["detail"] = str(exc)[:200] + return out + d = int(inst["d"]) + if M.shape != (d, d) or M.dtype != np.float64: + out["status"] = "bad_shape" + out["detail"] = f"got shape {M.shape} dtype {M.dtype}" + return out + if not np.all(np.isfinite(M)): + out["status"] = "non_finite" + return out + w = np.full(d, 1.0 / d) + out["v_hat"] = float(w @ M @ w) + out["status"] = "ok" + return out + except Exception as exc: + out["status"] = "infra_error" + out["detail"] = f"{type(exc).__name__}: {exc}"[:300] + return out + finally: + shutil.rmtree(work, ignore_errors=True) + + +def grade(split_dir, deliverable_dir, workroot=None, replications=REPLICATIONS): + t0 = time.time() + instances = load_instances(split_dir) + truth = {i["name"]: true_functional(i) for i in instances} + + entry = Path(deliverable_dir) / ENTRY_POINT + have_entry = entry.is_file() and entry.stat().st_size > 0 + results = [] + + if have_entry: + workroot = workroot or tempfile.mkdtemp(prefix="grade_") + os.chmod(workroot, 0o711) + staged = Path(workroot) / "solution" + shutil.rmtree(staged, ignore_errors=True) + src = Path(deliverable_dir) + for p in [src] + list(src.rglob("*")): + if p.is_symlink(): + raise RuntimeError(f"symlink in deliverable is not allowed: {p}") + shutil.copytree(deliverable_dir, staged, symlinks=True) + for p in [staged] + list(staged.rglob("*")): + os.chmod(p, 0o755 if p.is_dir() else 0o644) + + jobs = [(i, r) for i in instances for r in range(replications)] + + def work(job): + inst, rep = job + left = GLOBAL_DEADLINE_S - (time.time() - t0) + return run_replication(inst, rep, staged, workroot, + min(REPLICATION_TIMEOUT_S, left)) + + with ThreadPoolExecutor(max_workers=WORKERS) as pool: + results = list(pool.map(work, jobs)) + else: + for inst in instances: + for rep in range(replications): + results.append({"instance": inst["name"], "rep": rep, + "status": "missing_entry_point", "v_hat": None, "detail": ""}) + + per_instance = {} + for inst in instances: + name = inst["name"] + rows = [r for r in results if r["instance"] == name] + bad = [r for r in rows if r["status"] != "ok"] + if bad or len(rows) != replications: + per_instance[name] = {"error": TRIVIAL_ERROR, "failed": len(bad) + replications - len(rows)} + continue + v = truth[name] + rel = np.array([r["v_hat"] for r in rows], dtype=np.float64) / v - 1.0 + sd = float(rel.std(ddof=1)) if len(rel) > 1 else float("nan") + per_instance[name] = {"error": float(abs(rel.mean())), "failed": 0, + "signed_mean": float(rel.mean()), + "sd_per_replication": sd, + "mc_error": sd / math.sqrt(len(rel))} + + metric = float(np.mean([per_instance[i["name"]]["error"] for i in instances])) + n_failed = sum(1 for r in results if r["status"] != "ok") + statuses = {} + for r in results: + statuses[r["status"]] = statuses.get(r["status"], 0) + 1 + first_detail = next((r["detail"] for r in results if r["status"] != "ok" and r["detail"]), "") + + return { + "metric": metric, + "reward": reward_from_metric(metric), + "replications_per_instance": replications, + "replications_failed": n_failed, + "replication_status_counts": statuses, + "first_failure_detail": first_detail, + "per_instance": per_instance, + "wall_clock_s": round(time.time() - t0, 1), + } + + +def summary_lines(report): + """The only thing printed to stdout. Aggregates only -- no per-instance detail.""" + return [ + f"replications per instance : {report['replications_per_instance']}", + f"replications failed : {report['replications_failed']}" + + (f" {report['replication_status_counts']}" if report["replications_failed"] else ""), + f"first failure : {report['first_failure_detail'][:600]}" + if report["first_failure_detail"] else "first failure : -", + f"metric (lower is better) : {report['metric']:.6f}", + f"reward : {report['reward']:.6f}", + f"grading wall clock (s) : {report['wall_clock_s']}", + ] diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/harness/runner.py b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/harness/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..2584efc2c41bed308c340ef6aaabc15d12b9590e --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/harness/runner.py @@ -0,0 +1,116 @@ +import numpy as np +from scipy.linalg import solve_triangular + +_BLOCK = 8192 + + +def make_config(d, T, tau, w=None): + """The `config` dict handed to `estimate`. Contains no instance secrets.""" + if w is None: + w = np.full(d, 1.0 / d) + return { + "d": int(d), + "T": int(T), + "tau": int(tau), + "q": 1, + "sketch": "kaczmarz", + "beta": 0.505, + "c_beta": 1.0, + "loss": "squared_error_linear_regression", + "x0": np.zeros(d), + "B0": np.eye(d), + "w": np.asarray(w, dtype=np.float64), + } + + +def draw_samples(instance, seed): + """Draw the T samples of one replication from an instance's parameters. + + `instance` needs the keys d, T, sigma, x_star and either Sigma_a or (equi_r). + Returns (A, b) with A of shape (T, d) and b of shape (T,). + """ + d, T = int(instance["d"]), int(instance["T"]) + Sigma_a = instance_covariance(instance) + L = np.linalg.cholesky(Sigma_a) + rng = np.random.default_rng(seed) + A = rng.standard_normal((T, d)) @ L.T + eps = rng.standard_normal(T) * float(instance["sigma"]) + b = A @ np.asarray(instance["x_star"], dtype=np.float64) + eps + return A, b + + +def instance_covariance(instance): + """Equi-correlation design: [Sigma_a]_ii = 1, [Sigma_a]_ij = r for i != j.""" + d = int(instance["d"]) + r = float(instance["equi_r"]) + Sigma = np.full((d, d), r) + np.fill_diagonal(Sigma, 1.0) + return Sigma + + +def stream_from_samples(A, b, config, alg_seed): + """Yield one record per iteration. `A` is (T, d), `b` is (T,). + + Each record is a fresh dict holding read-only arrays. The runner never writes into an + array it has already yielded, so a record stays valid for as long as you keep it. + t int, the iteration index + x (d,) x_{t+1}, the iterate AFTER this step's update + alpha float the realized stepsize alpha_t + g (d,) the stochastic gradient at x_t + H (d, d) the sample Hessian at x_t + B (d, d) the Hessian average B_t used by this step's inner solve + sketch_idx (tau,) the Kaczmarz indices used by this step's inner solve + """ + d = int(config["d"]) + T = int(config["T"]) + tau = int(config["tau"]) + beta = float(config["beta"]) + c_beta = float(config["c_beta"]) + + x = np.array(config["x0"], dtype=np.float64) + B = np.array(config["B0"], dtype=np.float64) + rng = np.random.default_rng(alg_seed) + + idx_block = None + u_block = None + for t in range(T): + k = t % _BLOCK + if k == 0: + n = min(_BLOCK, T - t) + idx_block = rng.integers(0, d, size=(n, tau)) + u_block = rng.random(n) + + a = A[t] + g = a * (a @ x - b[t]) + + idx = idx_block[k] + sel = B[:, idx] + nrm = np.sqrt(np.einsum("ij,ij->j", sel, sel)) + F = sel / nrm + dx = F @ solve_triangular(np.tril(F.T @ F), -g[idx] / nrm, lower=True, + unit_diagonal=True, check_finite=False, overwrite_b=True) + + beta_t = c_beta / (t + 1.0) ** beta + alpha = beta_t + u_block[k] * beta_t * beta_t + x = x + alpha * dx + + H = np.outer(a, a) + for arr in (x, g, H, B, idx): + arr.flags.writeable = False + yield { + "t": t, + "x": x, + "alpha": float(alpha), + "g": g, + "H": H, + "B": B, + "sketch_idx": idx, + } + + B = ((t + 1.0) * B + H) / (t + 2.0) + + +def make_stream(instance, config, sample_seed, alg_seed): + """Convenience wrapper: draw an instance's samples, then stream one replication.""" + A, b = draw_samples(instance, sample_seed) + return stream_from_samples(A, b, config, alg_seed) diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_0.json b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_0.json new file mode 100644 index 0000000000000000000000000000000000000000..0523d06feb20f903ec74377375da51ad3d1de2b2 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_0.json @@ -0,0 +1,31 @@ +{ + "name": "sealF0", + "d": 20, + "T": 300000, + "tau": 20, + "equi_r": 0.132076, + "sigma": 1.035163, + "x_star": [ + -0.019722108888, + -0.043768990181, + -0.016978953849, + -0.041987901786, + -0.027223042407, + 0.006300373844, + 0.013943979186, + -0.019059026608, + 0.008421650997, + -0.079513148397, + -0.071653297202, + 0.053201419509, + -0.060378806686, + -0.085022153445, + -0.005837723371, + 0.101380431414, + 0.047635755492, + 7.7076412e-05, + -0.07658615567, + 0.025033501465 + ], + "seed_base": 841200185 +} diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_1.json b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_1.json new file mode 100644 index 0000000000000000000000000000000000000000..785b46e924cbb6c2096ec806055b1223aacedef8 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_1.json @@ -0,0 +1,31 @@ +{ + "name": "sealF1", + "d": 20, + "T": 300000, + "tau": 40, + "equi_r": 0.222325, + "sigma": 0.805114, + "x_star": [ + -0.082932808961, + 0.038545870624, + 0.004312618402, + -0.055654625394, + 0.020893374205, + -0.124393736972, + 0.057071827706, + 0.043785304794, + -0.042946668716, + 0.019317748747, + 0.002910150262, + -0.037568440259, + -0.055793184577, + 0.056245388685, + -0.031427430157, + 0.008295253253, + 0.053125175571, + -0.040845921657, + -0.040308878577, + -0.018703000051 + ], + "seed_base": 939721810 +} diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_2.json b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_2.json new file mode 100644 index 0000000000000000000000000000000000000000..a40f358461993c7d7696a68c66f1f43b2f53c2af --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_2.json @@ -0,0 +1,31 @@ +{ + "name": "sealF2", + "d": 20, + "T": 300000, + "tau": 10, + "equi_r": 0.151511, + "sigma": 0.874065, + "x_star": [ + 0.095956898049, + -0.004996400008, + 0.006311228453, + 0.011112538622, + -0.009496748634, + -0.015015359292, + -0.005287695998, + 0.048944383801, + -0.062397368507, + 0.00238404898, + -0.100809118235, + 0.028671325467, + -0.068214488049, + -0.023500778765, + 0.056537806242, + -0.033217168108, + -0.030644999212, + 0.011702616777, + -0.048161361361, + -0.100400192593 + ], + "seed_base": 755664261 +} diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_3.json b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_3.json new file mode 100644 index 0000000000000000000000000000000000000000..001fecff5e7027a9e4b34016cf16d933ddfcfab6 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_3.json @@ -0,0 +1,31 @@ +{ + "name": "sealF3", + "d": 20, + "T": 300000, + "tau": 20, + "equi_r": 0.271258, + "sigma": 1.751414, + "x_star": [ + 0.024972636039, + 0.03533280065, + 0.093659428727, + -0.041126527796, + -0.024346355273, + -0.083137388327, + -0.037750722609, + 0.066469180419, + -0.003471314605, + 0.091974410156, + -0.010119253259, + -0.010260004657, + -0.053269325588, + 0.047791864094, + 0.04810807302, + -0.004704687523, + 0.003928567812, + 0.006460957598, + 0.03196080178, + -0.084265993839 + ], + "seed_base": 996720305 +} diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_0.json b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_0.json new file mode 100644 index 0000000000000000000000000000000000000000..0400c3f8b10fe8c34c4141901d2254a0ebc462cb --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_0.json @@ -0,0 +1,31 @@ +{ + "name": "sealI0", + "d": 20, + "T": 300000, + "tau": 10, + "equi_r": 0.242438, + "sigma": 1.987579, + "x_star": [ + 0.035973464612, + 0.027253032917, + -0.031596861933, + -0.018343116487, + -0.020911424013, + -0.1491477536, + 0.013498660293, + 0.006200096616, + -0.015070425319, + 0.022844567177, + -0.077994643809, + -0.003851103026, + -0.032669570035, + 0.041203220648, + -0.007091550034, + 0.00811292529, + 0.065859152925, + 0.046109225502, + -0.04484870205, + -0.07431256495 + ], + "seed_base": 801608310 +} diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_1.json b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_1.json new file mode 100644 index 0000000000000000000000000000000000000000..9ea4104f8f0f3fb1a980676e96e76504e355c25e --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_1.json @@ -0,0 +1,31 @@ +{ + "name": "sealI1", + "d": 20, + "T": 300000, + "tau": 40, + "equi_r": 0.112021, + "sigma": 1.160481, + "x_star": [ + -0.03426103133, + 0.01757527391, + -0.114675095472, + -0.03974628369, + -0.057236905083, + 0.005505864975, + 0.044311780829, + -0.017366965234, + -0.040559344461, + -0.045404460944, + -0.002066011218, + -0.071839758821, + -0.05194956085, + -0.05814472584, + -0.021194042223, + -0.029639640005, + -0.038732120007, + 0.098609447255, + 0.026606893038, + -0.00214245734 + ], + "seed_base": 942125480 +} diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_2.json b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_2.json new file mode 100644 index 0000000000000000000000000000000000000000..b70c049d2cf9334fc0f262f918cb309ef66878fd --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_2.json @@ -0,0 +1,31 @@ +{ + "name": "sealI2", + "d": 20, + "T": 300000, + "tau": 20, + "equi_r": 0.150641, + "sigma": 1.9847, + "x_star": [ + 0.061912698266, + -0.011329243664, + 0.001349428686, + -0.033716256102, + -0.066686683827, + -0.040736213303, + 0.055910365725, + -0.023177050316, + 0.037218968578, + -0.038877559169, + 0.071259066126, + 0.022718553147, + 0.075966470665, + -0.009292402812, + -0.116543497448, + 0.017304237725, + -0.038278283045, + -0.044425847335, + -0.057455316556, + 0.012664324105 + ], + "seed_base": 462111903 +} diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_3.json b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_3.json new file mode 100644 index 0000000000000000000000000000000000000000..3db9fc629a32f69d4a968dd1d885f578d53447f5 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_3.json @@ -0,0 +1,31 @@ +{ + "name": "sealI3", + "d": 20, + "T": 300000, + "tau": 40, + "equi_r": 0.265884, + "sigma": 0.501666, + "x_star": [ + -0.00495812216, + 0.057794303105, + -0.132022500532, + 5.8374263e-05, + 0.011778313649, + -0.067304320932, + 0.053298500444, + -0.00069184491, + 0.031638710103, + -0.067837987423, + -0.002114095999, + -0.05050766958, + 0.040031360963, + -0.028814842159, + 0.037268534752, + -0.018590979209, + 0.016295358434, + -0.07212676206, + 0.008673464269, + -0.061859333449 + ], + "seed_base": 385455181 +} diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/intermediate.sh b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..9b30336f11fd9f38844c60d88094b6711cc04711 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/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/ctrf.json /logs/verifier/metric.json + +printf '0\n' > /logs/verifier/reward.txt +trap 'if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /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/sketched-newton-cov-estimator/environment/are-grader-ctx/oracle.py b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..e29bb732bbbb59514de36d7c141da878b36c961d --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/oracle.py @@ -0,0 +1,38 @@ +import numpy as np + + +def _projectors(B): + """P[i] = b_i b_i^T / ||b_i||^2 for every column b_i of B.""" + nrm2 = np.einsum("ij,ij->j", B, B) + return np.einsum("ik,jk->kij", B, B) / nrm2[:, None, None] + + +def xi_star(Sigma_a, sigma2, tau): + """The limiting covariance of the last iterate, exactly.""" + Sigma_a = np.asarray(Sigma_a, dtype=np.float64) + d = Sigma_a.shape[0] + Omega = float(sigma2) * np.linalg.inv(Sigma_a) + + Q = np.eye(d)[None, :, :] - _projectors(Sigma_a) + C = np.linalg.matrix_power(Q.mean(axis=0), int(tau)) + + A = Omega.copy() + for _ in range(int(tau)): + A = np.einsum("kij,jl,kml->im", Q, A, Q) / d + + RHS = Omega - C @ Omega - Omega @ C + A + RHS = 0.5 * (RHS + RHS.T) + + M = np.eye(d) - C + M = 0.5 * (M + M.T) + s, U = np.linalg.eigh(M) + if s.min() <= 1e-12: + raise ValueError("I - C* is singular; Xi* does not exist for this instance") + Theta = 1.0 / (s[:, None] + s[None, :]) + Xi = U @ (Theta * (U.T @ RHS @ U)) @ U.T + return 0.5 * (Xi + Xi.T) + + +def sandwich(Sigma_a, sigma2): + """Omega*/2, the exact-solver (tau -> infinity) limit. Used only by build-time checks.""" + return 0.5 * float(sigma2) * np.linalg.inv(np.asarray(Sigma_a, dtype=np.float64)) diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/requirements-verifier.txt b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..04676c89520bf969f2cb861ad1811f46d8370700 --- /dev/null +++ b/tasks/sketched-newton-cov-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/sketched-newton-cov-estimator/environment/are-grader-ctx/requirements.txt b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b2c8174712815cd13bff215d4cd4238b180df145 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,2 @@ +numpy==2.5.2 +scipy==1.18.0 diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/run_one.py b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/run_one.py new file mode 100644 index 0000000000000000000000000000000000000000..af571a6efcf203310615566af2bdd6970d8a130f --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/run_one.py @@ -0,0 +1,35 @@ +import argparse +import json +import sys +from pathlib import Path + +import numpy as np + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--workdir", required=True) + args = ap.parse_args() + work = Path(args.workdir) + + sys.path.insert(0, str(work / "harness")) + import runner + + spec = json.loads((work / "job.json").read_text()) + config = runner.make_config(spec["d"], spec["T"], spec["tau"]) + + A = np.load(work / "samples_a.npy", mmap_mode="r", allow_pickle=False) + b = np.load(work / "samples_b.npy", mmap_mode="r", allow_pickle=False) + stream = runner.stream_from_samples(A, b, config, spec["alg_seed"]) + + sys.path.insert(0, str(work / "solution")) + import estimator + + out = estimator.estimate(stream, config) + out = np.asarray(out, dtype=np.float64) + np.save(work / "out" / "result.npy", out, allow_pickle=False) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/test.sh b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e00b253a432a6114466365ece25cadaad54a6e8 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/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/ctrf.json /logs/verifier/metric.json + +printf '0\n' > /logs/verifier/reward.txt +trap 'if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /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/sketched-newton-cov-estimator/environment/are-grader-ctx/test_state.py b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..9e613b83cea5cbc42da34f3a9c870674f3a1c054 --- /dev/null +++ b/tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/test_state.py @@ -0,0 +1,39 @@ +import json +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import grader_core + +DELIVERABLE = Path(os.environ.get("GRADER_DELIVERABLE", "/app/output")) +SPLIT = os.environ.get("GRADE_SPLIT", "final") +SPLIT_DIR = Path(os.environ.get( + "GRADER_SPLIT_DIR", str(Path(__file__).resolve().parent / "hidden_data" / SPLIT))) +METRIC_PATH = Path(os.environ.get("GRADER_METRIC_PATH", "/logs/verifier/metric.json")) + + +def test_limiting_covariance_estimator(): + """Run the submitted estimator over every sealed instance and score its variance error. + + The agent's code runs only in per-replication subprocesses launched by grader_core, as a + non-root uid, with no access to the instance parameters or to the true covariance. This + process recomputes the metric from verifier-owned ground truth; nothing the submission + reports about itself is read. + """ + report = {"metric": None, "reward": 0.0, "split": SPLIT} + try: + report = grader_core.grade(str(SPLIT_DIR), str(DELIVERABLE)) + report["split"] = SPLIT + except Exception as exc: + report["error"] = f"{type(exc).__name__}: {exc}" + finally: + METRIC_PATH.parent.mkdir(parents=True, exist_ok=True) + METRIC_PATH.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n") + + print("") + for line in grader_core.summary_lines(report) if "error" not in report else \ + [f"grading failed: {report['error']}", "metric (lower is better) : n/a", + "reward : 0.000000"]: + print(line) + assert "error" not in report, report.get("error") diff --git a/tasks/sketched-newton-cov-estimator/environment/docker-compose.yaml b/tasks/sketched-newton-cov-estimator/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ef6545717170b23a2fa65d948a845e8e8d723319 --- /dev/null +++ b/tasks/sketched-newton-cov-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: "1500" + 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: "1500" + 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/sketched-newton-cov-estimator/task.toml b/tasks/sketched-newton-cov-estimator/task.toml index 719fcd701f50781109cdf85031789c201fb9c71c..39003460ef2af3afc168a414177c9b03b77fe06f 100644 --- a/tasks/sketched-newton-cov-estimator/task.toml +++ b/tasks/sketched-newton-cov-estimator/task.toml @@ -1,57 +1,71 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/sketched-newton-cov-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 = "Model Training and ML Infrastructure" subcategory = "Evaluation infrastructure" -task_objective = [ "Implement", "Optimize",] -artifact_type = [ "Single script or program",] +task_objective = [ + "Implement", + "Optimize", +] +artifact_type = [ + "Single script or program", +] expert_time_estimate_hours = 6.0 +are_version = "1.1" +budget_seconds = 86400 [verifier] -timeout_sec = 1500.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/sketched-newton-cov-estimator/tests/Dockerfile b/tasks/sketched-newton-cov-estimator/tests/Dockerfile index b5a4bb6526d3299406eeff96b12dda06f7527a97..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/sketched-newton-cov-estimator/tests/Dockerfile +++ b/tasks/sketched-newton-cov-estimator/tests/Dockerfile @@ -1,31 +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 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 +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/sketched-newton-cov-estimator/tests/finalize.py b/tasks/sketched-newton-cov-estimator/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/sketched-newton-cov-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/sketched-newton-cov-estimator/tests/test.sh b/tasks/sketched-newton-cov-estimator/tests/test.sh index 9e00b253a432a6114466365ece25cadaad54a6e8..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/sketched-newton-cov-estimator/tests/test.sh +++ b/tasks/sketched-newton-cov-estimator/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 - -printf '0\n' > /logs/verifier/reward.txt -trap 'if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /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 +python3 /tests/finalize.py diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/.dockerignore b/tasks/sopcc-online-chance-constrained-policy/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/Dockerfile b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eecf368ab2e270d72769fce908d380caafac46d0 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/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/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/Dockerfile.are b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..af832a8f3c5a676dce9b48b2d6464eaa78799f39 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/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/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/are/drain.py b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/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/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/are/server.py b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/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/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/compute_reward.py b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..711a62a5a0d08a6a0956ab171990c6d9f5dca07a --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/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/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/grader_core.py b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..606789088fce4a400b64599484828c02b122a180 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import sopcc + +HIDDEN = Path(__file__).resolve().parent / "hidden_data" +SPLITS = ("final", "intermediate") + +ANCHORS = { + + "final": (4.212162974044415, 5.403678393388951), + "intermediate": (4.90108511497506, 5.935456731233547), +} + + +def load_panel(split: str): + """The sealed panel for `split`: instances plus their pre-drawn cost noise.""" + if split not in SPLITS: + raise ValueError(f"unknown split {split!r}") + with np.load(HIDDEN / split / "panel.npz") as data: + coords, rewards, noise, draw = (data["coords"], data["rewards"], + data["noise"], data["draw"]) + return [ + {"draw": int(draw[i]), "index": i, + "instance": sopcc.instance_from_arrays(coords[i], rewards[i]), + "noise": noise[i]} + for i in range(coords.shape[0]) + ] + + +def graded_reward(metric: float, split: str) -> float: + """Map the raw metric to a reward in [0, 1): 0 at m0, 0.5 at m_ref, no cutoff above.""" + m0, m_ref = ANCHORS[split] + x_ref = m_ref - m0 + if not x_ref > 0: + raise AssertionError("malformed task: the reference does not beat the trivial baseline") + if not np.isfinite(metric): + return 0.0 + u = max(0.0, float(metric) - m0) / x_ref + return u / (1.0 + u) diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/final/panel.npz b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/final/panel.npz new file mode 100644 index 0000000000000000000000000000000000000000..1235c4dd1e964c052bf176ccc6bbd1a7dc25a050 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/final/panel.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b034f0a99b9a9f72228a791c6216acbf68dc22dc33fc3f6d4ededd34f0330a7f +size 605757 diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/intermediate/panel.npz b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/intermediate/panel.npz new file mode 100644 index 0000000000000000000000000000000000000000..e90c7a60c23279ec1f75f0978e07fcffa19aae32 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/intermediate/panel.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c457412f004826b4404e915b5b81e17400cef99f395d5bb76241ea770f2aaeb4 +size 605708 diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/intermediate.sh b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..137c82cad46d77990b2aee4d2f80fb3a57716a62 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,29 @@ +#!/bin/bash + + +set -u + + + +reward_floor() { + if [ ! -s /logs/verifier/reward.txt ]; then + mkdir -p /logs/verifier + printf '0\n' > /logs/verifier/reward.txt + fi +} +trap reward_floor EXIT + +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 + +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/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/policy_worker.py b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/policy_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..e8bf3c99d4ffa5f64c330feae9268ffe5e83048c --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/policy_worker.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import importlib.util +import json +import os +import resource +import sys +import traceback + + +def _fail(reply, stage, exc): + reply({"ok": False, "stage": stage, "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(limit=6)[-1200:]}) + + +def _apply_limits(limits: dict) -> None: + """Cap this process before any candidate code is imported. + + Set here rather than by the caller so there is no window between exec and the cap, and + the hard limit is set too: candidate code can lower these but never raise them. + """ + cpu = int(limits["cpu_seconds"]) + resource.setrlimit(resource.RLIMIT_CPU, (cpu + 1, cpu + 3)) + for name, key in (("RLIMIT_AS", "address_space_bytes"), + ("RLIMIT_FSIZE", "file_size_bytes"), + ("RLIMIT_NOFILE", "open_files")): + value = int(limits[key]) + soft, hard = resource.getrlimit(getattr(resource, name)) + if hard != resource.RLIM_INFINITY: + value = min(value, hard) + resource.setrlimit(getattr(resource, name), (value, value)) + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + + +def main() -> int: + solution_dir = os.path.abspath(sys.argv[1]) + entry = os.path.join(solution_dir, "policy.py") + _apply_limits(json.loads(sys.argv[2])) + + reply_fd = os.dup(1) + os.dup2(2, 1) + sys.stdout = sys.stderr + channel = os.fdopen(reply_fd, "w", buffering=1) + + def reply(obj): + channel.write(json.dumps(obj) + "\n") + channel.flush() + + import numpy as np + try: + import torch + torch.set_num_threads(1) + except ImportError: + pass + + policy = None + for raw in sys.stdin: + raw = raw.strip() + if not raw: + continue + msg = json.loads(raw) + cmd = msg.get("cmd") + + if cmd == "init": + if not os.path.isfile(entry): + reply({"ok": False, "stage": "import", "error": f"no entry point at {entry}"}) + return 0 + try: + if solution_dir not in sys.path: + sys.path.insert(0, solution_dir) + spec = importlib.util.spec_from_file_location("candidate_policy", entry) + module = importlib.util.module_from_spec(spec) + sys.modules["candidate_policy"] = module + spec.loader.exec_module(module) + policy_cls = getattr(module, "Policy") + except Exception as exc: + _fail(reply, "import", exc) + return 0 + try: + policy = policy_cls(int(msg["seed"])) + except Exception as exc: + _fail(reply, "construct", exc) + return 0 + try: + instance = { + "coords": np.asarray(msg["instance"]["coords"], dtype=np.float64), + "rewards": np.asarray(msg["instance"]["rewards"], dtype=np.float64), + "dist": np.asarray(msg["instance"]["dist"], dtype=np.float64), + "start": int(msg["instance"]["start"]), + "goal": int(msg["instance"]["goal"]), + "budget": float(msg["instance"]["budget"]), + "p_fail": float(msg["instance"]["p_fail"]), + "cost_model": str(msg["instance"]["cost_model"]), + } + policy.prepare(instance) + except Exception as exc: + _fail(reply, "prepare", exc) + return 0 + reply({"ok": True}) + + elif cmd == "act": + obs = msg["obs"] + obs = { + "current": int(obs["current"]), + "visited": np.asarray(obs["visited"], dtype=bool), + "remaining_budget": float(obs["remaining_budget"]), + "collected_reward": float(obs["collected_reward"]), + "step": int(obs["step"]), + } + try: + action = policy.act(obs) + except Exception as exc: + reply({"ok": False, "stage": "act", + "error": f"{type(exc).__name__}: {exc}"}) + continue + if isinstance(action, bool) or not isinstance(action, (int, np.integer)): + reply({"ok": True, "action": None, + "kind": type(action).__name__}) + else: + reply({"ok": True, "action": int(action)}) + + elif cmd == "bye": + return 0 + + else: + reply({"ok": False, "stage": "protocol", "error": f"unknown command {cmd!r}"}) + return 0 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/requirements-verifier.txt b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..04676c89520bf969f2cb861ad1811f46d8370700 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/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/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/requirements.txt b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..01ccb069ac7a13550ab665749d672a28a21aaada --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,5 @@ +--index-url https://download.pytorch.org/whl/cpu +--extra-index-url https://pypi.org/simple +numpy==2.5.2 +scipy==1.18.0 +torch==2.13.0+cpu diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/runner.py b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..5d41a6bdb2a42a69e51742ed157698e86f7d1402 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/runner.py @@ -0,0 +1,517 @@ +from __future__ import annotations + +import ctypes +import json +import os +import resource +import select +import shutil +import signal +import stat +import sys +import tempfile +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field + +import numpy as np + + + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import sopcc + +CLOCK_TICKS = os.sysconf("SC_CLK_TCK") +CPU_POLL_INTERVAL = 2.0 +PR_SET_CHILD_SUBREAPER = 36 + +_LOCK = threading.Lock() +_WORKERS: set[int] = set() +_ESCAPED_CPU = 0.0 + + +@dataclass +class Sandbox: + """Resource and privilege policy applied to every candidate process.""" + + cpu_seconds: float = 75.0 + timeout: float = 150.0 + address_space_bytes: int = 6 * 1024 ** 3 + file_size_bytes: int = 64 * 1024 ** 2 + open_files: int = 256 + run_as_uid: int | None = None + run_as_gid: int | None = None + new_session: bool = True + env: dict = field(default_factory=dict) + + +class WorkerGone(Exception): + """The candidate process died, hung, or stopped speaking the protocol.""" + + +class _LineChannel: + """Deadline-bounded line reads straight off a pipe fd.""" + + def __init__(self, fd: int): + self.fd = fd + self.buf = b"" + + def readline(self, deadline: float) -> bytes: + while b"\n" not in self.buf: + left = deadline - time.monotonic() + if left <= 0: + raise WorkerGone("wall-clock budget exhausted") + ready, _, _ = select.select([self.fd], [], [], min(left, 0.5)) + if not ready: + continue + chunk = os.read(self.fd, 1 << 16) + if not chunk: + raise WorkerGone("candidate process closed the channel") + self.buf += chunk + line, _, self.buf = self.buf.partition(b"\n") + return line + + +def _write_line(fd: int, payload: bytes, deadline: float) -> None: + view = memoryview(payload + b"\n") + while view: + left = deadline - time.monotonic() + if left <= 0: + raise WorkerGone("wall-clock budget exhausted") + _, ready, _ = select.select([], [fd], [], min(left, 0.5)) + if not ready: + continue + try: + written = os.write(fd, view) + except (BrokenPipeError, OSError) as exc: + raise WorkerGone(f"candidate process is not reading: {exc}") from exc + view = view[written:] + + +def _become_subreaper() -> None: + """Adopt orphaned descendants of every candidate instead of leaving them to init. + + A candidate that forks and lets the parent exit would otherwise hand the orphan to pid 1, + outside any tree walked below. With this set, such an orphan is re-parented to this process, + where `_tree` recognises it (a child of ours that is not a worker we started) and it is + charged, killed and reaped along with the candidate's own tree. + """ + try: + ctypes.CDLL(None, use_errno=True).prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) + except (OSError, AttributeError): + pass + + +def _scan() -> dict[int, tuple[int, float]]: + """pid -> (ppid, CPU seconds) for every live process. + + The CPU figure is utime + stime + cutime + cstime: the process's own threads plus every + child it has already reaped, so a helper that burns CPU and exits between two scans is + still charged to whoever reaped it. + """ + procs: dict[int, tuple[int, float]] = {} + try: + names = os.listdir("/proc") + except OSError: + return procs + for name in names: + if not name.isdigit(): + continue + try: + with open(f"/proc/{name}/stat", "rb") as fh: + raw = fh.read() + except OSError: + continue + cut = raw.rfind(b")") + if cut < 0: + continue + fields = raw[cut + 2:].split() + if len(fields) < 15: + continue + try: + procs[int(name)] = (int(fields[1]), + sum(int(f) for f in fields[11:15]) / CLOCK_TICKS) + except ValueError: + continue + return procs + + +def _tree(procs: dict[int, tuple[int, float]], root: int) -> tuple[set[int], set[int]]: + """(`root` plus its live descendants, adopted orphans plus theirs), both by parent pid. + + Parentage is what setsid(2) cannot change, which is why the session id is not used. An + adopted orphan (a child of this process that is not a worker it started) cannot be + attributed to one instance, so it is charged to every instance: the candidate is the same + code in each of them. Call with `_LOCK` held. + """ + children: dict[int, list[int]] = {} + for pid, (ppid, _) in procs.items(): + children.setdefault(ppid, []).append(pid) + + def walk(roots) -> set[int]: + members: set[int] = set() + stack = list(roots) + while stack: + pid = stack.pop() + if pid in members: + continue + members.add(pid) + stack.extend(children.get(pid, [])) + return members + + own = walk([root]) + orphans = walk(pid for pid in children.get(os.getpid(), []) if pid not in _WORKERS) - own + return own, orphans + + +def _charge(procs: dict[int, tuple[int, float]], own: set[int], orphans: set[int]) -> float: + return sum(procs[pid][1] for pid in own | orphans if pid in procs) + _ESCAPED_CPU + + +def _tree_cpu(root: int) -> float: + """CPU seconds the instance rooted at `root` is charged for right now.""" + with _LOCK: + procs = _scan() + return _charge(procs, *_tree(procs, root)) + + +def _end_instance(proc) -> float: + """Kill the instance's tree, reap what this process adopted, and return the final charge.""" + global _ESCAPED_CPU + with _LOCK: + procs = _scan() + own, orphans = _tree(procs, proc.pid) + charge = _charge(procs, own, orphans) + try: + os.killpg(proc.pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError, OSError): + pass + for _ in range(2): + for pid in set().union(*_tree(_scan(), proc.pid)): + try: + os.kill(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError, OSError): + pass + try: + proc.stdin.close() + proc.stdout.close() + except OSError: + pass + try: + proc.wait(timeout=10) + except Exception: + pass + _WORKERS.discard(proc.pid) + + + + deadline = time.monotonic() + 5.0 + while True: + pending = 0 + for pid, (ppid, cpu) in _scan().items(): + if ppid != os.getpid() or pid in _WORKERS: + continue + try: + reaped, _ = os.waitpid(pid, os.WNOHANG) + except ChildProcessError: + continue + if not reaped: + pending += 1 + elif pid not in own: + _ESCAPED_CPU += cpu + if not pending or time.monotonic() >= deadline: + break + time.sleep(0.05) + return charge + + +def validate_solution_dir(path: str, max_bytes: int) -> tuple[bool, str, int]: + """Reject a deliverable tree that is missing, oversized, or contains links. + + A symlink or a hard link inside a tree the harness copies is an attempt to make a + privileged copy materialise a file from somewhere else, so it is refused outright + rather than followed. + """ + if not os.path.isdir(path): + return False, f"no deliverable directory at {path}", 0 + if os.path.islink(path): + return False, "deliverable directory is a symlink", 0 + total = 0 + for root, dirs, files in os.walk(path, followlinks=False): + for name in dirs + files: + full = os.path.join(root, name) + info = os.lstat(full) + if stat.S_ISLNK(info.st_mode): + return False, f"symlink in deliverable: {os.path.relpath(full, path)}", total + if stat.S_ISREG(info.st_mode): + if info.st_nlink > 1: + return False, f"hard link in deliverable: {os.path.relpath(full, path)}", total + total += info.st_size + elif not stat.S_ISDIR(info.st_mode): + return False, f"non-regular file in deliverable: {os.path.relpath(full, path)}", total + if total > max_bytes: + return False, f"deliverable exceeds {max_bytes} bytes", total + if not os.path.isfile(os.path.join(path, "policy.py")): + return False, f"no entry point at {os.path.join(path, 'policy.py')}", total + return True, "ok", total + + +def stage_candidate(src: str, dst: str, own_uid: int | None = None) -> str: + """Copy a validated deliverable to a location the candidate cannot rewrite mid-grade. + + `src` is treated as hostile and must already have passed `validate_solution_dir`; the + copy keeps symlinks as symlinks rather than following them. The caller is responsible + for `dst`'s parent being traversable by the uid the candidate runs as. + """ + if os.path.exists(dst): + shutil.rmtree(dst) + shutil.copytree(src, dst, symlinks=True) + for root, dirs, files in os.walk(dst): + for name in dirs: + os.chmod(os.path.join(root, name), 0o755) + for name in files: + os.chmod(os.path.join(root, name), 0o644) + os.chmod(dst, 0o755) + if own_uid is not None: + for root, dirs, files in os.walk(dst): + for name in dirs + files: + os.chown(os.path.join(root, name), own_uid, own_uid) + os.chown(dst, own_uid, own_uid) + return dst + + +def _instance_payload(instance: dict) -> dict: + return { + "coords": instance["coords"].tolist(), + "rewards": instance["rewards"].tolist(), + "dist": instance["dist"].tolist(), + "start": int(instance["start"]), + "goal": int(instance["goal"]), + "budget": float(instance["budget"]), + "p_fail": float(instance["p_fail"]), + "cost_model": str(instance["cost_model"]), + } + + +def run_instance( + sandbox: Sandbox, + candidate_dir: str, + worker_path: str, + python_exe: str, + instance: dict, + noise: np.ndarray, + seed: int, + episodes: int = sopcc.EPISODES_PER_INSTANCE, +) -> dict: + """Grade one instance: `episodes` episodes of one candidate process.""" + import subprocess + + limits = { + "cpu_seconds": float(sandbox.cpu_seconds), + "address_space_bytes": int(sandbox.address_space_bytes), + "file_size_bytes": int(sandbox.file_size_bytes), + "open_files": int(sandbox.open_files), + } + cmd = [python_exe, "-I", "-B", worker_path, candidate_dir, json.dumps(limits)] + privilege = {} + if sandbox.run_as_uid is not None: + privilege = {"user": int(sandbox.run_as_uid), + "group": int(sandbox.run_as_gid if sandbox.run_as_gid is not None + else sandbox.run_as_uid), + "extra_groups": []} + + + + scratch = tempfile.mkdtemp(prefix="sopcc-run-") + if sandbox.run_as_uid is not None: + os.chown(scratch, int(sandbox.run_as_uid), + int(sandbox.run_as_gid if sandbox.run_as_gid is not None + else sandbox.run_as_uid)) + os.chmod(scratch, 0o700) + env = { + "PATH": "/usr/local/bin:/usr/local/sbin:/usr/bin:/bin", + "HOME": scratch, + "TMPDIR": scratch, + "PYTHONHASHSEED": "0", + "PYTHONDONTWRITEBYTECODE": "1", + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", + } + env.update(sandbox.env) + + errlog = open(os.path.join(scratch, "stderr.log"), "w+b") + deadline = time.monotonic() + float(sandbox.timeout) + report = { + "seed": int(seed), + "episodes": [], + "cpu_seconds": 0.0, + "wall_seconds": 0.0, + "abort": None, + "stderr_tail": "", + } + started = time.monotonic() + proc = None + _become_subreaper() + try: + with _LOCK: + proc = subprocess.Popen( + cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=errlog, + cwd="/", + env=env, + close_fds=True, + start_new_session=bool(sandbox.new_session), + **privilege, + ) + _WORKERS.add(proc.pid) + try: + resource.prlimit(proc.pid, resource.RLIMIT_CPU, + (int(sandbox.cpu_seconds) + 1, int(sandbox.cpu_seconds) + 3)) + except (PermissionError, ProcessLookupError, OSError): + pass + reader = _LineChannel(proc.stdout.fileno()) + writer = proc.stdin.fileno() + + next_poll = [time.monotonic()] + + def _exchange(payload: dict) -> dict: + _write_line(writer, json.dumps(payload).encode(), deadline) + now = time.monotonic() + if now >= next_poll[0]: + next_poll[0] = now + CPU_POLL_INTERVAL + cpu = _tree_cpu(proc.pid) + report["cpu_seconds"] = max(report["cpu_seconds"], cpu) + if cpu > sandbox.cpu_seconds: + raise WorkerGone(f"cpu budget exhausted ({cpu:.1f}s)") + line = reader.readline(deadline) + try: + return json.loads(line) + except (ValueError, UnicodeDecodeError) as exc: + raise WorkerGone(f"unparseable reply: {exc}") from exc + + ack = _exchange({"cmd": "init", "seed": int(seed), + "instance": _instance_payload(instance)}) + if not ack.get("ok"): + report["abort"] = f"{ack.get('stage', 'init')}: {ack.get('error', 'refused')}" + raise WorkerGone(report["abort"]) + + for episode in range(int(episodes)): + def choose(obs): + message = { + "cmd": "act", + "obs": { + "current": int(obs["current"]), + "visited": [bool(v) for v in obs["visited"]], + "remaining_budget": float(obs["remaining_budget"]), + "collected_reward": float(obs["collected_reward"]), + "step": int(obs["step"]), + }, + } + answer = _exchange(message) + if not answer.get("ok"): + raise sopcc.InvalidAction( + f"policy raised {answer.get('error', 'an exception')}") + action = answer.get("action") + if action is None: + raise sopcc.InvalidAction( + f"action is {answer.get('kind', 'None')}, not an int") + return int(action) + + outcome = sopcc.run_episode(instance, noise[episode], choose) + report["episodes"].append(outcome) + except WorkerGone as exc: + report["abort"] = report["abort"] or str(exc) + except Exception as exc: + report["abort"] = f"{type(exc).__name__}: {exc}" + finally: + if proc is not None: + report["cpu_seconds"] = max(report["cpu_seconds"], _end_instance(proc)) + report["wall_seconds"] = time.monotonic() - started + try: + errlog.seek(0) + report["stderr_tail"] = errlog.read(4096).decode("utf-8", "replace") + except OSError: + pass + errlog.close() + shutil.rmtree(scratch, ignore_errors=True) + + while len(report["episodes"]) < int(episodes): + report["episodes"].append( + {"delivered": 0.0, "failed": True, + "reason": f"aborted: {report['abort'] or 'unknown'}", "visits": 0, + "traversals": 0}) + return report + + +def grade_panel( + panel, + sandbox: Sandbox, + candidate_dir: str, + worker_path: str, + python_exe: str | None = None, + workers: int = 8, + seed_base: int = 1000, + episodes: int = sopcc.EPISODES_PER_INSTANCE, + retry_budget: int = 4, +) -> dict: + """Grade a whole panel, at most `workers` instances at a time, and aggregate the metric.""" + python_exe = python_exe or sys.executable + reports: list[dict | None] = [None] * len(panel) + with ThreadPoolExecutor(max_workers=max(1, min(workers, len(panel)))) as pool: + futures = { + pool.submit( + run_instance, sandbox, candidate_dir, worker_path, python_exe, + panel[i]["instance"], panel[i]["noise"], seed_base + i, episodes, + ): i + for i in range(len(panel)) + } + for future, i in futures.items(): + reports[i] = future.result() + + + + + retries = [] + for i, report in enumerate(reports): + if retry_budget <= 0: + break + abort = report["abort"] or "" + infra = ("closed the channel" in abort) or ("is not reading" in abort) + if not infra or report["wall_seconds"] > 0.25 * sandbox.timeout: + continue + retry_budget -= 1 + retries.append({"instance": i, "first_abort": abort}) + reports[i] = run_instance( + sandbox, candidate_dir, worker_path, python_exe, + panel[i]["instance"], panel[i]["noise"], seed_base + i, episodes) + + delivered, failed, draws = [], [], [] + for i, report in enumerate(reports): + for outcome in report["episodes"]: + delivered.append(outcome["delivered"]) + failed.append(outcome["failed"]) + draws.append(panel[i].get("draw", 0)) + summary = sopcc.panel_metric(delivered, failed) + delivered_arr = np.asarray(delivered, dtype=np.float64) + failed_arr = np.asarray(failed, dtype=bool) + draw_arr = np.asarray(draws, dtype=np.int64) + per_draw = {} + for draw in sorted(set(draws)): + mask = draw_arr == draw + per_draw[int(draw)] = sopcc.panel_metric(delivered_arr[mask], failed_arr[mask]) + summary["per_draw"] = per_draw + summary["draw_metric_mean"] = float( + np.mean([per_draw[d]["metric"] for d in sorted(per_draw)])) if per_draw else 0.0 + summary["instances"] = len(panel) + summary["retried_instances"] = retries + summary["aborted_instances"] = sum(1 for r in reports if r["abort"]) + summary["max_cpu_seconds"] = max((r["cpu_seconds"] for r in reports), default=0.0) + summary["max_wall_seconds"] = max((r["wall_seconds"] for r in reports), default=0.0) + summary["reports"] = reports + return summary diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/sopcc.py b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/sopcc.py new file mode 100644 index 0000000000000000000000000000000000000000..a9070eca242226f7bf62e4702fad58dafac7ad76 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/sopcc.py @@ -0,0 +1,212 @@ +from __future__ import annotations + +import numpy as np + + +N_VERTICES = 40 +START = 0 +GOAL = 1 +BUDGET = 2.0 +P_FAIL = 0.1 +COST_MODEL = "exponential_mean_equals_euclidean" + + +EPISODES_PER_INSTANCE = 32 +MAX_TRAVERSALS = 48 + + +FAILURE_ALLOWANCE = 0.10 +PENALTY_SLOPE = 10.0 + + +DEV_ENTROPY = 20240917 +DEV_DRAWS = 4 +DEV_INSTANCES_PER_DRAW = 50 + + +def instance_seed(entropy: int, index: int) -> np.random.SeedSequence: + """Seed sequence for instance `index` of the family rooted at `entropy`.""" + return np.random.SeedSequence(entropy=int(entropy), spawn_key=(int(index), 0)) + + +def noise_seed(entropy: int, index: int, variant: int = 0) -> np.random.SeedSequence: + """Seed sequence for the pre-drawn cost noise of instance `index`. + + `variant` draws an independent noise realisation for the same instance, which is how the + build measures the metric's own sampling noise. + """ + key = (int(index), 1) if int(variant) == 0 else (int(index), 1, int(variant)) + return np.random.SeedSequence(entropy=int(entropy), spawn_key=key) + + +def euclidean_matrix(coords: np.ndarray) -> np.ndarray: + diff = coords[:, None, :] - coords[None, :, :] + dist = np.sqrt((diff * diff).sum(axis=-1)) + np.fill_diagonal(dist, 0.0) + return dist + + +def make_instance(seed_sequence: np.random.SeedSequence) -> dict: + """One SOPCC instance: complete graph, U[0,1]^2 coordinates, U[0,1] vertex rewards. + + The start and goal vertex rewards are forced to 0.0, so no reward is collected for + free by starting or finishing. + """ + rng = np.random.Generator(np.random.PCG64(seed_sequence)) + coords = rng.random((N_VERTICES, 2)) + rewards = rng.random(N_VERTICES) + rewards[START] = 0.0 + rewards[GOAL] = 0.0 + return instance_from_arrays(coords, rewards) + + +def instance_from_arrays(coords: np.ndarray, rewards: np.ndarray) -> dict: + coords = np.ascontiguousarray(coords, dtype=np.float64) + rewards = np.ascontiguousarray(rewards, dtype=np.float64) + return { + "coords": coords, + "rewards": rewards, + "dist": euclidean_matrix(coords), + "start": START, + "goal": GOAL, + "budget": BUDGET, + "p_fail": P_FAIL, + "cost_model": COST_MODEL, + } + + +def make_noise( + seed_sequence: np.random.SeedSequence, + episodes: int = EPISODES_PER_INSTANCE, + traversals: int = MAX_TRAVERSALS, +) -> np.ndarray: + """Pre-drawn unit-Exponential cost multipliers, one row of `traversals` per episode. + + The realised cost of the k-th traversal of an episode is `dist[u, v] * noise[k]`, so + every traversal costs an Exponential variate with mean equal to the Euclidean edge + length, and two submissions see the identical random stream. + """ + rng = np.random.Generator(np.random.PCG64(seed_sequence)) + return rng.exponential(1.0, size=(int(episodes), int(traversals))) + + +def make_dev_panel(draws: int = DEV_DRAWS, instances_per_draw: int = DEV_INSTANCES_PER_DRAW): + """The public dev panel: `draws` independent draws of `instances_per_draw` instances.""" + panel = [] + for draw in range(int(draws)): + for k in range(int(instances_per_draw)): + index = draw * int(instances_per_draw) + k + panel.append( + { + "draw": draw, + "index": index, + "instance": make_instance(instance_seed(DEV_ENTROPY, index)), + "noise": make_noise(noise_seed(DEV_ENTROPY, index)), + } + ) + return panel + + +class InvalidAction(Exception): + """The policy returned something that is not a legal next vertex.""" + + +def check_action(action, current: int, visited: np.ndarray) -> int: + """Validate one action, returning it as an int or raising InvalidAction.""" + if isinstance(action, bool) or not isinstance(action, (int, np.integer)): + raise InvalidAction(f"action is {type(action).__name__}, not an int") + a = int(action) + if not 0 <= a < N_VERTICES: + raise InvalidAction(f"action {a} out of range") + if a == current: + raise InvalidAction("action is the current vertex") + if a != GOAL and visited[a]: + raise InvalidAction(f"action {a} is an already visited vertex") + return a + + +def run_episode(instance: dict, noise_row: np.ndarray, choose) -> dict: + """Drive one episode. `choose(obs)` returns the next vertex, or raises. + + Returns a dict with `delivered` (0.0 unless the goal was reached inside budget), + `failed`, `reason`, `visits` (count of distinct non-start vertices collected) and + `traversals`. + """ + dist = instance["dist"] + rewards = instance["rewards"] + visited = np.zeros(N_VERTICES, dtype=bool) + visited[START] = True + current = START + remaining = float(instance["budget"]) + collected = 0.0 + step = 0 + + while True: + if step >= MAX_TRAVERSALS: + return _failed("traversal_cap", collected, step) + obs = { + "current": int(current), + "visited": visited.copy(), + "remaining_budget": float(remaining), + "collected_reward": float(collected), + "step": int(step), + } + try: + action = check_action(choose(obs), current, visited) + except InvalidAction as exc: + return _failed(f"invalid_action: {exc}", collected, step) + cost = float(dist[current, action]) * float(noise_row[step]) + remaining -= cost + step += 1 + if remaining < 0.0: + return _failed("budget_exhausted", collected, step) + if action == GOAL: + return { + "delivered": float(collected), + "failed": False, + "reason": "goal", + "visits": int(visited.sum()) - 1, + "traversals": step, + "remaining_budget": float(remaining), + } + visited[action] = True + collected += float(rewards[action]) + current = action + + +def _failed(reason: str, collected: float, step: int) -> dict: + return { + "delivered": 0.0, + "failed": True, + "reason": reason, + "visits": 0, + "traversals": int(step), + "collected_when_failed": float(collected), + } + + +def penalty(failure_rate: float) -> float: + """1.0 while the failure rate respects the allowance, ramping linearly to 0.0.""" + f = float(failure_rate) + if f <= FAILURE_ALLOWANCE: + return 1.0 + return max(0.0, 1.0 - PENALTY_SLOPE * (f - FAILURE_ALLOWANCE)) + + +def panel_metric(delivered, failed) -> dict: + """Penalised mean delivered reward over a panel of episodes.""" + delivered = np.asarray(delivered, dtype=np.float64) + failed = np.asarray(failed, dtype=bool) + if delivered.size == 0: + return {"metric": 0.0, "R": 0.0, "F": 1.0, "penalty": 0.0, "episodes": 0} + R = float(delivered.mean()) + F = float(failed.mean()) + p = penalty(F) + return { + "metric": R * p, + "R": R, + "F": F, + "penalty": p, + "episodes": int(delivered.size), + "delivered_std": float(delivered.std(ddof=1)) if delivered.size > 1 else 0.0, + } diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test.sh b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..492622781afd2c06d496f7c30e2e3616b2145647 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test.sh @@ -0,0 +1,30 @@ +#!/bin/bash + + + +set -u + + + +reward_floor() { + if [ ! -s /logs/verifier/reward.txt ]; then + mkdir -p /logs/verifier + printf '0\n' > /logs/verifier/reward.txt + fi +} +trap reward_floor EXIT + +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 + +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/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test_state.py b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..682e8710f93219e95b8a0c0a86f36df7d716e86c --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test_state.py @@ -0,0 +1,229 @@ +from __future__ import annotations + +import collections +import json +import os +import shutil +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import grader_core +import runner +import sopcc + +TESTS = Path(__file__).resolve().parent +DELIVERABLE = Path("/app/solution") +STAGING = Path("/tmp/sopcc-candidate") +LOGS = Path("/logs/verifier") + + +MAX_DELIVERABLE_BYTES = 50 * 1024 * 1024 +CPU_SECONDS_PER_INSTANCE = 75.0 +WALL_SECONDS_PER_INSTANCE = 150.0 +ADDRESS_SPACE_BYTES = 6 * 1024 ** 3 +FILE_SIZE_BYTES = 64 * 1024 ** 2 +OPEN_FILES = 256 +AGENT_UID = 1001 +AGENT_GID = 1001 +WORKERS = 8 + + + + + + + + +SANDBOX = runner.Sandbox( + cpu_seconds=CPU_SECONDS_PER_INSTANCE, + timeout=WALL_SECONDS_PER_INSTANCE, + address_space_bytes=ADDRESS_SPACE_BYTES, + file_size_bytes=FILE_SIZE_BYTES, + open_files=OPEN_FILES, + run_as_uid=AGENT_UID, + run_as_gid=AGENT_GID, + new_session=True, +) + + +def _write_metric(payload: dict) -> None: + LOGS.mkdir(parents=True, exist_ok=True) + (LOGS / "metric.json").write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + + +def _redacted(split: str) -> bool: + """The intermediate grader's stdout goes back to the agent, so it stays aggregate-only.""" + return split != "final" + + +@pytest.fixture(scope="session") +def graded() -> dict: + """Grade the sealed panel exactly once, and write the metric file.""" + split = os.environ.get("GRADE_SPLIT", "final") + payload = { + "split": split, + "metric": 0.0, + "reward": 0.0, + "R": 0.0, + "F": 1.0, + "penalty": 0.0, + "valid": False, + "reason": "grading did not complete", + } + _write_metric(payload) + + if split not in grader_core.SPLITS: + payload["reason"] = f"unknown split {split!r}" + _write_metric(payload) + return payload + + ok, reason, size = runner.validate_solution_dir(str(DELIVERABLE), MAX_DELIVERABLE_BYTES) + payload["deliverable_bytes"] = size + if not ok: + payload["reason"] = f"deliverable rejected: {reason}" + _write_metric(payload) + return payload + + panel = grader_core.load_panel(split) + STAGING.parent.mkdir(parents=True, exist_ok=True) + if STAGING.exists(): + shutil.rmtree(STAGING) + STAGING.mkdir() + STAGING.chmod(0o755) + candidate = runner.stage_candidate(str(DELIVERABLE), str(STAGING / "solution")) + + + + + worker = STAGING / "policy_worker.py" + shutil.copyfile(TESTS / "policy_worker.py", worker) + os.chown(worker, 0, 0) + worker.chmod(0o644) + + summary = runner.grade_panel( + panel, SANDBOX, candidate, + worker_path=str(worker), + python_exe=sys.executable, + workers=WORKERS, + episodes=sopcc.EPISODES_PER_INSTANCE, + ) + reasons = collections.Counter() + aborts = [] + for i, report in enumerate(summary["reports"]): + for outcome in report["episodes"]: + if outcome["failed"]: + reasons[outcome["reason"].split(":")[0]] += 1 + if report["abort"]: + aborts.append({ + "instance": i, + "abort": report["abort"], + "cpu_seconds": report["cpu_seconds"], + "wall_seconds": report["wall_seconds"], + + + "unexplained": (("closed the channel" in report["abort"] + or "is not reading" in report["abort"]) + and report["wall_seconds"] < 0.25 * WALL_SECONDS_PER_INSTANCE + and report["cpu_seconds"] < 0.5 * CPU_SECONDS_PER_INSTANCE), + }) + + payload.update({ + "metric": summary["metric"], + "reward": grader_core.graded_reward(summary["metric"], split), + "R": summary["R"], + "F": summary["F"], + "penalty": summary["penalty"], + "episodes": summary["episodes"], + "instances": summary["instances"], + "per_draw_metric": {str(d): summary["per_draw"][d]["metric"] + for d in sorted(summary["per_draw"])}, + "per_draw_F": {str(d): summary["per_draw"][d]["F"] + for d in sorted(summary["per_draw"])}, + "delivered_std": summary["delivered_std"], + "failure_reasons": dict(reasons), + "aborted_instances": summary["aborted_instances"], + "aborts": aborts, + "unexplained_aborts": sum(1 for a in aborts if a["unexplained"]), + "retried_instances": summary["retried_instances"], + "max_cpu_seconds": summary["max_cpu_seconds"], + "max_wall_seconds": summary["max_wall_seconds"], + "valid": True, + "reason": "ok", + }) + _write_metric(payload) + + if _redacted(split): + print(f"episodes: {payload['episodes']} over {payload['instances']} instances") + print(f"failure rate F: {payload['F']:.4f} penalty factor: {payload['penalty']:.4f}") + print("failure rate per draw: " + ", ".join( + f"{d}={v:.4f}" for d, v in payload["per_draw_F"].items())) + print("failure reasons: " + (", ".join( + f"{k}={v}" for k, v in sorted(reasons.items())) or "none")) + print(f"largest per-instance cpu {payload['max_cpu_seconds']:.1f}s of " + f"{CPU_SECONDS_PER_INSTANCE:.0f}s, wall {payload['max_wall_seconds']:.1f}s of " + f"{WALL_SECONDS_PER_INSTANCE:.0f}s") + print(f"instances that ended early: {payload['aborted_instances']}" + + (" (" + "; ".join(a["abort"][:80] for a in aborts[:3]) + ")" if aborts else "")) + else: + print(json.dumps({k: v for k, v in payload.items() if k != "failure_reasons"}, + indent=2, sort_keys=True)) + print("failure reasons: " + json.dumps(dict(reasons), sort_keys=True)) + return payload + + +def test_deliverable_runs(graded): + """The submitted policy must exist, import, and answer decisions at all. + + WHY: everything else is meaningless if the deliverable never ran. A missing, oversized, + link-bearing or unimportable deliverable is scored 0 rather than skipped. + """ + assert graded["valid"], graded["reason"] + assert graded["episodes"] == graded["instances"] * sopcc.EPISODES_PER_INSTANCE + + +def test_metric_is_well_formed(graded): + """The metric and its parts must be finite and inside their definitions. + + WHY: the reward is a function of these numbers, so a NaN or an out-of-range failure rate + has to fail loudly here instead of propagating into reward.txt. + """ + assert 0.0 <= graded["F"] <= 1.0 + assert 0.0 <= graded["penalty"] <= 1.0 + assert graded["R"] >= 0.0 + assert graded["metric"] == pytest.approx(graded["R"] * graded["penalty"], abs=1e-9) + assert 0.0 <= graded["reward"] < 1.0 + + +def test_reward_follows_the_metric(graded): + """The reward written for this run must be exactly the map applied to the measured metric. + + WHY: the reward is the only number that leaves the verifier, and it is computed once in the + fixture. This re-derives it from the metric through the same map, so a mis-keyed split or a + hand-edited payload cannot slip a different number into reward.txt. It also pins the floor: + a metric at or below the trivial anchor is worth exactly 0. + """ + split = graded["split"] + assert graded["reward"] == pytest.approx( + grader_core.graded_reward(graded["metric"], split), abs=1e-12) + m0, m_ref = grader_core.ANCHORS[split] + assert m_ref > m0 + assert grader_core.graded_reward(m0, split) == 0.0 + assert grader_core.graded_reward(m0 - 1.0, split) == 0.0 + assert grader_core.graded_reward(m_ref, split) == pytest.approx(0.5, abs=1e-12) + + +def test_no_infrastructure_failure(graded): + """No instance may end early for a reason that is not the policy's own doing. + + WHY: an instance whose child process vanished contributes 32 failures and drags the metric + down. Retries absorb a transient death; anything still unexplained afterwards is surfaced + here, on a channel the candidate cannot reach or trigger, instead of being folded silently + into a low score. A policy that crashes or blows its own budget is NOT unexplained. + """ + assert graded.get("unexplained_aborts", 0) == 0, ( + f"{graded.get('unexplained_aborts')} instances died without spending their own " + f"budget: {[a for a in graded.get('aborts', []) if a['unexplained']][:3]}") diff --git a/tasks/sopcc-online-chance-constrained-policy/environment/docker-compose.yaml b/tasks/sopcc-online-chance-constrained-policy/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7222fefdc51adf48e9ad22054bced2b2c43e3cc6 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/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: "1800" + 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: "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/sopcc-online-chance-constrained-policy/task.toml b/tasks/sopcc-online-chance-constrained-policy/task.toml index 8a9e2db4dd4cb9c1c735024c9f4a220c50798612..6d2ffbf575ebc7d4ab05868230f11a4645733ef8 100644 --- a/tasks/sopcc-online-chance-constrained-policy/task.toml +++ b/tasks/sopcc-online-chance-constrained-policy/task.toml @@ -1,57 +1,71 @@ schema_version = "1.4" -artifacts = [ "/app/solution",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/sopcc-online-chance-constrained-policy" -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 = "Reinforcement 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/sopcc-online-chance-constrained-policy/tests/Dockerfile b/tasks/sopcc-online-chance-constrained-policy/tests/Dockerfile index eecf368ab2e270d72769fce908d380caafac46d0..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/sopcc-online-chance-constrained-policy/tests/Dockerfile +++ b/tasks/sopcc-online-chance-constrained-policy/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/sopcc-online-chance-constrained-policy/tests/finalize.py b/tasks/sopcc-online-chance-constrained-policy/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/sopcc-online-chance-constrained-policy/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/sopcc-online-chance-constrained-policy/tests/test.sh b/tasks/sopcc-online-chance-constrained-policy/tests/test.sh index 492622781afd2c06d496f7c30e2e3616b2145647..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/sopcc-online-chance-constrained-policy/tests/test.sh +++ b/tasks/sopcc-online-chance-constrained-policy/tests/test.sh @@ -1,30 +1,2 @@ #!/bin/bash - - - -set -u - - - -reward_floor() { - if [ ! -s /logs/verifier/reward.txt ]; then - mkdir -p /logs/verifier - printf '0\n' > /logs/verifier/reward.txt - fi -} -trap reward_floor EXIT - -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 - -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/sparse-elsa-item-embeddings-8nnz/environment/.dockerignore b/tasks/sparse-elsa-item-embeddings-8nnz/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/Dockerfile b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..92638e433647911796fb839f1fc0aeb4b8fada78 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,38 @@ +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 \ + NUMEXPR_NUM_THREADS=8 \ + TORCH_NUM_THREADS=8 \ + HF_HUB_OFFLINE=1 \ + TRANSFORMERS_OFFLINE=1 + +RUN useradd --create-home --uid 1001 agent + +RUN command -v runuser >/dev/null || command -v /usr/sbin/runuser >/dev/null \ + && command -v setsid >/dev/null && command -v timeout >/dev/null + +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 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/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/Dockerfile.are b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..46fd2dc06a6cc6fbf5e061bf5ad35e952a73c517 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,56 @@ +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 \ + NUMEXPR_NUM_THREADS=8 \ + TORCH_NUM_THREADS=8 \ + HF_HUB_OFFLINE=1 \ + TRANSFORMERS_OFFLINE=1 + +RUN useradd --create-home --uid 1001 agent + +RUN command -v runuser >/dev/null || command -v /usr/sbin/runuser >/dev/null \ + && command -v setsid >/dev/null && command -v timeout >/dev/null + +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 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/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/are/drain.py b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/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/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/are/server.py b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/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/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/compute_reward.py b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..4548359b5a83c27d01892d0a56c9d69b416434ab --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,23 @@ +import json +import math +import sys +from pathlib import Path + +METRIC_PATH = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/logs/verifier/metric.json") +REWARD_PATH = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("/logs/verifier/reward.txt") + +try: + record = json.loads(METRIC_PATH.read_text()) + if not record.get("valid", False): + raise ValueError(f"invalid submission: {record.get('detail', '')[:200]}") + value = float(record["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/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/data/train.npz b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/data/train.npz new file mode 100644 index 0000000000000000000000000000000000000000..9b8820e463ca0387d1f0ddfe7ba0788685a985dc --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/data/train.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52aaed79def8f56565733eafd9878730dbe084f43340b210a152107d95300661 +size 6996745 diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/grader_core.py b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f49e244bcf31fce8580e162c7ebd68adaac907 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,366 @@ +import json +import math +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +import scipy.sparse as sp + + + + + +N_ITEMS = 10000 +MAX_NNZ_PER_ITEM = 8 +MAX_DIMS = 65536 +CANDIDATE_SEED = 815 +CANDIDATE_TIMEOUT_SEC = 2400.0 +K = 100 +CANDIDATE_THREADS = "8" + + + +M0 = 0.354019 +BASELINE_SCORE = 0.469 + + + + + +def load_train_matrix(path) -> sp.csr_matrix: + X = sp.load_npz(str(path)).tocsr() + X.sort_indices() + return X.astype(np.float32) + + +def load_eval_slice(path): + """Return (src, target) csr matrices of the sealed evaluation rows.""" + with np.load(str(path), allow_pickle=False) as z: + shape = tuple(int(v) for v in z["shape"]) + src = sp.csr_matrix( + (z["src_data"].astype(np.float32), z["src_indices"], z["src_indptr"]), shape=shape + ) + tgt_indptr = z["tgt_indptr"] + tgt_indices = z["tgt_indices"] + tgt = sp.csr_matrix( + (np.ones(len(tgt_indices), dtype=np.float32), tgt_indices, tgt_indptr), shape=shape + ) + src.sort_indices() + tgt.sort_indices() + return src, tgt + + + + + +def candidate_command(python_exe, runner, code_copy, train_copy, emb_path, run_as, timeout): + """The exact command line the graded run is launched with. + + Three properties are load-bearing and are asserted by tests/test_state.py: `runuser` drops + to the unprivileged uid, `setsid` detaches the run into its own session, and `timeout + --signal=KILL` bounds the whole process group in wall-clock seconds. + """ + argv = [ + str(python_exe), + "-I", + str(runner), + str(code_copy), + str(train_copy), + str(emb_path), + str(N_ITEMS), + str(MAX_NNZ_PER_ITEM), + str(MAX_DIMS), + str(CANDIDATE_SEED), + ] + wrapped = ["setsid", "timeout", "--signal=KILL", str(int(timeout))] + argv + if run_as: + runuser = shutil.which("runuser") or "/usr/sbin/runuser" + wrapped = [runuser, "-u", run_as, "--"] + wrapped + return wrapped + + +def run_candidate( + code_dir, + harness_dir, + work_dir, + train_path, + python_exe=None, + run_as="agent", + timeout_sec=CANDIDATE_TIMEOUT_SEC, +): + """Copy the deliverable somewhere the candidate cannot rewrite, run it, return status. + + Returns (ok, detail, embedding_path, elapsed_sec). + """ + python_exe = python_exe or sys.executable + harness_dir = Path(harness_dir) + work_dir = Path(work_dir) + code_dir = Path(code_dir) + + for d in (harness_dir, work_dir): + if d.exists(): + shutil.rmtree(d) + d.mkdir(parents=True) + + runner_src = Path(__file__).resolve().parent / "run_candidate.py" + runner = harness_dir / "run_candidate.py" + shutil.copy2(runner_src, runner) + + code_copy = harness_dir / "candidate_code" + if not code_dir.is_dir(): + return False, f"deliverable directory {code_dir} is missing", None, 0.0 + + + + shutil.copytree(code_dir, code_copy, symlinks=True, ignore_dangling_symlinks=True) + + train_copy = harness_dir / "train.npz" + shutil.copy2(train_path, train_copy) + + emb_path = work_dir / "embedding.npz" + + + for path in harness_dir.rglob("*"): + os.chmod(path, 0o555 if path.is_dir() else 0o444) + os.chmod(harness_dir, 0o555) + if run_as: + shutil.chown(work_dir, user=run_as) + os.chmod(work_dir, 0o700) + + wrapped = candidate_command( + python_exe, runner, code_copy, train_copy, emb_path, run_as=run_as, timeout=timeout_sec + ) + + env = { + "PATH": "/usr/local/bin:/usr/bin:/bin", + "HOME": str(work_dir), + "TMPDIR": str(work_dir), + "PYTHONHASHSEED": "0", + "OMP_NUM_THREADS": CANDIDATE_THREADS, + "MKL_NUM_THREADS": CANDIDATE_THREADS, + "OPENBLAS_NUM_THREADS": CANDIDATE_THREADS, + "NUMEXPR_NUM_THREADS": CANDIDATE_THREADS, + "TORCH_NUM_THREADS": CANDIDATE_THREADS, + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + } + + start = time.monotonic() + try: + proc = subprocess.run( + wrapped, + cwd=str(work_dir), + env=env, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=timeout_sec + 120.0, + ) + except subprocess.TimeoutExpired: + return False, "candidate exceeded its wall-clock budget", None, time.monotonic() - start + elapsed = time.monotonic() - start + + tail = (proc.stdout or "")[-2000:] + (proc.stderr or "")[-2000:] + if proc.returncode == -9 or proc.returncode == 137: + return False, f"candidate killed at the wall-clock budget: {tail}", None, elapsed + if proc.returncode != 0: + return False, f"candidate exited {proc.returncode}: {tail}", None, elapsed + if not emb_path.is_file(): + return False, f"candidate wrote no embedding: {tail}", None, elapsed + return True, tail, emb_path, elapsed + + + + + +class InvalidSubmission(Exception): + """The submitted embedding violates the declared contract.""" + + +def load_embedding(path) -> sp.csr_matrix: + """Build A from the candidate's serialized output, enforcing the declared contract. + + The serialization holds at most MAX_NNZ_PER_ITEM slots per row, so the sparsity budget + is structurally unforgeable: a candidate that lies about its own row counts can only + ever produce a matrix that already satisfies the cap. + """ + with np.load(str(path), allow_pickle=False) as z: + missing = {"idx", "val", "nnz_per_row", "n_rows", "n_dims"} - set(z.files) + if missing: + raise InvalidSubmission(f"serialized embedding is missing {sorted(missing)}") + idx = np.asarray(z["idx"]) + val = np.asarray(z["val"]) + nnz_per_row = np.asarray(z["nnz_per_row"]) + n_rows = int(np.asarray(z["n_rows"]).reshape(-1)[0]) + n_dims = int(np.asarray(z["n_dims"]).reshape(-1)[0]) + + if n_rows != N_ITEMS: + raise InvalidSubmission(f"A has {n_rows} rows, expected {N_ITEMS}") + if not (1 <= n_dims <= MAX_DIMS): + raise InvalidSubmission(f"A has {n_dims} columns, expected 1..{MAX_DIMS}") + if idx.shape != (N_ITEMS, MAX_NNZ_PER_ITEM) or val.shape != (N_ITEMS, MAX_NNZ_PER_ITEM): + raise InvalidSubmission(f"serialized shapes {idx.shape}/{val.shape} are malformed") + if nnz_per_row.shape != (N_ITEMS,): + raise InvalidSubmission("serialized nnz_per_row is malformed") + if int(nnz_per_row.max(initial=0)) > MAX_NNZ_PER_ITEM: + worst = int(nnz_per_row.max(initial=0)) + raise InvalidSubmission( + f"row {int(np.argmax(nnz_per_row))} of A has {worst} nonzeros, " + f"the budget is {MAX_NNZ_PER_ITEM}" + ) + if not np.issubdtype(val.dtype, np.floating) and not np.issubdtype(val.dtype, np.integer): + raise InvalidSubmission(f"A has non-real dtype {val.dtype}") + val = val.astype(np.float64) + idx = idx.astype(np.int64) + if not np.isfinite(val).all(): + raise InvalidSubmission("A contains a non-finite value") + live = (idx >= 0) & (val != 0.0) + if np.any(idx[live] >= n_dims): + raise InvalidSubmission("A references a column outside its declared width") + + rows = np.repeat(np.arange(N_ITEMS, dtype=np.int64), MAX_NNZ_PER_ITEM)[live.ravel()] + cols = idx.ravel()[live.ravel()] + data = val.ravel()[live.ravel()] + A = sp.csr_matrix((data, (rows, cols)), shape=(N_ITEMS, n_dims), dtype=np.float64) + A.sum_duplicates() + A.eliminate_zeros() + over = np.flatnonzero(np.diff(A.indptr) > MAX_NNZ_PER_ITEM) + if over.size: + raise InvalidSubmission(f"row {int(over[0])} of A exceeds the nonzero budget") + return A + + +def row_normalize(A: sp.csr_matrix) -> sp.csr_matrix: + """L2-normalize every row of A; all-zero rows stay all-zero.""" + A = A.tocsr(copy=True).astype(np.float64) + norms = np.sqrt(np.asarray(A.multiply(A).sum(axis=1)).ravel()) + scale = np.divide(1.0, norms, out=np.zeros_like(norms), where=norms > 0) + return sp.diags(scale).dot(A).tocsr() + + +def gram(A_norm: sp.csr_matrix, block: int = 2000) -> np.ndarray: + """Dense A A^T. Blocked, because A A^T can be dense even when A is very sparse.""" + G = np.empty((A_norm.shape[0], A_norm.shape[0]), dtype=np.float64) + AT = A_norm.T.tocsc() + for i in range(0, A_norm.shape[0], block): + j = min(i + block, A_norm.shape[0]) + G[i:j] = (A_norm[i:j] @ AT).toarray() + return G + + +def mean_ndcg_at_k(A_norm, src, tgt, k=K, block=1000): + """Mean nDCG@k over the evaluation rows, exactly as instruction.md defines it. + + r = x_src A_norm A_norm^T - x_src, the row's own src items forced to -inf, ranked by + descending score with ties broken by ascending item index; DCG sums 1/log2(rank+1) + over target items landing in the top k; IDCG = sum_{i=1..min(k, #targets)} 1/log2(i+1). + """ + G = gram(A_norm) + n = src.shape[0] + disc = 1.0 / np.log2(np.arange(1, k + 1) + 1.0) + idcg_table = np.concatenate([[0.0], np.cumsum(disc)]) + scores = np.empty(n, dtype=np.float64) + + for i in range(0, n, block): + j = min(i + block, n) + xs = src[i:j] + R = xs @ G + R -= xs.toarray() + rows, cols = xs.nonzero() + R[rows, cols] = -np.inf + top = np.argsort(-R, axis=1, kind="stable")[:, :k] + for b in range(j - i): + targets = tgt.indices[tgt.indptr[i + b] : tgt.indptr[i + b + 1]] + n_tgt = len(targets) + if n_tgt == 0: + scores[i + b] = 0.0 + continue + hit = np.isin(top[b], targets, assume_unique=False) + dcg = float(disc[hit].sum()) + idcg = float(idcg_table[min(k, n_tgt)]) + scores[i + b] = dcg / idcg + return float(scores.mean()), scores + + + + + +def graded_reward(metric, valid=True, m0=M0, baseline_score=BASELINE_SCORE): + if not valid or metric is None or not math.isfinite(metric): + return 0.0 + x_ref = baseline_score - m0 + assert x_ref > 0, "malformed task: the baseline score does not beat the trivial baseline" + u = max(0.0, metric - m0) / x_ref + return u / (1.0 + u) + + + + + +def grade( + code_dir, + train_path, + eval_path, + harness_dir, + work_dir, + metric_path=None, + python_exe=None, + run_as="agent", + timeout_sec=CANDIDATE_TIMEOUT_SEC, +): + result = { + "valid": False, + "metric": None, + "reward": 0.0, + "stage": "start", + "detail": "", + "elapsed_sec": None, + "n_dims": None, + "max_nnz_per_item": None, + "n_eval_rows": None, + } + try: + ok, detail, emb_path, elapsed = run_candidate( + code_dir, + harness_dir, + work_dir, + train_path, + python_exe=python_exe, + run_as=run_as, + timeout_sec=timeout_sec, + ) + result["elapsed_sec"] = round(elapsed, 2) + result["detail"] = detail[-1500:] if detail else "" + if not ok: + result["stage"] = "execution" + return result + + result["stage"] = "validation" + A = load_embedding(emb_path) + result["n_dims"] = int(A.shape[1]) + result["max_nnz_per_item"] = int(np.diff(A.indptr).max(initial=0)) + + result["stage"] = "scoring" + src, tgt = load_eval_slice(eval_path) + result["n_eval_rows"] = int(src.shape[0]) + metric, per_row = mean_ndcg_at_k(row_normalize(A), src, tgt) + result["metric"] = metric + result["per_row_sem"] = float(per_row.std(ddof=1) / math.sqrt(len(per_row))) + result["valid"] = True + result["reward"] = graded_reward(metric, True) + result["stage"] = "done" + return result + except InvalidSubmission as exc: + result["detail"] = f"invalid submission: {exc}" + return result + except Exception as exc: + result["detail"] = f"{type(exc).__name__}: {exc}" + return result + finally: + if metric_path is not None: + Path(metric_path).parent.mkdir(parents=True, exist_ok=True) + Path(metric_path).write_text(json.dumps(result, indent=2, default=str) + "\n") diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/hidden_data/final/eval.npz b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/hidden_data/final/eval.npz new file mode 100644 index 0000000000000000000000000000000000000000..02265292e59b61a507ec30c835fb8b39b9fa4581 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/hidden_data/final/eval.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b2ba8e97176a1dca890613120100d65a0e99cc7530b8ab57b306b7f5fd648ed +size 938126 diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/hidden_data/intermediate/eval.npz b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/hidden_data/intermediate/eval.npz new file mode 100644 index 0000000000000000000000000000000000000000..51bf9b9a181ce354b181a73cdf3be4973394b5c2 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/hidden_data/intermediate/eval.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b6cb5ddb207b32f366e172e8cda03bb474be863b123428325d1f8c8c58168a9 +size 950869 diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/intermediate.sh b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c34e001e4dd18db02db8b38282bb1edcea7994f --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,26 @@ +#!/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_to_zero() { + [ -s /logs/verifier/reward.txt ] || printf '0\n' > /logs/verifier/reward.txt +} +trap default_reward_to_zero 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 -q -s --no-header +/usr/local/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/requirements-verifier.txt b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca9610a272c852274e7264cf3b8885cd200a9a61 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/requirements-verifier.txt @@ -0,0 +1,2 @@ +pytest==8.4.2 +pytest-json-ctrf==0.5.3 diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/requirements.txt b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ffa3ec8d9aecf991e0c3b728749b524ae9c1e468 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,6 @@ +--index-url https://download.pytorch.org/whl/cpu +--extra-index-url https://pypi.org/simple +numpy==2.5.1 +scipy==1.18.0 +scikit-learn==1.9.0 +torch==2.13.0+cpu diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/run_candidate.py b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/run_candidate.py new file mode 100644 index 0000000000000000000000000000000000000000..3204a3479427cbae65dfe3176d50ac8204509fab --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/run_candidate.py @@ -0,0 +1,94 @@ +import json +import os +import random +import sys +from pathlib import Path + +import numpy as np +import scipy.sparse as sp + + + + + +try: + import torch + + torch.set_num_threads(int(os.environ.get("TORCH_NUM_THREADS", "8"))) +except ImportError: + pass + + +def main() -> int: + code_dir, train_path, out_path, n_items, max_nnz, max_dims, seed = sys.argv[1:8] + n_items, max_nnz, max_dims, seed = int(n_items), int(max_nnz), int(max_dims), int(seed) + + random.seed(seed) + np.random.seed(seed) + try: + torch.manual_seed(seed) + except NameError: + pass + + sys.path.insert(0, str(Path(code_dir).resolve())) + try: + import solution + except Exception as exc: + print(f"import of solution.py failed: {type(exc).__name__}: {exc}", file=sys.stderr) + return 3 + fn = getattr(solution, "build_item_embeddings", None) + if not callable(fn): + print("solution.py exposes no callable build_item_embeddings", file=sys.stderr) + return 4 + + X_train = sp.load_npz(str(train_path)).tocsr().astype(np.float32) + X_train.sort_indices() + + A = fn(X_train, n_items, max_nnz, max_dims, seed) + + if sp.issparse(A): + A = sp.csr_matrix(A) + elif isinstance(A, np.ndarray) and A.ndim == 2: + A = sp.csr_matrix(A) + else: + print(f"entry point returned {type(A)!r}, not a 2-D sparse matrix", file=sys.stderr) + return 5 + + A = A.tocsr() + if A.shape[0] < 1 or A.shape[1] < 1: + print(f"entry point returned a degenerate shape {A.shape}", file=sys.stderr) + return 6 + A.sum_duplicates() + A.eliminate_zeros() + + n_rows, n_dims = int(A.shape[0]), int(A.shape[1]) + idx = np.full((n_items, max_nnz), -1, dtype=np.int64) + val = np.zeros((n_items, max_nnz), dtype=np.float64) + nnz_per_row = np.zeros(n_items, dtype=np.int64) + + counts = np.diff(A.indptr) + for r in range(min(n_rows, n_items)): + lo, hi = A.indptr[r], A.indptr[r + 1] + cols = A.indices[lo:hi] + vals = A.data[lo:hi].astype(np.float64) + nnz_per_row[r] = int(counts[r]) + if len(cols) > max_nnz: + keep = np.argsort(-np.abs(vals))[:max_nnz] + cols, vals = cols[keep], vals[keep] + idx[r, : len(cols)] = cols + val[r, : len(vals)] = vals + + np.savez( + str(out_path), + idx=idx.astype(np.int32), + val=val, + nnz_per_row=nnz_per_row, + n_rows=np.array([n_rows], dtype=np.int64), + n_dims=np.array([n_dims], dtype=np.int64), + ) + print(json.dumps({"n_rows": n_rows, "n_dims": n_dims, "max_nnz": int(counts.max(initial=0))})) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/test.sh b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8a94b206b998264f438f6875d44189fae27dc55d --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/test.sh @@ -0,0 +1,24 @@ +#!/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_to_zero() { + [ -s /logs/verifier/reward.txt ] || printf '0\n' > /logs/verifier/reward.txt +} +trap default_reward_to_zero 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/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/test_state.py b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..94ffa6d3c256c837dd629a5f4a6b1ccf4283e487 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/environment/are-grader-ctx/test_state.py @@ -0,0 +1,90 @@ +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import grader_core + +DELIVERABLE = Path("/app/output") +TRAIN_PATH = Path("/tests/data/train.npz") + + +SPLIT = os.environ.get("GRADE_SPLIT", "final") +EVAL_PATH = Path("/tests/hidden_data") / SPLIT / "eval.npz" +N_EVAL_ROWS = 6250 +HARNESS_DIR = Path("/tmp/graded_harness") +WORK_DIR = Path("/tmp/graded_work") +METRIC_PATH = Path("/logs/verifier/metric.json") +PYTHON = "/usr/local/bin/python3" + +_RESULT = None + + +def graded_run(): + global _RESULT + if _RESULT is None: + _RESULT = grader_core.grade( + code_dir=DELIVERABLE, + train_path=TRAIN_PATH, + eval_path=EVAL_PATH, + harness_dir=HARNESS_DIR, + work_dir=WORK_DIR, + metric_path=METRIC_PATH, + python_exe=PYTHON, + run_as="agent", + timeout_sec=grader_core.CANDIDATE_TIMEOUT_SEC, + ) + return _RESULT + + +def test_graded_run_is_unprivileged_and_bounded(): + """The submitted code must be executed with privilege dropped to the agent uid, detached + into its own session, and killed at the declared wall-clock budget -- so it can neither read + the sealed evaluation slice nor outlive its own deadline.""" + cmd = grader_core.candidate_command( + PYTHON, + HARNESS_DIR / "run_candidate.py", + HARNESS_DIR / "candidate_code", + HARNESS_DIR / "train.npz", + WORK_DIR / "embedding.npz", + run_as="agent", + timeout=grader_core.CANDIDATE_TIMEOUT_SEC, + ) + assert any(part.endswith("runuser") for part in cmd), cmd + assert cmd[cmd.index("-u") + 1] == "agent", cmd + assert "setsid" in cmd and "timeout" in cmd, cmd + assert "--signal=KILL" in cmd, cmd + assert str(int(grader_core.CANDIDATE_TIMEOUT_SEC)) in cmd, cmd + assert not EVAL_PATH.is_relative_to(HARNESS_DIR), EVAL_PATH + + +def test_entry_point_executes_within_budget(): + """/app/output/solution.py must import, expose build_item_embeddings, and return an + embedding within the declared wall-clock budget.""" + res = graded_run() + assert res["stage"] != "execution", res["detail"] + + +def test_embedding_satisfies_declared_budget(): + """The returned matrix must be 10000 x d with 1 <= d <= 65536, finite, real, and at most + 8 stored nonzeros in every row.""" + res = graded_run() + assert res["n_dims"] is not None, res["detail"] + assert 1 <= res["n_dims"] <= grader_core.MAX_DIMS, res["n_dims"] + assert res["max_nnz_per_item"] <= grader_core.MAX_NNZ_PER_ITEM, res["max_nnz_per_item"] + + +def test_metric_and_reward_recorded(): + """The mean nDCG@100 over the sealed evaluation rows is recomputed here and recorded with + the reward it maps to.""" + res = graded_run() + assert res["valid"], res["detail"] + assert res["n_eval_rows"] == N_EVAL_ROWS + assert res["metric"] is not None and 0.0 <= res["metric"] <= 1.0 + assert 0.0 <= res["reward"] <= 1.0 + print( + f"mean nDCG@100 = {res['metric']:.6f} (sem {res.get('per_row_sem')}) " + f"over {res['n_eval_rows']} rows; d={res['n_dims']}; " + f"max nnz/item={res['max_nnz_per_item']}; candidate ran {res['elapsed_sec']}s" + ) diff --git a/tasks/sparse-elsa-item-embeddings-8nnz/environment/docker-compose.yaml b/tasks/sparse-elsa-item-embeddings-8nnz/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b005049745ebb7d83d2702d5238f73fb1f6939f6 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/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: "3300" + 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: "3300" + 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/sparse-elsa-item-embeddings-8nnz/task.toml b/tasks/sparse-elsa-item-embeddings-8nnz/task.toml index 538a9a40f31eaa2050941599358e64845e9d2d55..5f96d1c375efec63809c16aeadfeb99665fea48f 100644 --- a/tasks/sparse-elsa-item-embeddings-8nnz/task.toml +++ b/tasks/sparse-elsa-item-embeddings-8nnz/task.toml @@ -1,57 +1,71 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/sparse-elsa-item-embeddings-8nnz" -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 = 3300.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 = 6600.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 = 18000.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/sparse-elsa-item-embeddings-8nnz/tests/Dockerfile b/tasks/sparse-elsa-item-embeddings-8nnz/tests/Dockerfile index 92638e433647911796fb839f1fc0aeb4b8fada78..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/sparse-elsa-item-embeddings-8nnz/tests/Dockerfile +++ b/tasks/sparse-elsa-item-embeddings-8nnz/tests/Dockerfile @@ -1,38 +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 \ - NUMEXPR_NUM_THREADS=8 \ - TORCH_NUM_THREADS=8 \ - HF_HUB_OFFLINE=1 \ - TRANSFORMERS_OFFLINE=1 - -RUN useradd --create-home --uid 1001 agent - -RUN command -v runuser >/dev/null || command -v /usr/sbin/runuser >/dev/null \ - && command -v setsid >/dev/null && command -v timeout >/dev/null - -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 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/sparse-elsa-item-embeddings-8nnz/tests/finalize.py b/tasks/sparse-elsa-item-embeddings-8nnz/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/sparse-elsa-item-embeddings-8nnz/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/sparse-elsa-item-embeddings-8nnz/tests/test.sh b/tasks/sparse-elsa-item-embeddings-8nnz/tests/test.sh index 8a94b206b998264f438f6875d44189fae27dc55d..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/sparse-elsa-item-embeddings-8nnz/tests/test.sh +++ b/tasks/sparse-elsa-item-embeddings-8nnz/tests/test.sh @@ -1,24 +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_to_zero() { - [ -s /logs/verifier/reward.txt ] || printf '0\n' > /logs/verifier/reward.txt -} -trap default_reward_to_zero 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 +python3 /tests/finalize.py diff --git a/tasks/svdquant-w4a4-psnr/environment/.dockerignore b/tasks/svdquant-w4a4-psnr/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/Dockerfile b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..09c7a3dfb6cc7c0e0a6e9c74f2fd6508b4816048 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,42 @@ +FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV PYTHONNOUSERSITE=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 \ + CUBLAS_WORKSPACE_CONFIG=:4096:8 + +RUN useradd --create-home --uid 1001 agent +COPY ./requirements.txt /tmp/requirements.txt +RUN /usr/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements.txt \ + && rm /tmp/requirements.txt +RUN /usr/bin/python3 -c "from huggingface_hub import snapshot_download; snapshot_download('PixArt-alpha/PixArt-Sigma-XL-2-1024-MS', revision='e102b3591cc82e97071b8b4cb90d834d0c487207', local_dir='/opt/pixart-sigma', ignore_patterns=['asset/*', 'README.md', '.gitattributes'])" \ + && rm -rf /root/.cache/huggingface + +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 mkdir -p /app/output /logs/verifier /tests/hidden_data/intermediate /tests/hidden_data/final +COPY ./test.sh /tests/test.sh +COPY ./intermediate.sh /tests/intermediate.sh +COPY ./test_state.py /tests/test_state.py +COPY ./compute_reward.py /tests/compute_reward.py +COPY ./grader_core.py /tests/grader_core.py +COPY ./candidate_runner.py /tests/candidate_runner.py +COPY ./hidden_data/intermediate/prompts.jsonl /tests/hidden_data/intermediate/prompts.jsonl +COPY ./hidden_data/final/prompts.jsonl /tests/hidden_data/final/prompts.jsonl +COPY ./app_data/calibration_prompts.jsonl /app/data/calibration_prompts.jsonl +RUN chown -R root:root /tests /logs/verifier /opt/pixart-sigma \ + && chmod 700 /tests /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests /app/data -exec touch -d @1700000000 {} + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 +WORKDIR /tests diff --git a/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/Dockerfile.are b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..20bcc489197d7358a264162869f5a3d10b1986b4 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,60 @@ +FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV PYTHONNOUSERSITE=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 \ + CUBLAS_WORKSPACE_CONFIG=:4096:8 + +RUN useradd --create-home --uid 1001 agent +COPY ./requirements.txt /tmp/requirements.txt +RUN /usr/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements.txt \ + && rm /tmp/requirements.txt +RUN /usr/bin/python3 -c "from huggingface_hub import snapshot_download; snapshot_download('PixArt-alpha/PixArt-Sigma-XL-2-1024-MS', revision='e102b3591cc82e97071b8b4cb90d834d0c487207', local_dir='/opt/pixart-sigma', ignore_patterns=['asset/*', 'README.md', '.gitattributes'])" \ + && rm -rf /root/.cache/huggingface + +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 mkdir -p /app/output /logs/verifier /tests/hidden_data/intermediate /tests/hidden_data/final +COPY ./test.sh /tests/test.sh +COPY ./intermediate.sh /tests/intermediate.sh +COPY ./test_state.py /tests/test_state.py +COPY ./compute_reward.py /tests/compute_reward.py +COPY ./grader_core.py /tests/grader_core.py +COPY ./candidate_runner.py /tests/candidate_runner.py +COPY ./hidden_data/intermediate/prompts.jsonl /tests/hidden_data/intermediate/prompts.jsonl +COPY ./hidden_data/final/prompts.jsonl /tests/hidden_data/final/prompts.jsonl +COPY ./app_data/calibration_prompts.jsonl /app/data/calibration_prompts.jsonl +RUN chown -R root:root /tests /logs/verifier /opt/pixart-sigma \ + && chmod 700 /tests /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ + && chmod +x /tests/test.sh /tests/intermediate.sh \ + && find /tests /app/data -exec touch -d @1700000000 {} + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 +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/svdquant-w4a4-psnr/environment/are-grader-ctx/app_data/calibration_prompts.jsonl b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/app_data/calibration_prompts.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3900fcdf3fef2359718278a38853f021045cd3aa --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/app_data/calibration_prompts.jsonl @@ -0,0 +1,128 @@ +{"prompt": "New Campervan in a corn field. photo", "category": "vehicles"} +{"prompt": "STYLE Closeup Shot GENRE Gourmet EMOTION Tempting SCENE A table of American food TAGS Highend food photography, clean composition, dramatic lighting, luxurious, elegant, mouthwatering, indulgent, gourmet CAMERA Nikon Z7 FOCAL LENGTH 105mm SHOT TYPE Closeup COMPOSITION Centered LIGHTING Soft directional light PRODUCTION Food Stylist TIME Evening LOCATION TYPE Interior", "category": "food"} +{"prompt": "tattoo design, sleeve, project, original, 4 ideas, japanese style,8k,samurai", "category": "art"} +{"prompt": "an old and creepy beggar on the side of an antique cobbled road near a forest, with a lightning storm in the sky, middleage, dark atmosphere, photograph", "category": "people"} +{"prompt": "very beautiful oil painting of polson montana on flathead lake by artist Ted Winger, HDR, fine brush strokes", "category": "landscape"} +{"prompt": "halfbody, expressive eyes, ORANGE FROG IN SPACEX SPACESUIT IN scifi fantasy BACKGROUND landscape with a Mars scenario background, HE is based on the god Thor. He wears a cloak on top of the spacesuit. athletic build, toned muscles. You cant imagine how beautiful he is. Human proportions, semirealistic. 32k, rtx on", "category": "art"} +{"prompt": "a sea of cars and trucks on a highway with lots of traffic, highways and traffic everywhere, Birds Eye view, minimal design, symmetric composition, David Lynch, coloring in style of the movie The Joker, offcenter, 35 mm film still shot on Kodachrome, inside, night time, retro. instant capture, 8k, ultra detailed, ultra realistic, Contax T3 SLR, 16mm lens , accent lighting", "category": "vehicles"} +{"prompt": "Harry Potter is training in the gym on a power rack, Canon EOS R5, photorealistic, super detail skin, hyper detailed", "category": "indoor"} +{"prompt": "a realistic photo of Chris Patten eating a eggtart at a busy street of hong kong in the early evening, with disire, professional cinematic photography", "category": "food"} +{"prompt": "preraphaelite, In the painting, a woman is depicted as the personification of Scorpio, with piercing eyes and an intense expression on her face. The womans clothing and the background of the painting are dark and mysterious, evoking the signs association with depth and hidden truths. She may be holding a scorpion, the symbol of the Scorpio zodiac sign, or surrounded by other elements that represent the sign, such as a serpent or a phoenix. The womans gaze is direct and unwavering, conveying a sense of power and emotional depth that is often associated with Scorpio. Overall, the painting captures the enigmatic and transformative energy of Scorpio", "category": "art"} +{"prompt": "minecraft castle on hill", "category": "landscape"} +{"prompt": "ginger girl with long straight hair, a rose in one of her eyes, holding a celt carnyx, rosebushes around her, petals flying with the wind, protecting a giant three behind her, rose tattoos in her shoulders and legs, cute outfit", "category": "art"} +{"prompt": "an epic oldschool US Astronaut walks through the streets of Lagos, Nigeria, Emmanuel Lubezki Photography, modern neon lights and screens, difused lighting, Professional Commercial Photography Cinematic full body, DSLR, Canon EOS 5D and Fujifilm Superia X TRA 400 film, iso 100, 120mm anamorphic lens flare Photorealistic, ultrarealistic color grading, fine tune square shape edges, fix eyes lips face fingers body geometry incorrections, Make it a wide cinematic shot, ultra detailed, film lighting, moody, 35mm, candid, wide angle, in the style of davide sorrenti, DSLR, Synthology Nicheartunion, Cinematic, Color Grading, portrait Photography, Ultra Wide Angle, Depth of Field, hyper detailed, beautifully coded by color, insane detail, intricate detail, beautifully colored, Unreal Engine, Cinematic, Color Grading, Editorial Photography, Photography, Photoshoot, Depth of Field, DOF, Tilt Blur, White Balance, 32k, Super Resolution, Megapixel, ProPhoto RGB, VR, Halfrear Lighting, Backlight, Natural Lighting, Incandescent, Fiber Optic, Moody Lighting, Cinematic Lighting, Studio Lighting, Soft Lighting, Volumetric, Contre Jour, Beautiful Lighting, Accent Lighting, Global Illumination, Screen Space Global Illumination, Ray Tracing Global Illumination, Optical, Scattering, Glowing, Shadows, Rough, Shimmer, Ra y Tracing Reflections, Lumen Reflections, Screen Space Reflections, Diffraction Gradation, Chromatic aberration, GB displacement, scan lines, ray tracing, ray tracing ambient occlusion, anti aliasing, FK AA, TXAA, RTX, SSAO, Shaders", "category": "fashion"} +{"prompt": "a hot dog in the forest,", "category": "food"} +{"prompt": "Victoian Gothic, Butterfly Specimen, creepy, Parchment Paper, Display, cinematic", "category": "art"} +{"prompt": "Un parque bajo un puente vehicular en la ciudad, gente haciendo ejercicio bajo el puente, gente caminando, una parada de autobus, edificios en el horizonte, ciudad de Tuxtla Gutiérrez, una ciclovia con ciclistas, muchos arboles, la vista es bajo el puente, hyperrealism, 8k, full hd, HyperDetailed, Photorealistic, UHD, HDR, HD, Natural Lighting, Canon EOS R3, F1,4, ISO 200, 1160s, 32K, RAW, Pro Photo RGB, Bokeh, High Quality, 400MP, Megapixel, SuperResolution", "category": "vehicles"} +{"prompt": "a monkey wearing a helmet playing a guitart", "category": "animals"} +{"prompt": "a gunmetal colored 370z batmobile with an upgraded exoskeloton parked in a modern museum with neon lights", "category": "vehicles"} +{"prompt": "Modern minimalistic vibrant logo of zodiac libra,", "category": "logo"} +{"prompt": "Epic metamorphasis desert landscape with massive storm. Dont look at the esoteric red cirlce. v", "category": "landscape"} +{"prompt": "advertising photography of hamburger inspired by salvadore dali with 4 layers of well cooked beef meat. Ingredients include lettuce, tomato, oignon, pickles, peppers, white melting cheese, orange dripping sauce, mushrooms and bacon. There is a beautiful hard light coming from the back. The hamburger is sitting on a modern marble table, In the background we can see a blurry window and modern architecture at f1.2. bright light 5", "category": "food"} +{"prompt": "An intense and realistic battle scene, inspired by Game of Thrones Battle of the Bastards content fierce woman warrior, scantly clad , fantastical backdrop, fearlessly facing an undead army medium digital art style a combination of contemporary fantasy art and cinematic visuals lighting low and atmospheric, with flickering firelight reflecting off her battered armor colors a bold mix of deep blues, grays, and vivid warm tones from the surrounding flames composition a dynamic side view of the woman warrior in the foreground, poised for combat, with the relentless undead horde advancing in the background", "category": "art"} +{"prompt": "if tori kelly was black and jhene aiko was nerdy white girl, puppy", "category": "people"} +{"prompt": "combined samurai and viking style", "category": "people"} +{"prompt": "a woman performing a concert at dusk in new mexico surrounded by a huge crowd of fans, 8k, full HD", "category": "people"} +{"prompt": "coloring white sheet, beautiful mountain landscape, the monster truck with very high chassis, huge springs and shocks visible, converted from a 1983 Ford Ranger, highresolution white background, highresolution ink details, and outlines", "category": "vehicles"} +{"prompt": "a Cinematic, scene of two symbolemages fighting", "category": "indoor"} +{"prompt": "modern realisitic drawing art sketch of scabiosa flowers, clean straight lines, black and white, a lot of white space to color, coloring book style", "category": "plants"} +{"prompt": "nile river of chaos, anarchy, liberty, independence, force and energy, very detailed, photo taken with Hasselblad X1D, ISO 100, national geographic", "category": "vehicles"} +{"prompt": "Photo of an archeofusturist scene, rusty but futurist atmosphere, amidst the ruins, life still persists. A group of scavengers search through the debris, looking for something of value, wide angle, lots of details, UHD, 32k", "category": "indoor"} +{"prompt": "old 90s television with flicker on shelf horror dark style 169 super realistic", "category": "indoor"} +{"prompt": "hd photograph of various plants, flowers, shrubs, and gardening tools, overhead view, detailed, ar 169", "category": "plants"} +{"prompt": "Photograph of Superman, cinematic", "category": "fashion"} +{"prompt": "a camel, dressed as rock musician , with sunglasses ,by Bill Gekas", "category": "animals"} +{"prompt": "A group of friends laughing while sharing stories over dinner A cozy, dimly lit restaurant in Paris Warm candlelight 35mm, photorealistic, Canon EOS 5D Mark IV DSLR, f5.6 aperture, 1125 second shutter speed, ISO 100", "category": "people"} +{"prompt": "comeback of warrior, video game cover, 4k, ultra high quality, ultra detailed", "category": "art"} +{"prompt": "caminhos, man arquitetura, love, inside train, vacations, The resolution should be 8k", "category": "indoor"} +{"prompt": "Abel Makkonen Tesfaye in full growth in sunglasses Cyberpunk style in tokyo with massive fireworks in the background", "category": "fashion"} +{"prompt": "red sand mars and sky", "category": "landscape"} +{"prompt": "Girl, avatar, anime, face in shadow, sword, in a pose slightly leaning forward with a sword, yellow glowing eyes with a heart pattern", "category": "art"} +{"prompt": "An early summer forest with tiny wild strawberries, fern fronds, white blossoms in the photographic style of Paul Barson,", "category": "plants"} +{"prompt": "A plate with sushi on it is running fast on the rail", "category": "food"} +{"prompt": "a street scene on a dark hot summer night of the 1950s a very beautiful tall blonde in a silk dress with her hair blowing in the wind is looking and leaning into the camera her lips slightly separated with behind her little italy restaurants in the 1950s the houses connected with strings of italian light bulbs hanging across the street5", "category": "fashion"} +{"prompt": "A forest where a group of animals live, deer, elephant, giraffe, rabbit, fox, pig happy and free in harmony. Pieces, highly detailed cinematic, childrens book style ,, No Text super detailed vibrant", "category": "animals"} +{"prompt": "Digital Transformation Concept System Engineering Binary Code Programming. Highly detailed, ultra realistic, trending on artstation, rendered in octane, illuminated by brilliant led lights", "category": "logo"} +{"prompt": "A supersportscar prototype with retro elements on a coastal road, with the sea in the background, automotive photography, sunset, Canon 5D, DSLR, 50mm portrait, DOF, Vray render, 8K, ray tracing, golden hour lighting, uplight, hard rim lighting, photoshopped", "category": "vehicles"} +{"prompt": "Single character and background, setting is Fantasy, semirealistic proportions, a female Shadow Assassin with two daggers, lurking in the shadows of a dark alley, anime facial features, human proportions, semirealistic, by neoartcore, rtx on", "category": "fashion"} +{"prompt": "The Avenger She is a vengeful warrior, with a personal vendetta against the villain. She is often consumed by rage and hatred, but her desire for revenge is what fuels her strength.", "category": "fashion"} +{"prompt": "ancient iron coin, zoom in, fantasy, runes in a circle, ultrareal, 4k", "category": "logo"} +{"prompt": "coucher de soleil dans lespace sur saturne, cinematic lighting", "category": "landscape"} +{"prompt": "immense victorian era formal livingroom at night. dark. couches. dirty. roaring fire in the fireplace", "category": "indoor"} +{"prompt": "award winning architectural digest photograph of upscale living room in mcmansion, solid gold furniture with luxurious cushions, skylight, marble flooring, stone and hardwood walls, vaulted ceiling, ritzy, tasteful, gold, marble, wealthy, golden sunset light streaming in through cut crystal window", "category": "indoor"} +{"prompt": "La mano de Eva para llegar a la manzana prohibida. Una serpiente está colgando del árbol. ilustración digital, alta definición.", "category": "art"} +{"prompt": "Capital Letter L in Spencerian and blackletter form in 3D with spikes and roses, black background, details, striking details and dynamic range, colorful lighting", "category": "logo"} +{"prompt": "birds eye view of an island golf course, 8k quality", "category": "landscape"} +{"prompt": "a carrier pigeon wearing a flight suit with 100 stacks", "category": "fashion"} +{"prompt": "cinematic still of Agronomist observing a rose in a rose growing field, natural lights, sunlight, dramatic lighting, volumetric lighting, cinematic color tones, muted color tones, shot on Alexa 65, shot on 24mm lens, extreme wide angle, film grain, photorealistic, cinematography, depth of field, bokeh, ornate details, maximum resolution, Afga Vista 400, natural lighting", "category": "fashion"} +{"prompt": "An AIpowered flying car, soaring through the skies above a bustling Vancouver city, showcasing the freedom and innovation of transportation in the future", "category": "vehicles"} +{"prompt": "a ultramodern desert home built into the cliffs, built by Frank Lloyd Wright,futuristic,earth tones,military overtones,sandstone,polished aluminium,prairie style.elliptical minimalism,Cinematic, natural lighting, rich colors, magazine photography", "category": "indoor"} +{"prompt": "An award winning water color painting of a dynamic multi layered landscape including water and mountains with Japanese influences in the style of Roberto Nezzi", "category": "landscape"} +{"prompt": "professional photo of a campari spritz. italy theme.", "category": "fashion"} +{"prompt": "evil apocalypse ultrahighqualitycinematic hdr ray tracing", "category": "vehicles"} +{"prompt": "do a logo with letters F and C being part of a triangle, without background, metalic, 2D, company style, black and gold, volcano edit", "category": "logo"} +{"prompt": "a grass seed piercing through the soil, by mike lasove on 500px, in the style of andreas achenbach, oliver jeffers, ominous vibe, uhd image, pegi nicol macleod, stock photo, tumblewave", "category": "plants"} +{"prompt": "Spray bottle with a label sprays water on green coffee beans on a stool, black pepper, vanilla pods, bay leaf, parsley in the form of a mocap lie around 4320 x 4320 px size", "category": "plants"} +{"prompt": "Ash,Bodies Women,Hell,4k,Hight Resolution,Hight Texture,19201080 Pixels", "category": "art"} +{"prompt": "Film scene. An 8yearold boy and an 11yearold girl are making a very small wooden toy water wheel by a small stream. Bright forest. Rays of light break through the branches. Cinematic lighting. Wide angle shot", "category": "people"} +{"prompt": "Create an image of a young traveler man enjoying the beauty of Reykjadalur hot thermal spring in Iceland. The background should consist of a mild northern lights sky and a green mountain to create a sense of wonder and awe. The man should be the main focus of the image, taking up at least onethird of the area of the image, preferably twothirds. Use a sunny and clear weather setting to enhance the vibrancy of the hot spring. Use a closeup shot to make the man and the lagoon prominent, with the man in the center of the image and his head reaching the upper border. This image should be designed to serve as a YouTube thumbnail.", "category": "people"} +{"prompt": "3 oddly shaped UFOs hovering in the night sky, casting an eerie glow across the surrounding area. metallic exterior is unlike anything seen on Earth, with intricate patterns etched into the surface that seem to pulse with otherworldly energy. The multicolored lights, flicker and dance around the crafts a bright beam of blue light shoots down from the bottom of the ship, illuminating the ground below. As the light touches down on the ground, a cow grazing nearby becomes enveloped in the beam, lifted off the ground, and suspended in midair. casting a brilliant glow across the surrounding fields and countryside. the cow is carried up with it,", "category": "vehicles"} +{"prompt": "purple yellow and pink columbines looking up towards the sky from the grass or a meadow, in the style of light skyblue and light pink, naturalist aesthetic, dragonfly, light skyblue and green, vibrant florals, light red and green, ricoh ff9d", "category": "plants"} +{"prompt": "shitzu dog with glasses and seduction face", "category": "animals"} +{"prompt": "epic, exclusive, dark coloured background, black rolls royce, luxury, class, realistic,", "category": "vehicles"} +{"prompt": "Production still from a 1980s action movie, night, a fancy inerior of a condominium with large windows and a city scape in the background, dark, night, cinematic,", "category": "indoor"} +{"prompt": "affluent handsome young Latino man with a mustache and jheri curl mullet in the 1980s, high fashion, High fashion editorial shoot, expensive commercial photo, cinematic lighting, professionally retouched, dramatic lighting, emotional, highly detailed, intricate, elite, luxury, cinematic hypermaximalist, elegant, ornate, hyper textured, colored, insane details, depth of field background, artful bokeh depth of field, artstation, photorealistic ultra detailed cinematic scene smooth sharp features sharp focus, insanely detailed and intricate, hypermaximalist, elegant, ornate, hyper realistic, super detailed, clear glass reflection, subsurface scattering, photo realism, Photography, hypermaximalist, artful bokeh depth of field, Natural Lighting, intricate details, epic movie scene, professional photography, visualization most artistic way, breathtaking composition, photography, highly detailed, intricate details, Ultra Quality Awardwinning Photography, Ray Tracing Reflections", "category": "fashion"} +{"prompt": "a mindful magnolia on a balcony overlooking the country side peaceful serene ponderous", "category": "plants"} +{"prompt": "if the Last Of Us was a romcom", "category": "people"} +{"prompt": "3D illustration of a cellphone displaying a movie script written on the screen. apple product, product design, 3D,", "category": "logo"} +{"prompt": "An old man with a white beard wearing pirate attire sitting on a river bank by sunset talking to Heath Ledger wearing medieval attire", "category": "people"} +{"prompt": "watercolor wildflower border on white background", "category": "plants"} +{"prompt": "the tiles of the pool, in the style of alasdair mclellan, psychedelic color schemes, leon spilliaert, opaque resin panels, crossprocessed film, earthy color palette, stanisław ignacy witkiewicz", "category": "indoor"} +{"prompt": "hyper realistic viburnum, fill page, coloring book style, high detail, vector lines, 8k, modern cartoon, no shading, easy to color, printable coloring book page, black and white", "category": "plants"} +{"prompt": "white background, with a modern, minimalist sign, elegant neon gold color with the letters R", "category": "logo"} +{"prompt": "nightmare darkart dramatic sky, cinematic", "category": "landscape"} +{"prompt": "electric motorcycle 8k, Canon EOS R5, F1. 2, ISO100, 35MM, Realistic,", "category": "vehicles"} +{"prompt": "lemon and nearby crystal mephedrone, hashish, marijuana", "category": "food"} +{"prompt": "dungeons dragons anime a stone bridge takes to a squared fortress on a mountain mesa,", "category": "landscape"} +{"prompt": "Beautiful website pure water vector graphics conservation, special effect, ui, ux, ui ux, website 8k", "category": "logo"} +{"prompt": "Milwaukee, in the style of luis Royo, red glow, dim cinematic lighting, 8k udd, hyper realistic, extremely detailed, photograph", "category": "art"} +{"prompt": "DONALD TRUMP SAVING A CHILD FROM BURNING BUILDING", "category": "people"} +{"prompt": "An early summer forest with wild strawberries, fern fronds, white blossoms in the photographic style of Paul Barson", "category": "plants"} +{"prompt": "wet cobbled street photo tram tracks victorian", "category": "vehicles"} +{"prompt": "a slice of cheesecake with strawberries, expresso on the side,8k,high detail,", "category": "food"} +{"prompt": "photorealistic, 3d, transparent background, Blue Diamond , engraved with Level 1", "category": "logo"} +{"prompt": "A stylish Swahili muslim grandfather dressed in a Gucci suit is reading a newspaper through the streets of Lamu, magazine photography, editoria, cinematic lights, 8K kodak gold 200 details,", "category": "people"} +{"prompt": "photo in the style of Mario Sorrenti, Lachlan Bailey, photography, background in focus, ultra realistic face, full length photo of a person, girl, 35mm, kodak portra, kodak portra 800, 35 mm f1. 8, 8k,", "category": "people"} +{"prompt": "golden hour nature, morning nature photography", "category": "plants"} +{"prompt": "black Caribbean man walking balance front his fate chaos anarchy liberty independence force energy torahans the Galaxy hypermaximalist sculpted anatomically correct cinematic global illumination darkness shafts of iridescent smoke they glow coming from their intricate filigree", "category": "fashion"} +{"prompt": "Apollo american astronaut sitting on a salt flat at dusk, blue hour, dust blowing around, desolate, mountains in the far off background, Ford Raptor in background, hyper realistic, hyper detailed, 8k, photography", "category": "vehicles"} +{"prompt": "3 fashionalble girls in their 20s, with colorful magenta and blonde hair, looking at the camera, smiling, having fun, excited, wearing short skirts, during sunset, festival background, HD ultra quality, megapixel, realistic, 8k 16k, Canon EOS 5D Mar IV camera with a canon EF 2470mm f2.8 L II USM lens, aspect 11", "category": "fashion"} +{"prompt": "stunning, vibrant, multicolored, Energetic Positivity Unleashed playlist cover, highresolution, digital illustration", "category": "art"} +{"prompt": "Old brasilain couple at the jesus statue in Rio, year 2023, photography, superphotoreal, hyperreal, photorealistic, high def, ultradetailed, ultra realistic, medium format, wes anderson movie, pastel colors,delicate light, cinematic light 8k", "category": "people"} +{"prompt": "Magic The Gathering inspired Crest", "category": "logo"} +{"prompt": "full body, an black man with the wisdom of Solomon and the courage of Samson save the world with the help of cybernetic artificial intelligence , chaos, anarchy, liberty, independence, force and energy, very detailed, photo taken with Hasselblad X1D, ISO 100, national geographic", "category": "fashion"} +{"prompt": "an anthropomorphic white rabbit dressed as a wizard", "category": "animals"} +{"prompt": "An exquisite image capturing the essence of a luxurious seafood feast, set against the majestic beauty of the Antarctic. The seafood platter brimming with fresh lobster, scallops, mussels, and clams is displayed on the deck of a small yacht, with colossal icebergs bathed in the golden light of the sunset creating a mesmerizing background. Nikon D850, 50mm lens, ISO 200, f4, 1160s", "category": "food"} +{"prompt": "a black couple Caribbean man and woman with children walking balance front his fate, chaos, anarchy, liberty, independence, force, energy, torah, waving caustics deep below mens skulls head 4k cinematic lighting, atmosphere, light fog, foggy industrial environment, dim volumetric lighting, extreme detail, trending on artstation, 3 5 mm, f 3 2, golden angle,oil painting, whole body, very detailed, photo taken with Hasselblad X1D50c, ISO 100, national geographic", "category": "people"} +{"prompt": "five steampunk winemakers wine tasting 8k", "category": "people"} +{"prompt": "a redhaired kitten with a fulllength tail stands on a white background", "category": "animals"} +{"prompt": "film scene, teenager hacker doing works on computer n an abandoned factory, dimly lighting style, korean film style,", "category": "indoor"} +{"prompt": "food stylist photography of stylish chocolate pudding with sausages in a high class restaurant. haute cuisine. Mamiya 645, fstop 2.8, Kodak Portra.", "category": "food"} +{"prompt": "professional photo of a lemonade cocktail on the counter of a stylish new york bar", "category": "food"} +{"prompt": "obiwan Kenobi in a 80s Bollywood movie dark , brown skin.", "category": "people"} +{"prompt": "This is an ultra realistic photo a glass bowl full of tasty ripe strawberries with the top layer in the bowl covered with cream on top. There is a glass of strawberry milkshake next to the bowl with strawberries. The scene is set in a rustic outdoor setting in the countryside, surrounded by lush greenery and a small lake with light blue water sparkling in the sun in the background. In the foreground, there is a wooden table with a glass bowl full of fresh and ripe strawberries that have been covered in a generous layer of creamy white cream. The strawberries look plump and juicy, with their vibrant red color standing out against the pale cream. The bowl is placed at an angle, with some of the strawberries spilling over the edge onto the wooden table, adding a touch of playfulness and spontaneity to the scene. The lighting is sharp, with the sun shining through the trees and casting shadows on the scene. The colors are rich and vibrant, with the light green of the trees, blue water on the lake and the vivid red of the strawberries creating a beautiful contrast. In the background, the small lake adds an extra touch of tranquility to the scene, with its calm waters reflecting the greenery and blue sky above. The photo has a bright and airy feel, with a focus on the bright vivid colors and textures of the food. The scene should evoke a desire for fresh, organic food. This photo is captured by Marte Marie Forsberg with a Canon EOS R5 camera, paired with a macro lens such as the Canon EF 100mm f2.8L Macro IS USM, a wide aperture such as f2.8 to achieve a shallow depth of field and blur the background slightly, creating a sense of depth and focus on the strawberries. A shutter speed of 1125s will help to freeze any movement and ensure a sharp image. Finally, using a ...", "category": "food"} +{"prompt": "Thai pretty girl, 25 years old, wearing v neck gown, long hair, enjoying herself in a night club environment, dancing to the music and smiling towards the camera.", "category": "people"} +{"prompt": "full shot, a mysterious ocean, edge of beach, epic waves, greek mythological, cinematic, rich colors, daytime, surreal, artistic photography", "category": "landscape"} +{"prompt": "barbados as a transformer in an action pose", "category": "vehicles"} +{"prompt": "extremely simple flowers, smiling, childrens book illustration style, multiple poses and expressions, single black and white drawing, line art, white space, coloring page, wide angle, white background", "category": "plants"} +{"prompt": "halloween candy packages from another world, knolling, white background", "category": "food"} +{"prompt": "closeup food photography of a shoyu ramen, creamy chicken broth, soy sauce, black garlic mayu oil, thin organic wheat noodle, Thinly sliced spring onions ,Thinly sliced chicken meat, Narutomaki , Nori seaweed, sliced into strips,half Softboiled egg, ,Roasted sesame seeds. , ultra realistic, low angle, on table, canon 5d, dslr, 50mm portrait, DOF, vray render, 8k, ray tracing, golden hour lighting, up lighting, rim lighting rigid, photoshopped", "category": "food"} +{"prompt": "facebook logo, dry, broken", "category": "logo"} +{"prompt": "Create a mouthwatering Chocolate Protein Pudding with Whipped Cream and Berries that will make your taste buds tingle ultrarealistic", "category": "food"} +{"prompt": "small bucolic backyard with Japanese tree and koi pond", "category": "indoor"} +{"prompt": "Detox Diets,Shot using a Hasselblad camera, ISO 100. Professional color grading. Soft shadows. Clean sharp focus. High end retouching. Food magazine photography. Award winning photography. Advertising photography. Commercial photography.", "category": "food"} +{"prompt": "cactus ,sun shining through the old window an artist studio, nice weather, realistic, super detailed, photography, detailed, atmosphere, realistic, cinematic, photorealistic", "category": "indoor"} +{"prompt": "troupial 4K hyper realistic1 brave1", "category": "animals"} +{"prompt": "shubniggurath in a dark age grove, ultra fine details, ultrarealistic 4k, ultra photo realisitc 4k", "category": "art"} +{"prompt": "realistic wolf looking towards me on mountaintop with a sunset in background", "category": "animals"} +{"prompt": "realistic photography,Inside a selfdriving car,Sony Alpha 1,FE C 1635mmT3.1 G,", "category": "vehicles"} diff --git a/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/are/drain.py b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/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/svdquant-w4a4-psnr/environment/are-grader-ctx/are/server.py b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/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/svdquant-w4a4-psnr/environment/are-grader-ctx/candidate_runner.py b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/candidate_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..218e60e064f41281158ab71d5b7ef2dedb7a7751 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/candidate_runner.py @@ -0,0 +1,135 @@ +import argparse +import importlib.util +import inspect +import json +import math +import random +import sys +from pathlib import Path + +import numpy as np +import torch +from diffusers import PixArtSigmaPipeline + + +def load_submission(path): + spec = importlib.util.spec_from_file_location("candidate_quantize", path) + if spec is None or spec.loader is None: + raise RuntimeError("cannot load entry point") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + fn = getattr(module, "quantize_model", None) + if not callable(fn): + raise TypeError("quantize_model is not callable") + return fn + + +def check_tensor(value, name, shape, dtype, positive=False, code=False): + if not isinstance(value, torch.Tensor) or value.shape != shape or value.dtype != dtype: + raise ValueError(f"invalid {name}") + if code: + if value.numel() and (int(value.min()) < -7 or int(value.max()) > 7): + raise ValueError("qweight outside INT4 range") + else: + if not bool(torch.isfinite(value).all()): + raise ValueError(f"non-finite {name}") + if positive and not bool((value > 0).all()): + raise ValueError(f"non-positive {name}") + + +def validate_replacement(module, in_features, out_features, has_bias, rank): + expected = ["qweight", "scales", "l1", "l2", "smooth"] + tensors = {name: value for name, value in module.named_parameters(recurse=True)} + tensors.update({name: value for name, value in module.named_buffers(recurse=True)}) + if has_bias: + expected.append("bias") + if list(tensors) != expected or hasattr(module, "weight"): + raise ValueError("replacement tensor state does not match the required schema") + groups = math.ceil(in_features / 64) + check_tensor(tensors["qweight"], "qweight", (out_features, in_features), torch.int8, code=True) + check_tensor(tensors["scales"], "scales", (out_features, groups), torch.float16, positive=True) + check_tensor(tensors["smooth"], "smooth", (in_features,), torch.float16, positive=True) + r = tensors["l1"].shape[1] if tensors["l1"].ndim == 2 else -1 + if not 0 <= r <= rank: + raise ValueError("rank exceeds budget") + check_tensor(tensors["l1"], "l1", (in_features, r), torch.float16) + check_tensor(tensors["l2"], "l2", (r, out_features), torch.float16) + if has_bias: + check_tensor(tensors["bias"], "bias", (out_features,), torch.float16) + elif "bias" in tensors: + raise ValueError("unexpected bias") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--entry", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--rank", type=int, default=32) + args = parser.parse_args() + if args.rank < 0 or args.rank > 32 or not torch.cuda.is_available(): + raise RuntimeError("invalid rank or CUDA unavailable") + + random.seed(0) + np.random.seed(0) + torch.manual_seed(0) + torch.cuda.manual_seed_all(0) + torch.set_num_threads(1) + torch.use_deterministic_algorithms(True) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + torch.backends.cuda.matmul.allow_tf32 = False + quantize_model = load_submission(args.entry) + signature = inspect.signature(quantize_model) + parameters = list(signature.parameters.values()) + if ( + len(parameters) != 2 + or [parameter.name for parameter in parameters] != ["pipe", "rank"] + or parameters[0].default is not inspect.Parameter.empty + or parameters[1].default != 32 + ): + raise TypeError("quantize_model must have signature quantize_model(pipe, rank=32)") + pipe = PixArtSigmaPipeline.from_pretrained("/opt/pixart-sigma", torch_dtype=torch.float16, local_files_only=True) + pipe.to("cuda") + originals = { + name: (module, module.in_features, module.out_features, module.bias is not None) + for name, module in pipe.transformer.named_modules() + if isinstance(module, torch.nn.Linear) + } + result = quantize_model(pipe, rank=args.rank) + if result is not None: + raise ValueError("quantize_model must return None") + current = dict(pipe.transformer.named_modules()) + if not originals: + raise RuntimeError("no eligible linear layers found") + for name, (old, in_features, out_features, has_bias) in originals.items(): + module = current.get(name) + if module is None or module is old or isinstance(module, torch.nn.Linear): + raise ValueError(f"linear layer not replaced: {name}") + validate_replacement(module, in_features, out_features, has_bias, args.rank) + if any(isinstance(module, torch.nn.Linear) for module in pipe.transformer.modules()): + raise ValueError("linear layer remains") + + from safetensors.torch import save_file + + tensors = {} + manifest = {"rank": args.rank, "layers": []} + for name, (_, in_features, out_features, has_bias) in originals.items(): + module = current[name] + state = {key: value for key, value in module.named_parameters(recurse=True)} + state.update({key: value for key, value in module.named_buffers(recurse=True)}) + manifest["layers"].append({ + "name": name, "in_features": in_features, "out_features": out_features, + "has_bias": has_bias, + }) + for field in ("qweight", "scales", "l1", "l2", "smooth", "bias"): + if field in state: + tensors[f"{name}.{field}"] = state[field].detach().cpu().contiguous() + outdir = Path(args.output) + if not outdir.is_dir() or any(outdir.iterdir()): + raise ValueError("output directory is not fresh") + save_file(tensors, outdir / "quantized.safetensors") + (outdir / "manifest.json").write_text(json.dumps(manifest, sort_keys=True) + "\n") + + +if __name__ == "__main__": + main() diff --git a/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/compute_reward.py b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..376b100a87a746657f933de5738c08e4c4288385 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,16 @@ +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.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/svdquant-w4a4-psnr/environment/are-grader-ctx/grader_core.py b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..0071c3149da79f997a3f75c222576682666ffbb4 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,287 @@ +import json +import math +import os +import random +import shutil +import signal +import subprocess +import tempfile +import time +from pathlib import Path + +import numpy as np +import torch +from diffusers import PixArtSigmaPipeline + + +def configure_determinism(): + random.seed(0) + np.random.seed(0) + torch.manual_seed(0) + torch.cuda.manual_seed_all(0) + torch.set_num_threads(1) + torch.use_deterministic_algorithms(True) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + torch.backends.cuda.matmul.allow_tf32 = False + + +configure_determinism() + +M0 = 9.1 +BASELINE_SCORE = 17.6 +CANDIDATE_TIMEOUT = 900 +GENERATION_TIMEOUT = 5400 + + +def reward_for(metric): + improvement = max(0.0, float(metric) - M0) + reference = BASELINE_SCORE - M0 + u = improvement / reference + return u / (1.0 + u) + + +def sanitized_env(cuda_visible="0"): + keep = { + "HOME": "/home/agent", + "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "PYTHONPATH": "", + "PYTHONSAFEPATH": "1", + "PYTHONNOUSERSITE": "1", + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONHASHSEED": "0", + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "CUBLAS_WORKSPACE_CONFIG": ":4096:8", + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + "CUDA_VISIBLE_DEVICES": cuda_visible, + "NVIDIA_VISIBLE_DEVICES": os.environ.get("NVIDIA_VISIBLE_DEVICES", "all"), + "NVIDIA_DRIVER_CAPABILITIES": os.environ.get("NVIDIA_DRIVER_CAPABILITIES", "compute,utility"), + } + return keep + + +def run_process(command, timeout, env): + proc = subprocess.Popen( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env=env, cwd="/tmp", start_new_session=True, + ) + try: + stdout, stderr = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + stdout, stderr = proc.communicate() + raise TimeoutError(f"candidate timed out; stderr={stderr[-4000:]}") + if proc.returncode != 0: + raise RuntimeError(f"candidate exit={proc.returncode}; stderr={stderr[-4000:]}") + return stdout, stderr + + +def reap_agent_processes(): + """Kill every process owned by the submission user in this verifier.""" + for _ in range(3): + found = False + for item in Path("/proc").iterdir(): + if not item.name.isdigit(): + continue + try: + status = (item / "status").read_text() + uid_line = next(line for line in status.splitlines() + if line.startswith("Uid:")) + uids = [int(value) for value in uid_line.split()[1:]] + if 1001 not in uids[:2]: + continue + os.kill(int(item.name), signal.SIGKILL) + found = True + except (FileNotFoundError, ProcessLookupError, PermissionError, + StopIteration, ValueError): + continue + if not found: + break + time.sleep(0.1) + + +def stage_candidate(entry): + parent = Path(tempfile.mkdtemp(prefix="quant-grade-", dir="/tmp")) + parent.chmod(0o755) + staged_entry = parent / "quantize.py" + staged_runner = parent / "runner.py" + shutil.copyfile(entry, staged_entry) + shutil.copyfile("/tests/candidate_runner.py", staged_runner) + for path in (staged_entry, staged_runner): + path.chmod(0o444) + output = parent / "candidate-images" + output.mkdir(mode=0o700) + os.chown(output, 1001, 1001) + return parent, staged_entry, staged_runner, output + + +def generate_images(prompts, output, quantized_dir=None): + script = r''' +import json, math, random, sys, types +from pathlib import Path +import numpy as np +import torch +from diffusers import PixArtSigmaPipeline +from safetensors.torch import load_file + +random.seed(0) +np.random.seed(0) +torch.manual_seed(0) +torch.cuda.manual_seed_all(0) +torch.set_num_threads(1) +torch.use_deterministic_algorithms(True) +torch.backends.cudnn.deterministic=True +torch.backends.cudnn.benchmark=False +torch.backends.cuda.matmul.allow_tf32=False + +class QuantizedLinear(torch.nn.Module): + def __init__(self, state, prefix, info): + super().__init__(); self.in_features=info["in_features"]; self.out_features=info["out_features"] + for field in ("qweight","scales","l1","l2","smooth","bias"): + key=prefix+"."+field + if key in state: self.register_buffer(field,state[key].cuda()) + def forward(self,x): + shape=x.shape; xs=x/self.smooth + flat=xs.reshape(-1,self.in_features); parts=[] + for start in range(0,self.in_features,64): + chunk=flat[:,start:start+64]; scale=chunk.float().abs().amax(dim=1,keepdim=True)/7 + scale=torch.where(scale==0,torch.ones_like(scale),scale) + parts.append((torch.round(chunk.float()/scale).clamp(-7,7)*scale).to(x.dtype)) + qx=torch.cat(parts,dim=1) + wparts=[] + for group,start in enumerate(range(0,self.in_features,64)): + wparts.append(self.qweight[:,start:start+64].to(torch.float16)*self.scales[:,group:group+1]) + weight=torch.cat(wparts,dim=1) + y=qx@weight.T+(flat@self.l1)@self.l2 + if hasattr(self,"bias"): y=y+self.bias + return y.reshape(*shape[:-1],self.out_features) + +def replace(root,path,module): + parent=root + bits=path.split(".") + for bit in bits[:-1]: parent=getattr(parent,bit) + setattr(parent,bits[-1],module) + +p=PixArtSigmaPipeline.from_pretrained("/opt/pixart-sigma",torch_dtype=torch.float16,local_files_only=True) +if sys.argv[3] != "-": + qdir=Path(sys.argv[3]); state=load_file(qdir/"quantized.safetensors",device="cpu") + manifest=json.loads((qdir/"manifest.json").read_text()) + for info in manifest["layers"]: replace(p.transformer,info["name"],QuantizedLinear(state,info["name"],info)) +p.to("cuda"); p.set_progress_bar_config(disable=True) +rows=[json.loads(x) for x in Path(sys.argv[1]).read_text().splitlines() if x.strip()] +out=Path(sys.argv[2]); out.mkdir(parents=True,exist_ok=False) +for i,row in enumerate(rows): + g=torch.Generator(device="cuda").manual_seed(int(row["seed"])) + x=p(row["prompt"],num_inference_steps=20,guidance_scale=4.5,height=1024,width=1024,generator=g,output_type="pt").images[0] + if x.shape!=(3,1024,1024) or not torch.isfinite(x).all(): raise ValueError("bad image") + torch.save(x.detach().cpu().to(torch.float16).clamp(0,1).contiguous(),out/f"{i:04d}.pt") +''' + qarg = "-" if quantized_dir is None else str(quantized_dir) + run_process(["/usr/bin/python3", "-c", script, str(prompts), str(output), qarg], GENERATION_TIMEOUT, {**sanitized_env(), "HOME": "/root"}) + + +def verify_quantized_artifact(path): + from safetensors.torch import load_file + manifest = json.loads((path / "manifest.json").read_text()) + state = load_file(path / "quantized.safetensors", device="cpu") + if not isinstance(manifest.get("layers"), list) or not manifest["layers"] or manifest.get("rank") != 32: + raise ValueError("invalid manifest") + expected = set() + for info in manifest["layers"]: + name, m, n, has_bias = info["name"], int(info["in_features"]), int(info["out_features"]), bool(info["has_bias"]) + groups = math.ceil(m / 64) + fields = {"qweight", "scales", "l1", "l2", "smooth"} | ({"bias"} if has_bias else set()) + expected |= {f"{name}.{field}" for field in fields} + q, scales, l1, l2, smooth = (state[f"{name}.{field}"] for field in ("qweight", "scales", "l1", "l2", "smooth")) + if q.dtype != torch.int8 or q.shape != (n, m) or (q.numel() and (int(q.min()) < -7 or int(q.max()) > 7)): + raise ValueError("invalid qweight") + r = l1.shape[1] if l1.ndim == 2 else -1 + specs = [(scales, torch.float16, (n, groups), True), (l1, torch.float16, (m, r), False), (l2, torch.float16, (r, n), False), (smooth, torch.float16, (m,), True)] + if not 0 <= r <= 32: + raise ValueError("invalid rank") + if has_bias: specs.append((state[f"{name}.bias"], torch.float16, (n,), False)) + for tensor, dtype, shape, positive in specs: + if tensor.dtype != dtype or tensor.shape != shape or not torch.isfinite(tensor).all() or (positive and not (tensor > 0).all()): + raise ValueError("invalid quantized tensor") + if set(state) != expected: + raise ValueError("unexpected tensor state") + expected_count = 0 + pipe = PixArtSigmaPipeline.from_pretrained("/opt/pixart-sigma", torch_dtype=torch.float16, local_files_only=True) + original = {name: (module.in_features, module.out_features, module.bias is not None) for name, module in pipe.transformer.named_modules() if isinstance(module, torch.nn.Linear)} + listed = {x["name"]: (x["in_features"], x["out_features"], x["has_bias"]) for x in manifest["layers"]} + if listed != original: + raise ValueError("manifest does not replace every original linear") + del pipe + + +def safe_tensor(path): + tensor = torch.load(path, map_location="cpu", weights_only=True) + if not isinstance(tensor, torch.Tensor) or tensor.shape != (3, 1024, 1024): + raise ValueError("invalid image tensor") + tensor = tensor.to(torch.float32) + if not torch.isfinite(tensor).all() or float(tensor.min()) < 0 or float(tensor.max()) > 1: + raise ValueError("image outside [0,1]") + return tensor + + +def score(entry, prompts): + started = time.monotonic() + parent = reference_dir = generated_dir = validated_parent = None + try: + parent, staged_entry, runner, candidate_dir = stage_candidate(entry) + reference_dir = Path(tempfile.mkdtemp(prefix="reference-images-", dir="/tmp")) / "images" + command = [ + "/usr/sbin/runuser", "-u", "agent", "--", "/usr/bin/setsid", "/usr/bin/python3", + str(runner), "--entry", str(staged_entry), "--output", str(candidate_dir), + "--rank", "32", + ] + try: + _, stderr = run_process(command, CANDIDATE_TIMEOUT, sanitized_env()) + finally: + reap_agent_processes() + print(f"candidate stderr tail: {stderr[-2000:]}") + verify_quantized_artifact(candidate_dir) + + validated_parent = Path(tempfile.mkdtemp(prefix="validated-quant-", dir="/tmp")) + validated_parent.chmod(0o700) + validated_dir = validated_parent / "artifact" + validated_dir.mkdir(mode=0o700) + for name in ("manifest.json", "quantized.safetensors"): + target = validated_dir / name + shutil.copyfile(candidate_dir / name, target) + target.chmod(0o400) + verify_quantized_artifact(validated_dir) + generated_dir = Path(tempfile.mkdtemp(prefix="candidate-generated-", dir="/tmp")) / "images" + generate_images(prompts, reference_dir) + generate_images(prompts, generated_dir, validated_dir) + count = sum(1 for line in prompts.read_text().splitlines() if line.strip()) + values = [] + for index in range(count): + candidate = safe_tensor(generated_dir / f"{index:04d}.pt") + reference = safe_tensor(reference_dir / f"{index:04d}.pt") + mse = float(torch.mean((candidate - reference) ** 2, dtype=torch.float64)) + values.append(0.0 if not math.isfinite(mse) or mse <= 0 else 10.0 * math.log10(1.0 / mse)) + metric = sum(values) / len(values) + return { + "valid": True, "metric_name": "mean_psnr_db", "metric": metric, + "reward": reward_for(metric), "examples": len(values), + "elapsed_sec": time.monotonic() - started, + } + except Exception as exc: + return { + "valid": False, "metric_name": "mean_psnr_db", "metric": None, + "reward": 0.0, "reason": f"{type(exc).__name__}: {exc}", + "elapsed_sec": time.monotonic() - started, + } + finally: + if parent is not None: + shutil.rmtree(parent, ignore_errors=True) + if reference_dir is not None: + shutil.rmtree(reference_dir.parent, ignore_errors=True) + if generated_dir is not None: + shutil.rmtree(generated_dir.parent, ignore_errors=True) + if validated_parent is not None: + shutil.rmtree(validated_parent, ignore_errors=True) diff --git a/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/hidden_data/final/prompts.jsonl b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/hidden_data/final/prompts.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8c8efd3ffa164800bce15cc9488e5cd9c0333a6a --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/hidden_data/final/prompts.jsonl @@ -0,0 +1,32 @@ +{"prompt": "hyper realistic photo about two cute young kids that are lost in a forest. A boy and a girl.There must be a river. 4k resolution. In 3D and with depth perception", "category": "people", "seed": 150} +{"prompt": "Huge alligator alphamale standing in a distance by a riverside, hyperrealistic, photorealistic, high details, high quality, shot on Nikon D6, Galen Rowell, Peter Lik, Marc Adamus, David Muench,", "category": "animals", "seed": 151} +{"prompt": "HD big field of flowers Hyper realistic, HD,", "category": "landscape", "seed": 153} +{"prompt": "fashion editorial of a photorealistic female model with dark brown hair, full body, full body shot, wearing a futuristic cosmic nebula dress, metallic finishings, 4k, hyper realistic, cinematic, ultra detailed", "category": "fashion", "seed": 154} +{"prompt": "half tank half sandwich", "category": "food", "seed": 157} +{"prompt": "3d vector logo with a transparent background containing the letterV", "category": "logo", "seed": 158} +{"prompt": "A firstperson perspective of an F1 pilot engaged in a highspeed, adrenalinefueled race, featuring numerous F1 cars, intense action, and dangerous maneuvers, all rendered with Unreal Engine 5 for hyperrealistic details and cinematic lighting.", "category": "vehicles", "seed": 159} +{"prompt": "horror novel cover painting", "category": "art", "seed": 161} +{"prompt": "Spring has sprung, the flowers grow, The sun shines bright, the breeze is slow, The world awakens from its sleep, And natures beauty we get to keep.", "category": "plants", "seed": 166} +{"prompt": "Detailed photography of a large and modern room with tall windows on the 13th floor of a skyscraper in Miami, the windows show a view of the Florida coast, sunny day, cumulus clouds,", "category": "indoor", "seed": 170} +{"prompt": "A fit, brighteyed, welldressed Michael Gambon as Dumbledore in 1970s leisurewear, 8K, rich in details, hyperrealistic, chaos 50", "category": "people", "seed": 156} +{"prompt": "happy Daniel Tiger playing with a red bouncing ball", "category": "animals", "seed": 152} +{"prompt": "Realistic landscape photo of Vietnamese fishermen fishing on a bamboo boat, early in the morning there is a lot of dew and rays, dew floating on the lake, sunlight, wide lens, high quality", "category": "landscape", "seed": 160} +{"prompt": "blonde woman, sitting on beach", "category": "fashion", "seed": 155} +{"prompt": "pretzel extremely twisted", "category": "food", "seed": 168} +{"prompt": "a bic mac city gaudy style", "category": "logo", "seed": 179} +{"prompt": "The frame of the picture has an electric bicycle design, and the electric bicycle is small and placed directly below the picture, cyberpunk style, with subtle color changes, the center of the picture is blank, no text, no pattern. Innovative page design, Power point base map design", "category": "vehicles", "seed": 164} +{"prompt": "middle eastern woman wearing traditional clothes cooking Kabsa rice, using palm tree wood fire, full of palmtrees farm, at blue hour, with some water reflections in the floor, film grain, slight misty weather, Pixar movie style, Photorealistic, Ultra photoreal, Ultra detailed, Intricate details, Atmospheric, Hyperrealistic, Unreal engine, Ray tracing, Back light, Cinematic, Fairy lights, Soft lighting, Rim lighting, Low camera, FarShot Angle, LowAngle Shot, FullShot Angle, FullBody Shot, Cinematic Still Shot, Leica, Golden ratio, 8k", "category": "art", "seed": 165} +{"prompt": "sativa plants growing in a Mexico field, Hollywood scenery, movie set, ultra realistic, HD", "category": "plants", "seed": 172} +{"prompt": "a bedroom interior design in nomadic minimalistic style, flat gypsum ceiling with shadow gap profile, floor to ceiling windows with attached balcony, curtains, ottoman bench and minimalistic wardrobe, bed with area rug, realistic render, v5", "category": "indoor", "seed": 183} +{"prompt": "screen grab Robert Downey Jr young in the current year 2023 smiling and happy on a sunny day", "category": "people", "seed": 178} +{"prompt": "A photograph of a a large mushroom in a forest with a psychedelic and fairy tale atmosphere. The colors are like those of a drug induced vision.", "category": "animals", "seed": 167} +{"prompt": "scenic view of the surface of Tatooine from star wars at sunset, in the style of hollow knight", "category": "landscape", "seed": 162} +{"prompt": "Full length epic portrait, black cinderella entering a gala in Harlem, New York, photo realistic, 8k, high definition", "category": "fashion", "seed": 163} +{"prompt": "simple doughnut not glossy at all with not toppings, upright, black background, illustrationbased,", "category": "food", "seed": 171} +{"prompt": "heart shaped diamond on a matte black background", "category": "logo", "seed": 182} +{"prompt": "1956 Land Rover S\u00e9ries 1 climb a dune, Unreal Engine 5, Cinematic, portrait Photography, UltraWide Angle, Depth of Field, hyperdetailed, insane details, intricate details, beautifully color graded, Unreal Engine, Cinematic, Photoshoot, Shot on 25mm lens, Depth of Field, DOF, Tilt Blur, Shutter Speed 11000, F22, White Balance, 32k, SuperResolution, Megapixel, Pro Photo RGB, VR, Lonely, Good, Massive, Half rear Lighting, Backlight, Natural Lighting, Incandescent, Optical Fiber, Moody Lighting, Cinematic Lighting, Studio Lighting, Soft Lighting, Volumetric, Conte Jour, Beautiful Lighting, Accent Lighting, Global Illumination, Screen Space Global Illumination, Ray Tracing Global Illumination, Optics, Scattering, Glowing, Shadows, Rough, Shimmering, Ray Tracing Reflections, Lumen Reflections, Screen Space Reflections, Diffraction Grading, Chromatic Aberration, GB Displacement, Scan Lines, Ray Traced, ray Tracing Ambient Occlusion, AntiAliasing, FKAA, TXAA, RTX, SSAO, Shaders, OpenGLShaders, GLSLShaders, Post Processing, PostProduction, Cell Shading, Tone Mapping, CGI, VFX, SFX, insanely detailed and intricate, hyper maximalist, elegant, super detailed, dynamic pose, photography, volumetric, ultradetailed, intricate details, 8K, super detailed, ambient occlusion, volumetric lighting. high contrast, HDR v 4", "category": "vehicles", "seed": 191} +{"prompt": "female Tabaxi warlock looking like tabby cat, playing with a magical artifact", "category": "art", "seed": 176} +{"prompt": "abstract green deal backround made of", "category": "plants", "seed": 175} +{"prompt": "open circular coffee shop. starbucks style. bhopal. inside a park, beautifully landscaped. cultural convetion center background. evening. colorful sky. greenery.", "category": "indoor", "seed": 215} +{"prompt": "5 divers find treasure in a frigate at the bottom of the sea,", "category": "people", "seed": 184} +{"prompt": "overgrown animals", "category": "animals", "seed": 169} diff --git a/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/hidden_data/intermediate/prompts.jsonl b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/hidden_data/intermediate/prompts.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..368dd68eb0e52f2babfa3002938d70ef111eaaa3 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/hidden_data/intermediate/prompts.jsonl @@ -0,0 +1,32 @@ +{"prompt": "Will and Jada Pinkett Smiths Calabasas Compound in California, 8K, UHD,", "category": "landscape", "seed": 0} +{"prompt": "asian noodle, catalog photography, food photography, Canon EOS 5D Mark IV DSLR, f5.6, Resolution photography, maximum detail, hyperrealism", "category": "food", "seed": 1} +{"prompt": "Liveaction, Viriathus the young Leader of the Lusitanian people, 2nd century BC, wearing traditional Leader Lusitanian clothing, rugged landscape of the mountains and forests of modernday Portugal and Spain in background, shot by Rodrigo Prieto, DSMC2 DragonX and Cooke S4i lenses, highquality cinematic footage", "category": "people", "seed": 2} +{"prompt": "Super close macro shot of a water drop on pine sprouts sparkling in the bright with a light background hyperrealistic light photography", "category": "plants", "seed": 3} +{"prompt": "Toy Story style character of a happy friendly goose dressed in a pink formula 1 suit. Full body", "category": "art", "seed": 6} +{"prompt": "Photograph of a very small work office. It has a window through which you can see a city. A black glass table with black trestles. Very bright. White walls. Light wooden floor. A black reclining wheeled chair. It transmits relaxation, peace, tranquility.", "category": "indoor", "seed": 7} +{"prompt": "anthropomorphic lion pixar style white background", "category": "animals", "seed": 10} +{"prompt": "cyberpunk scene, interior of a very sophisticated vehicle, it rains heavily cyberpunk, very clear and detailed photos that clearly show even the smallest details, Best quality, clear image, image of the product with small plate, neon color palette, with precise focus, high resolution image, high resolution image with large capacity, 8k, photos like real food photos, product photos that look delicious, low angle shot, wide shot, art by Michelangelo Grand Master", "category": "vehicles", "seed": 12} +{"prompt": "redheaded beautiful 16 year old witch in a black gown standing inside a grove of trees laden with red berries and green leaves with the wind whipping her hair and her dress. Photorealistic. Cinematic.", "category": "fashion", "seed": 13} +{"prompt": "roses, surrounded by leaf motifs in a circluar shape, 2d vector, neon colors, vector design on the edges of the image", "category": "logo", "seed": 19} +{"prompt": "Alaskan Glacial Lake Portage in late winter directional light godrays detailed sky and clouds, chairoscuro shadows, sunset cinematic in the style of national geographic award winning photography alcohol ink overpaint.6", "category": "landscape", "seed": 5} +{"prompt": "an aerial view of a food vendors tent interior, top down view, flowers, photo realistic,", "category": "food", "seed": 9} +{"prompt": "reptilian King Charles and Queen Camilla", "category": "people", "seed": 11} +{"prompt": "a background full of flowers with black and white manga style", "category": "plants", "seed": 4} +{"prompt": "Heroine fighting against a huge Machine Hydra in the middle of a destroyed New York", "category": "art", "seed": 44} +{"prompt": "modern house at christmas night, cinematic and typical USA house", "category": "indoor", "seed": 23} +{"prompt": "rabbit, high quality, clipart, white background, vintage", "category": "animals", "seed": 30} +{"prompt": "climate crisis in mumbai, 200 years in the future, hitech buildings, advanced technology, homeless people", "category": "vehicles", "seed": 14} +{"prompt": "obese happy Lindsay Lohan photo shoot of obese Lindsay Lohan dressed as a cyberpunk sitting next to an 18 wheeler truck looking drunk and happy at a truck stop, wind blowing hair back, laughing and having a good time next to beer bottles, nighttime photography, twilight hour, tattoos, piercings, wide angle, soft box stock style photography, canon dslr, 50mm", "category": "fashion", "seed": 35} +{"prompt": "Minimal logo gradient in circle in center Corvette silhouette Blue gradient, white background, by Chip Foose", "category": "logo", "seed": 22} +{"prompt": "an ink painting red poppies along a river bank with a cottage in the distance", "category": "landscape", "seed": 8} +{"prompt": "food photography. familystyle feast from side angle. american rustic cottage breakfast. omelet, bacon, sauage. in foreground focus 4k on floral decorative plate with an omelette with lots of cheese. half eaten, bite taken out omelet, gooey cheesy . in background on table serving dish of sausage link, bratwersts, and bacon fatty stips. for familystyle breakfast meal", "category": "food", "seed": 15} +{"prompt": "Still from a campy, grotesque 1980s Estonian commercial for tomato juice featuring a happy overweight family lavishly dining on the strange, terrible product, horror vibes", "category": "people", "seed": 17} +{"prompt": "green leaf like texture, macro, hyper realistic, unfocused, vegetable, background abstract ar 916", "category": "plants", "seed": 38} +{"prompt": "another image of a wizard with smoke thrown at him, in the style of mark lovett, tokina atx 1116mm f2.8 pro dx ii, matthias haker, realistic hyperdetailed portraits, glittery and shiny, john howe, historical", "category": "art", "seed": 47} +{"prompt": "a hot pink wonderland", "category": "indoor", "seed": 28} +{"prompt": "Beautiful Siberian cat sitting at the window, phorealistic, full frame, cinematic, looks like professional hdr photography, beautiful cinematic lighting, ultrahigh quality", "category": "animals", "seed": 31} +{"prompt": "A dramatic nightscape of a bustling city with glowing neon lights, captured from a rooftop vantage point using a Nikon Z7 II and a Nikon Z 2470mm f2.8 S lens.", "category": "vehicles", "seed": 21} +{"prompt": "a hyperrealistic underwater photo of a mermaid under the ocean, glowy ambient, ar 169", "category": "fashion", "seed": 36} +{"prompt": "a 2d frog, top view, made only from bubbles, every bubble is an oval bubble,stretched along various curves", "category": "logo", "seed": 27} +{"prompt": "The cold breath of the north. Deep dark tones, dynamic light, hdr", "category": "landscape", "seed": 16} +{"prompt": "A photorealistic digital artwork featuring a zombieburger as the centerpiece of a postapocalyptic wasteland. Medium digital art. Colors muted, desaturated tones with a focus on grays and browns to convey the bleakness of the environment. Lighting harsh, with a single spotlight directed at the burger as if its the only thing worth fighting for in this world. Composition a wideangle lens capturing the burger in the midground, surrounded by hordes of zombies in the foreground and the ruins of a city in the background. The burger should be presented in all its delicious glory, with the toppings and sauces dripping down the sides, tempting even the undead to take a bite.", "category": "food", "seed": 26} diff --git a/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/intermediate.sh b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..d1cc20034494d086edd6d394635411a59056dc61 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,13 @@ +#!/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 +chmod -R go-rwx /tests + +cd /tests +GRADER_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/svdquant-w4a4-psnr/environment/are-grader-ctx/requirements-verifier.txt b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..04676c89520bf969f2cb861ad1811f46d8370700 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/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/svdquant-w4a4-psnr/environment/are-grader-ctx/requirements.txt b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3eb7b818f0c853966150e30553d1f8e371f94a42 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,4 @@ +diffusers==0.39.0 +huggingface-hub==1.11.0 +safetensors==0.8.0 +sentencepiece==0.2.1 diff --git a/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/test.sh b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..abea8f5274b8cc21ad204b71c2650de364385eff --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/test.sh @@ -0,0 +1,13 @@ +#!/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 +chmod -R go-rwx /tests + +cd /tests +GRADER_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/svdquant-w4a4-psnr/environment/are-grader-ctx/test_state.py b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0746421c0a5c4fb8490a4ab4beedfdb65c15bb --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/environment/are-grader-ctx/test_state.py @@ -0,0 +1,54 @@ +import json +import os +import random +import sys +from pathlib import Path + +import numpy as np +import torch + +random.seed(0) +np.random.seed(0) +torch.manual_seed(0) +torch.cuda.manual_seed_all(0) +torch.set_num_threads(1) +torch.use_deterministic_algorithms(True) +torch.backends.cudnn.deterministic = True +torch.backends.cudnn.benchmark = False +torch.backends.cuda.matmul.allow_tf32 = False + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import grader_core + +METRIC_PATH = Path("/logs/verifier/metric.json") + + +def invalid(reason): + return { + "valid": False, + "metric_name": "mean_psnr_db", + "metric": None, + "reward": 0.0, + "reason": reason, + } + + +def test_submission(): + split = os.environ.get("GRADER_SPLIT", "final") + if split not in {"intermediate", "final"}: + result = invalid("invalid grader split") + else: + entry = Path("/app/output/quantize.py") + prompts = Path("/tests/hidden_data") / split / "prompts.jsonl" + try: + print(f"trusted CUDA device_count={__import__('torch').cuda.device_count()}") + if set(entry.parent.iterdir()) != {entry}: + raise ValueError("only /app/output/quantize.py may be created or modified") + if not entry.is_file() or entry.is_symlink() or entry.stat().st_size == 0: + raise FileNotFoundError("missing or empty /app/output/quantize.py") + result = grader_core.score(entry, prompts) + except Exception as exc: + print(f"grading failure: {type(exc).__name__}: {exc}") + result = invalid(f"{type(exc).__name__}: {exc}") + METRIC_PATH.write_text(json.dumps(result, sort_keys=True) + "\n") + assert result.get("valid") is True, result.get("reason", "invalid submission") diff --git a/tasks/svdquant-w4a4-psnr/environment/docker-compose.yaml b/tasks/svdquant-w4a4-psnr/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0bb3f9bff6177543021b715040566def62fee4f5 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/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: 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: "14400" + 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/svdquant-w4a4-psnr/task.toml b/tasks/svdquant-w4a4-psnr/task.toml index e17c7b580f775865289e765a808da7b66ea93fc7..9c3e3ffb06b7745ba15749c4b73c774b41b3e0a5 100644 --- a/tasks/svdquant-w4a4-psnr/task.toml +++ b/tasks/svdquant-w4a4-psnr/task.toml @@ -1,46 +1,75 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/svdquant-w4a4-psnr" -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 = "ML serving and deployment" -task_objective = [ "Optimize", "Transform", "Implement",] -artifact_type = [ "Codebase", "Generated output artifact",] +task_objective = [ + "Optimize", + "Transform", + "Implement", +] +artifact_type = [ + "Codebase", + "Generated output artifact", +] expert_time_estimate_hours = 4.0 +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 = 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/svdquant-w4a4-psnr/tests/Dockerfile b/tasks/svdquant-w4a4-psnr/tests/Dockerfile index 09c7a3dfb6cc7c0e0a6e9c74f2fd6508b4816048..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/svdquant-w4a4-psnr/tests/Dockerfile +++ b/tasks/svdquant-w4a4-psnr/tests/Dockerfile @@ -1,42 +1,2 @@ -FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 - -ENTRYPOINT [] -ENV PYTHONPATH= -ENV PYTHONSAFEPATH=1 -ENV PYTHONNOUSERSITE=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 \ - CUBLAS_WORKSPACE_CONFIG=:4096:8 - -RUN useradd --create-home --uid 1001 agent -COPY ./requirements.txt /tmp/requirements.txt -RUN /usr/bin/python3 -m pip install --no-cache-dir -r /tmp/requirements.txt \ - && rm /tmp/requirements.txt -RUN /usr/bin/python3 -c "from huggingface_hub import snapshot_download; snapshot_download('PixArt-alpha/PixArt-Sigma-XL-2-1024-MS', revision='e102b3591cc82e97071b8b4cb90d834d0c487207', local_dir='/opt/pixart-sigma', ignore_patterns=['asset/*', 'README.md', '.gitattributes'])" \ - && rm -rf /root/.cache/huggingface - -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 mkdir -p /app/output /logs/verifier /tests/hidden_data/intermediate /tests/hidden_data/final -COPY ./test.sh /tests/test.sh -COPY ./intermediate.sh /tests/intermediate.sh -COPY ./test_state.py /tests/test_state.py -COPY ./compute_reward.py /tests/compute_reward.py -COPY ./grader_core.py /tests/grader_core.py -COPY ./candidate_runner.py /tests/candidate_runner.py -COPY ./hidden_data/intermediate/prompts.jsonl /tests/hidden_data/intermediate/prompts.jsonl -COPY ./hidden_data/final/prompts.jsonl /tests/hidden_data/final/prompts.jsonl -COPY ./app_data/calibration_prompts.jsonl /app/data/calibration_prompts.jsonl -RUN chown -R root:root /tests /logs/verifier /opt/pixart-sigma \ - && chmod 700 /tests /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \ - && chmod +x /tests/test.sh /tests/intermediate.sh \ - && find /tests /app/data -exec touch -d @1700000000 {} + -ENV HF_HUB_OFFLINE=1 -ENV TRANSFORMERS_OFFLINE=1 -WORKDIR /tests +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/svdquant-w4a4-psnr/tests/finalize.py b/tasks/svdquant-w4a4-psnr/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/svdquant-w4a4-psnr/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/svdquant-w4a4-psnr/tests/test.sh b/tasks/svdquant-w4a4-psnr/tests/test.sh index abea8f5274b8cc21ad204b71c2650de364385eff..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/svdquant-w4a4-psnr/tests/test.sh +++ b/tasks/svdquant-w4a4-psnr/tests/test.sh @@ -1,13 +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 -chmod -R go-rwx /tests - -cd /tests -GRADER_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/tgat-milp-branching-node-count/environment/.dockerignore b/tasks/tgat-milp-branching-node-count/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/Dockerfile b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..12dd31a81502a2bf7d7b3a504e57e28ac9a061f1 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,37 @@ +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/submission /logs/verifier + +COPY ./bnbenv /opt/bnbenv + +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 {} + \ + && chmod 0700 /usr/local/lib/python3.13/site-packages/pyscipopt + +WORKDIR /tests + +ENV HF_HUB_OFFLINE=1 +ENV TRANSFORMERS_OFFLINE=1 diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/Dockerfile.are b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..ce2183ced3676146d41f31f80510b1dae440a724 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,55 @@ +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/submission /logs/verifier + +COPY ./bnbenv /opt/bnbenv + +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 {} + \ + && chmod 0700 /usr/local/lib/python3.13/site-packages/pyscipopt + +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/tgat-milp-branching-node-count/environment/are-grader-ctx/are/drain.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/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/tgat-milp-branching-node-count/environment/are-grader-ctx/are/server.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/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/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/__init__.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/features.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/features.py new file mode 100644 index 0000000000000000000000000000000000000000..95e3114d6a326d8f3bc4e6b4654aaeede6383856 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/features.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +import numpy as np + +VAR_FEATURE_NAMES = ( + "obj_coeff", + "lb_local", + "ub_local", + "sol_val", + "sol_frac", + "sol_at_lb", + "sol_at_ub", + "reduced_cost", + "basis_lower", + "basis_basic", + "basis_upper", + "basis_zero", + "age_norm", + "degree_norm", +) + +CONS_FEATURE_NAMES = ( + "bias", + "has_lhs", + "is_tight", + "dual_norm", + "age_norm", + "obj_cos_sim", +) + +N_VAR_FEATURES = len(VAR_FEATURE_NAMES) +N_CONS_FEATURES = len(CONS_FEATURE_NAMES) + +_BASIS = {"lower": 8, "basic": 9, "upper": 10, "zero": 11} + + +def extract(model, cands, cands_sol): + """Build the observation dict for the current node of `model`. + + `cands` are the fractional branching candidates (pyscipopt Variables) and + `cands_sol` their LP values, as returned by getLPBranchCands(). + """ + cols = model.getLPColsData() + rows = model.getLPRowsData() + n_cols = len(cols) + n_rows = len(rows) + n_lps = model.getNLPs() + inv_lps = 1.0 / (1.0 + n_lps) + + obj = np.empty(n_cols, dtype=np.float64) + lb = np.empty(n_cols, dtype=np.float64) + ub = np.empty(n_cols, dtype=np.float64) + sol = np.empty(n_cols, dtype=np.float64) + age = np.empty(n_cols, dtype=np.float64) + redcost = np.empty(n_cols, dtype=np.float64) + basis = np.zeros((n_cols, 4), dtype=np.float32) + lp_pos_of = {} + for k, col in enumerate(cols): + var = col.getVar() + obj[k] = col.getObjCoeff() + lb[k] = col.getLb() + ub[k] = col.getUb() + sol[k] = col.getPrimsol() + age[k] = col.getAge() + redcost[k] = model.getVarRedcost(var) + slot = _BASIS.get(col.getBasisStatus()) + if slot is not None: + basis[k, slot - 8] = 1.0 + lp_pos_of[var.getIndex()] = k + + obj_norm = float(np.linalg.norm(obj)) + if obj_norm <= 0.0: + obj_norm = 1.0 + + edge_rows = [] + edge_cols = [] + edge_vals = [] + cons = np.zeros((n_rows, N_CONS_FEATURES), dtype=np.float32) + for r, row in enumerate(rows): + row_cols = row.getCols() + row_vals = row.getVals() + norm = float(row.getNorm()) + if norm <= 0.0: + norm = 1.0 + constant = row.getConstant() + lhs = row.getLhs() + rhs = row.getRhs() + activity = 0.0 + dot = 0.0 + for col, val in zip(row_cols, row_vals): + pos = col.getLPPos() + if pos < 0: + continue + edge_rows.append(r) + edge_cols.append(pos) + edge_vals.append(val / norm) + activity += val * sol[pos] + dot += val * obj[pos] + has_lhs = 1.0 if lhs > -1e19 else 0.0 + bound = rhs if rhs < 1e19 else lhs + if bound > 1e19 or bound < -1e19: + bound = 0.0 + tight = 0.0 + act = activity + constant + if (rhs < 1e19 and abs(act - rhs) < 1e-6) or \ + (lhs > -1e19 and abs(act - lhs) < 1e-6): + tight = 1.0 + cons[r, 0] = (bound - constant) / norm + cons[r, 1] = has_lhs + cons[r, 2] = tight + cons[r, 3] = row.getDualsol() / (norm * obj_norm) + cons[r, 4] = row.getAge() * inv_lps + cons[r, 5] = dot / (norm * obj_norm) + + edge_index = np.empty((2, len(edge_rows)), dtype=np.int32) + edge_index[0] = np.asarray(edge_rows, dtype=np.int32) + edge_index[1] = np.asarray(edge_cols, dtype=np.int32) + edge_values = np.asarray(edge_vals, dtype=np.float32) + degree = np.bincount(edge_index[1], minlength=n_cols).astype(np.float32) + + var_feats = np.empty((n_cols, N_VAR_FEATURES), dtype=np.float32) + var_feats[:, 0] = obj / obj_norm + var_feats[:, 1] = lb + var_feats[:, 2] = ub + var_feats[:, 3] = sol + var_feats[:, 4] = sol - np.floor(sol) + var_feats[:, 5] = (np.abs(sol - lb) < 1e-9).astype(np.float32) + var_feats[:, 6] = (np.abs(sol - ub) < 1e-9).astype(np.float32) + var_feats[:, 7] = redcost / obj_norm + var_feats[:, 8:12] = basis + var_feats[:, 12] = age * inv_lps + var_feats[:, 13] = degree / max(1, n_rows) + + cand_idx = np.array([lp_pos_of[v.getIndex()] for v in cands], + dtype=np.int32) + cand_feats = np.ascontiguousarray(var_feats[cand_idx]) + + primal = model.getPrimalbound() + dual = model.getDualbound() + obs = { + "var_feats": np.ascontiguousarray(var_feats), + "cons_feats": np.ascontiguousarray(cons), + "edge_index": np.ascontiguousarray(edge_index), + "edge_vals": np.ascontiguousarray(edge_values), + "cand_idx": cand_idx, + "cand_feats": cand_feats, + "depth": int(model.getDepth()), + "n_nodes": int(model.getNNodes()), + "n_lps": int(n_lps), + "dual_bound": float(dual), + "primal_bound": float(primal), + "gap": float(model.getGap()), + } + return obs diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/host.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/host.py new file mode 100644 index 0000000000000000000000000000000000000000..34354da1ef82373dc2a075224cf8334f6ccb95c3 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/host.py @@ -0,0 +1,163 @@ +from __future__ import annotations + +import importlib.util +import io +import os +import sys +import traceback + +import numpy as np + +from . import protocol + +BLOCKED_MODULES = ( + "pyscipopt", + "gurobipy", + "mip", + "pulp", + "highspy", + "ortools", + "cplex", + "docplex", + "xpress", + "cylp", +) + +MAX_ERROR_CHARS = 400 + +NATIVE_ROOTS = ("/usr/local/lib/", "/usr/lib/", "/lib/") +NATIVE_SUFFIXES = (".so", ".pyd", ".dylib") + + +def _audit(event, args): + path = None + if event == "import" and len(args) > 1: + path = args[1] + elif event in ("ctypes.dlopen", "ctypes.LoadLibrary") and args: + path = args[0] + if not isinstance(path, str) or not path: + return + if path.endswith(NATIVE_SUFFIXES) or ".so." in path: + if not path.startswith(NATIVE_ROOTS): + raise PermissionError( + f"loading the native module {path} is not allowed inside the " + "branching policy process") + + +class _BlockSolvers: + """meta_path finder that refuses exactly the modules listed above.""" + + def find_module(self, fullname, path=None): + return None + + def find_spec(self, fullname, path=None, target=None): + root = fullname.split(".", 1)[0] + if root in BLOCKED_MODULES: + raise ImportError( + f"import of {root!r} is blocked inside the branching policy " + "process") + return None + + +def _load_policy_module(submission_dir, entry_point): + path = os.path.join(submission_dir, entry_point) + if not os.path.isfile(path): + raise FileNotFoundError(f"missing entry point {path}") + if os.path.getsize(path) == 0: + raise ValueError(f"empty entry point {path}") + if submission_dir not in sys.path: + sys.path.insert(0, submission_dir) + spec = importlib.util.spec_from_file_location("agent_policy", path) + if spec is None or spec.loader is None: + raise ImportError(f"cannot load {path}") + module = importlib.util.module_from_spec(spec) + sys.modules["agent_policy"] = module + spec.loader.exec_module(module) + return module + + +def _freeze(obs): + for value in obs.values(): + if isinstance(value, np.ndarray): + value.setflags(write=False) + return obs + + +def _short(exc): + text = f"{type(exc).__name__}: {exc}" + return text[:MAX_ERROR_CHARS].replace("\n", " ") + + +def main(): + try: + import torch + torch.set_num_threads(1) + except ImportError: + pass + import numpy.linalg + sys.meta_path.insert(0, _BlockSolvers()) + sys.addaudithook(_audit) + inp = io.open(0, "rb", closefd=False) + out = io.open(int(os.environ["BNB_REPLY_FD"]), "wb", closefd=False) + + module = None + policy = None + while True: + try: + frame = protocol.read_obs(inp) + except Exception: + return 1 + if frame is None: + return 0 + cmd = frame.get("cmd") + if cmd == "quit": + return 0 + if cmd == "load": + try: + module = _load_policy_module(frame["submission_dir"], + frame["entry_point"]) + loader = getattr(module, "load", None) + if loader is not None: + loader() + except BaseException as exc: + traceback.print_exc(file=sys.stderr) + protocol.write_decision(out, "err " + _short(exc)) + return 0 + protocol.write_decision(out, "ready") + elif cmd == "new": + try: + policy = module.Policy() + except BaseException as exc: + traceback.print_exc(file=sys.stderr) + protocol.write_decision(out, "err " + _short(exc)) + return 0 + protocol.write_decision(out, "ok") + elif cmd == "select": + obs = _freeze(frame["obs"]) + n_cands = len(obs["cand_idx"]) + try: + choice = policy.select(obs) + except BaseException as exc: + traceback.print_exc(file=sys.stderr) + protocol.write_decision(out, "err " + _short(exc)) + return 0 + if isinstance(choice, bool) or not isinstance( + choice, (int, np.integer)): + protocol.write_decision( + out, f"err select returned {type(choice).__name__}, " + "expected int") + return 0 + index = int(choice) + if not 0 <= index < n_cands: + protocol.write_decision( + out, f"err select returned {index}, outside " + f"[0, {n_cands})") + return 0 + protocol.write_decision(out, f"i {index}") + else: + protocol.write_decision(out, "err unknown command") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/protocol.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..8b7292afbc065d8a27dd4c0a587c04688265a220 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/protocol.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import pickle +import struct + +_HEADER = struct.Struct(" MAX_FRAME: + raise ValueError("frame too large") + body = _read_exactly(stream, size) + if body is None: + return None + return pickle.loads(body) + + +def write_decision(stream, text): + data = (text + "\n").encode("ascii", "replace") + stream.write(data) + stream.flush() + + +def _read_exactly(stream, size): + chunks = [] + remaining = size + while remaining: + chunk = stream.read(remaining) + if not chunk: + return None + chunks.append(chunk) + remaining -= len(chunk) + return b"".join(chunks) diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/runner.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..d0c930195d08ac3efd2a28cb2f4a7157ada14ae9 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/runner.py @@ -0,0 +1,279 @@ +from __future__ import annotations + +import os +import select +import signal +import subprocess +import sys +import time +from pathlib import Path + +from pyscipopt import SCIP_RESULT, Branchrule + +from . import features, protocol +from .setcover import NODE_LIMIT, TIME_LIMIT, build_model + +ENTRY_POINT = "policy.py" +STARTUP_LIMIT = 30.0 +DECISION_READ_CHUNK = 4096 + + +class PolicyChannel: + """Owns the policy subprocess and the framed request/response cycle.""" + + def __init__(self, submission_dir, host_pkg_root, python_exe=None, + launch_prefix=(), stderr_to=None, entry_point=ENTRY_POINT, + drop_to_uid=None): + self.submission_dir = str(Path(submission_dir).resolve()) + self.entry_point = entry_point + env = { + "PATH": "/usr/local/bin:/usr/bin:/bin", + "PYTHONPATH": str(Path(host_pkg_root).resolve()), + "PYTHONSAFEPATH": "1", + "PYTHONHASHSEED": "0", + "PYTHONDONTWRITEBYTECODE": "1", + "HOME": "/home/agent", + "TMPDIR": "/tmp", + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", + } + read_fd, write_fd = os.pipe() + os.set_inheritable(write_fd, True) + env["BNB_REPLY_FD"] = str(write_fd) + cmd = list(launch_prefix) + [ + python_exe or sys.executable, "-c", + "from bnbenv.host import main; raise SystemExit(main())", + ] + + def _drop(): + """Drop to the unprivileged uid before exec, in the child.""" + os.setgroups([]) + os.setgid(int(drop_to_uid)) + os.setuid(int(drop_to_uid)) + + self.proc = subprocess.Popen( + cmd, + stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, + stderr=stderr_to if stderr_to is not None else subprocess.DEVNULL, + env=env, + pass_fds=(write_fd,), + start_new_session=True, + preexec_fn=(_drop if drop_to_uid and not launch_prefix else None), + cwd="/tmp", + ) + os.close(write_fd) + self.reply = os.fdopen(read_fd, "rb") + self.error = None + + def _send(self, payload): + protocol.write_obs(self.proc.stdin, payload) + + def _recv(self, budget): + """Read one newline-terminated reply, or None on timeout/death.""" + deadline = time.monotonic() + budget + buf = bytearray() + fd = self.reply.fileno() + while b"\n" not in buf: + remaining = deadline - time.monotonic() + if remaining <= 0: + self.error = "policy process exceeded its wall-clock budget" + return None + ready, _, _ = select.select([fd], [], [], min(remaining, 1.0)) + if not ready: + continue + chunk = os.read(fd, DECISION_READ_CHUNK) + if not chunk: + self.error = "policy process exited without answering" + return None + buf.extend(chunk) + if len(buf) > 1 << 16: + self.error = "policy process wrote an oversized reply" + return None + return bytes(buf).split(b"\n", 1)[0].decode("ascii", "replace") + + def start(self, budget=STARTUP_LIMIT): + self._send({"cmd": "load", "submission_dir": self.submission_dir, + "entry_point": self.entry_point}) + reply = self._recv(budget) + if reply != "ready": + self.error = self.error or f"load failed ({reply})" + return False + self._send({"cmd": "new"}) + reply = self._recv(budget) + if reply != "ok": + self.error = self.error or f"Policy() failed ({reply})" + return False + return True + + def decide(self, obs, budget, n_cands): + try: + self._send({"cmd": "select", "obs": obs}) + except (BrokenPipeError, OSError): + self.error = "policy process closed the channel" + return None + reply = self._recv(budget) + if reply is None: + return None + if not reply.startswith("i "): + self.error = f"policy error ({reply[:200]})" + return None + try: + index = int(reply[2:]) + except ValueError: + self.error = f"unparseable decision ({reply[:80]})" + return None + if not 0 <= index < n_cands: + self.error = f"decision {index} outside [0, {n_cands})" + return None + return index + + def extra_processes(self): + """Live processes in the policy session other than the policy itself.""" + try: + sid = os.getsid(self.proc.pid) + except (ProcessLookupError, PermissionError, OSError): + return 0 + extra = 0 + for entry in os.listdir("/proc"): + if not entry.isdigit(): + continue + pid = int(entry) + if pid == self.proc.pid: + continue + try: + if os.getsid(pid) == sid: + extra += 1 + except (ProcessLookupError, PermissionError, OSError): + continue + return extra + + def close(self): + try: + self._send({"cmd": "quit"}) + except Exception: + pass + try: + self.proc.stdin.close() + except Exception: + pass + try: + self.proc.wait(timeout=5) + except Exception: + try: + os.killpg(os.getpgid(self.proc.pid), signal.SIGKILL) + except Exception: + pass + try: + self.proc.wait(timeout=5) + except Exception: + pass + try: + self.reply.close() + except Exception: + pass + + +class HostedBranchrule(Branchrule): + """Hands every branching decision of this solve to the policy process.""" + + def __init__(self, channel, deadline): + super().__init__() + self.channel = channel + self.deadline = deadline + self.decisions = 0 + self.failure = None + + def branchexeclp(self, allowaddcons): + if self.failure is not None: + return {"result": SCIP_RESULT.DIDNOTRUN} + cands, cands_sol, _frac, ncands, _nprio, _nimpl = \ + self.model.getLPBranchCands() + if ncands == 0: + return {"result": SCIP_RESULT.DIDNOTRUN} + cands = list(cands)[:ncands] + obs = features.extract(self.model, cands, cands_sol) + budget = self.deadline - time.monotonic() + if budget <= 0: + self.failure = "run exceeded its wall-clock budget" + self.model.interruptSolve() + return {"result": SCIP_RESULT.DIDNOTRUN} + index = self.channel.decide(obs, budget, len(cands)) + if index is None: + self.failure = self.channel.error or "policy failed" + self.model.interruptSolve() + return {"result": SCIP_RESULT.DIDNOTRUN} + self.decisions += 1 + if self.decisions % 20 == 1 and self.channel.extra_processes(): + self.failure = "policy process spawned extra processes" + self.model.interruptSolve() + return {"result": SCIP_RESULT.DIDNOTRUN} + self.model.branchVar(cands[index]) + return {"result": SCIP_RESULT.BRANCHED} + + +def run_one(seed, shift, submission_dir, host_pkg_root, python_exe=None, + launch_prefix=(), stderr_to=None, node_limit=NODE_LIMIT, + time_limit=TIME_LIMIT, startup_timeout=STARTUP_LIMIT, + entry_point=ENTRY_POINT, drop_to_uid=None): + """Solve one instance with the submission in charge of variable selection. + + Returns a record with the node count charged for this run: the solver's own + total node count when it proved optimality, and `node_limit` otherwise. + """ + record = { + "seed": int(seed), + "shift": int(shift), + "nodes": int(node_limit), + "raw_nodes": None, + "status": "unstarted", + "proved_optimal": False, + "decisions": 0, + "solve_seconds": 0.0, + "error": None, + "extra_processes": 0, + } + if not (Path(submission_dir) / entry_point).is_file(): + record["status"] = "missing_entry_point" + record["error"] = f"no {entry_point} in {submission_dir}" + return record + + channel = PolicyChannel(submission_dir, host_pkg_root, + python_exe=python_exe, launch_prefix=launch_prefix, + stderr_to=stderr_to, entry_point=entry_point, + drop_to_uid=drop_to_uid) + try: + if not channel.start(budget=startup_timeout): + record["status"] = "startup_failed" + record["error"] = channel.error + return record + + model, _xs = build_model(seed, shift, node_limit=node_limit, + time_limit=time_limit) + started = time.monotonic() + rule = HostedBranchrule(channel, started + time_limit) + model.includeBranchrule(rule, "hosted", "policy-process branching", + priority=10_000_000, maxdepth=-1, + maxbounddist=1.0) + model.optimize() + record["solve_seconds"] = round(time.monotonic() - started, 3) + record["status"] = model.getStatus() + record["decisions"] = rule.decisions + raw_nodes = int(model.getNTotalNodes()) + record["raw_nodes"] = raw_nodes + record["extra_processes"] = channel.extra_processes() + proved = (rule.failure is None and model.getStatus() == "optimal" + and raw_nodes <= node_limit + and record["extra_processes"] == 0) + if rule.failure is not None: + record["error"] = rule.failure + elif record["extra_processes"] > 0: + record["error"] = "policy process spawned extra processes" + record["proved_optimal"] = bool(proved) + record["nodes"] = raw_nodes if proved else int(node_limit) + del model + return record + finally: + channel.close() diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/setcover.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/setcover.py new file mode 100644 index 0000000000000000000000000000000000000000..5918d1c14ea49ebdc1f8daf382ad724b4c53a5ae --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/bnbenv/setcover.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import numpy as np + +N_ROWS = 500 +N_COLS = 1000 +DENSITY = 0.05 +MAX_COEF = 100 + +NODE_LIMIT = 20000 +TIME_LIMIT = 120.0 + + +def generate_instance(seed, n_rows=N_ROWS, n_cols=N_COLS, density=DENSITY, + max_coef=MAX_COEF): + """Return (costs, row_indptr, row_indices) for one set covering instance. + + `costs` is an int array of length n_cols. The constraint matrix is returned + in CSR form over rows: row r covers columns + `row_indices[row_indptr[r]:row_indptr[r + 1]]`. + """ + rng = np.random.default_rng(int(seed)) + nnzrs = int(n_rows * n_cols * density) + if nnzrs // n_rows < 2 or nnzrs // n_cols < 2: + raise ValueError("density too low for the requested shape") + + indices = rng.integers(0, n_rows, size=nnzrs) + col_of_nnz = rng.integers(0, n_cols, size=nnzrs) + col_of_nnz[: 2 * n_cols] = np.repeat(np.arange(n_cols), 2) + _, col_nnzs = np.unique(col_of_nnz, return_counts=True) + indices[:n_rows] = rng.permutation(n_rows) + + i = 0 + indptr = [0] + for n in col_nnzs: + if i >= n_rows: + indices[i:i + n] = rng.choice(n_rows, size=n, replace=False) + elif i + n > n_rows: + remaining = np.setdiff1d(np.arange(n_rows), indices[i:n_rows], + assume_unique=True) + indices[n_rows:i + n] = rng.choice( + remaining, size=i + n - n_rows, replace=False) + i += n + indptr.append(i) + + costs = rng.integers(1, max_coef + 1, size=n_cols) + + col_indptr = np.asarray(indptr, dtype=np.int64) + row_of_nnz = np.asarray(indices[:i], dtype=np.int64) + col_ids = np.repeat(np.arange(n_cols, dtype=np.int64), np.diff(col_indptr)) + order = np.lexsort((col_ids, row_of_nnz)) + row_sorted = row_of_nnz[order] + row_indices = col_ids[order] + row_counts = np.bincount(row_sorted, minlength=n_rows) + row_indptr = np.concatenate(([0], np.cumsum(row_counts))).astype(np.int64) + return costs.astype(np.int64), row_indptr, row_indices + + +def build_model(seed, shift, node_limit=NODE_LIMIT, time_limit=TIME_LIMIT, + **gen_kwargs): + """Build the pinned pyscipopt Model for (instance seed, seed shift).""" + from pyscipopt import Model, quicksum + + costs, row_indptr, row_indices = generate_instance(seed, **gen_kwargs) + n_cols = len(costs) + + model = Model(f"setcover-{seed}") + model.hideOutput() + xs = [model.addVar(vtype="B", obj=float(costs[j]), name=f"x{j}") + for j in range(n_cols)] + for r in range(len(row_indptr) - 1): + cols = row_indices[row_indptr[r]:row_indptr[r + 1]] + model.addCons(quicksum(xs[int(j)] for j in cols) >= 1, name=f"c{r}") + + model.setIntParam("separating/maxrounds", 0) + model.setIntParam("presolving/maxrestarts", 0) + model.setIntParam("randomization/permutationseed", int(shift)) + model.setIntParam("randomization/randomseedshift", int(shift)) + model.setIntParam("timing/clocktype", 2) + model.setLongintParam("limits/nodes", int(node_limit)) + model.setRealParam("limits/time", float(time_limit)) + model.setParam("display/verblevel", 0) + return model, xs diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/compute_reward.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..066c6d74153cde4557431798eed29be5bdc7c615 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import json +import math +from pathlib import Path + +REWARD_PATH = Path("/logs/verifier/reward.txt") +METRIC_PATH = Path("/logs/verifier/metric.json") + +try: + payload = json.loads(METRIC_PATH.read_text()) + value = float(payload["reward"]) if payload.get("valid") else 0.0 + 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/tgat-milp-branching-node-count/environment/are-grader-ctx/grader_core.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..35058f6f059d0af7945fc80261fffdf402b89743 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import json +import math +from pathlib import Path + +NODE_CAP = 20000 + +M0_BY_PANEL = {"intermediate": 398.89, "final": 595.15} +M0_DEFAULT = 487.0 +BASELINE_SCORE = 126.0 + + +def m0_for(panel): + return M0_BY_PANEL.get(panel, M0_DEFAULT) + +MAX_SUBMISSION_BYTES = 200 * 1024 * 1024 + + +def shifted_geomean(nodes): + """exp(mean(log(n + 1))) - 1 over the run node counts.""" + values = [float(n) for n in nodes] + if not values: + raise ValueError("no runs to aggregate") + return math.exp(sum(math.log(v + 1.0) for v in values) / len(values)) - 1.0 + + +def reward_from_metric(metric, m0=M0_DEFAULT): + """Map a node-count metric to a reward in [0, 1]; lower metric is better.""" + if metric is None or not math.isfinite(metric) or metric < 0: + return 0.0 + x_ref = math.log1p(m0) - math.log1p(BASELINE_SCORE) + assert x_ref > 0, "malformed task: the baseline score does not beat the trivial rule" + x = math.log1p(m0) - math.log1p(metric) + u = max(0.0, x) / x_ref + return u / (1.0 + u) + + +def load_panel(panel_dir): + """Read one sealed panel: instance seeds and solver seed shifts.""" + spec = json.loads((Path(panel_dir) / "panel.json").read_text()) + seeds = [int(s) for s in spec["seeds"]] + shifts = [int(k) for k in spec["shifts"]] + if not seeds or not shifts: + raise ValueError(f"empty panel in {panel_dir}") + return seeds, shifts diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/hidden_data/final/panel.json b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/hidden_data/final/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..ff73cb483b7f3e6c6cd7acac0853c77d824c1e6b --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/hidden_data/final/panel.json @@ -0,0 +1 @@ +{"seeds": [166168984713443, 166608692677627, 167335946794831, 168166293748666, 168203654674866, 168818544469219, 169926472391610, 172624471364011, 172942070534143, 173033243417267, 173831499122182, 173911671553598, 174636451767918, 175222218927612, 177885408025558, 178260741575725, 179025685820358, 180180769861047, 180616911470984, 181047369429824, 181938761321275, 182106013640696, 183087060150036, 183913877006466, 184625836524321, 185683452554815, 185999888802787, 188592428319028, 188838073799118, 190234398654864, 191188026842038, 191200837785332, 191926700239707, 192327986971286, 192621300834950, 193657742995583, 195110041367383, 195497169949370, 195581619515192, 195646848757014], "shifts": [0, 1]} diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/hidden_data/intermediate/panel.json b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/hidden_data/intermediate/panel.json new file mode 100644 index 0000000000000000000000000000000000000000..a67c77958cb83e69889ac0c45d79ba7b9c16b6f1 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/hidden_data/intermediate/panel.json @@ -0,0 +1 @@ +{"seeds": [140850428960565, 141873238652254, 142009945552195, 142112234229131, 143750526809517, 143865201938284, 144346250682454, 144420811669405, 144662001709460, 145430315660390, 145464561064255, 146514491074813, 146758217667556, 149717369692528, 149891128306633, 150753503905554, 150956559704529, 151496602785847, 152310221187048, 152685125717065, 152915148771590, 153366012179151, 153518571530594, 154159515906741, 156158417170012, 156698301178329, 156793614019320, 157889408108203, 157911854925942, 158505497075691, 160077600026441, 160316270683091, 161018456823700, 161729153373888, 163268697742743, 163923044430378, 164876754317166, 165913980076947, 166018908061055, 166158128576784], "shifts": [0, 1]} diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/intermediate.sh b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..c5a2d6d2fd76371c136ffa8982626bbe2397e825 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/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/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/report_intermediate.py +/usr/local/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/report_intermediate.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/report_intermediate.py new file mode 100644 index 0000000000000000000000000000000000000000..e88d08a1dd09433705a34a0dbc1205b5ae17fa20 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/report_intermediate.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +import json +import statistics +from pathlib import Path + +try: + payload = json.loads(Path("/logs/verifier/metric.json").read_text()) +except Exception as exc: + print(f"no grading result to report ({exc})") + raise SystemExit(0) + +if not payload.get("valid"): + print(f"submission rejected: {payload.get('invalid_reason')}") + raise SystemExit(0) + +nodes = sorted(r["nodes"] for r in payload["runs"]) +print("=== public evaluation panel ===") +print(f"runs : {payload['n_runs']}") +print(f"proved optimality : {payload['n_proved_optimal']}") +print(f"charged the cap : {payload['n_charged_cap']}") +print(f"nodes min / median / max : {nodes[0]} / " + f"{int(statistics.median(nodes))} / {nodes[-1]}") +print(f"1-shifted geometric mean : {payload['metric']}") diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/requirements-verifier.txt b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..04676c89520bf969f2cb861ad1811f46d8370700 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/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/tgat-milp-branching-node-count/environment/are-grader-ctx/requirements.txt b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..6a68a0bf90a8e747157198775aa58bb0fd3f472f --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,18 @@ +--index-url https://download.pytorch.org/whl/cpu +--extra-index-url https://pypi.org/simple +numpy==2.3.4 +scipy==1.16.3 +scikit-learn==1.7.2 +pyscipopt==6.2.1 +torch==2.9.1+cpu +filelock==3.32.3 +fsspec==2026.7.0 +jinja2==3.1.6 +joblib==1.5.3 +markupsafe==3.0.3 +mpmath==1.3.0 +networkx==3.6.1 +setuptools==84.0.0 +sympy==1.14.0 +threadpoolctl==3.6.0 +typing_extensions==4.16.0 diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/solve_run.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/solve_run.py new file mode 100644 index 0000000000000000000000000000000000000000..6e9526e20fd38ddadc590a2ca52b68989390cd1a --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/solve_run.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import argparse +import json +import signal +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from bnbenv import runner + + +class _Expired(Exception): + pass + + +def _on_alarm(signum, frame): + raise _Expired("run driver exceeded its own hard limit") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, required=True) + ap.add_argument("--shift", type=int, required=True) + ap.add_argument("--submission", required=True) + ap.add_argument("--host-pkg-root", required=True) + ap.add_argument("--python", default="/usr/local/bin/python3") + ap.add_argument("--time-limit", type=float, required=True) + ap.add_argument("--startup-timeout", type=float, required=True) + ap.add_argument("--launch-prefix", default="") + ap.add_argument("--drop-to-uid", type=int, default=None) + args = ap.parse_args() + + prefix = [p for p in args.launch_prefix.split(",") if p] + signal.signal(signal.SIGALRM, _on_alarm) + signal.alarm(int(args.time_limit + args.startup_timeout + 60)) + try: + record = runner.run_one( + args.seed, args.shift, args.submission, args.host_pkg_root, + python_exe=args.python, launch_prefix=prefix, + time_limit=args.time_limit, + startup_timeout=args.startup_timeout, + drop_to_uid=args.drop_to_uid) + except BaseException as exc: + from bnbenv.setcover import NODE_LIMIT + record = { + "seed": args.seed, "shift": args.shift, "nodes": NODE_LIMIT, + "raw_nodes": None, "status": "run_driver_failed", + "proved_optimal": False, "decisions": 0, "solve_seconds": 0.0, + "error": f"{type(exc).__name__}: {exc}"[:200], + "extra_processes": 0, + } + finally: + signal.alarm(0) + print(json.dumps(record), flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/test.sh b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a592fd0f679078052c765b37ab7bc84f28a8cb7b --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/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/tgat-milp-branching-node-count/environment/are-grader-ctx/test_state.py b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..01d0bd209085343d938521ab39b36fd1750125c4 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/environment/are-grader-ctx/test_state.py @@ -0,0 +1,226 @@ +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import time +from concurrent.futures import ProcessPoolExecutor, as_completed +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import grader_core + +TESTS = Path(__file__).resolve().parent +SUBMISSION = Path("/app/submission") +ENTRY_POINT = "policy.py" +HOST_PKG_ROOT = "/opt" +PANEL = os.environ.get("GRADE_SPLIT", "final") +PANEL_DIR = TESTS / "hidden_data" / PANEL +METRIC_PATH = Path("/logs/verifier/metric.json") + +PYTHON = "/usr/local/bin/python3" +AGENT_UID = 1001 +SBIN = "/usr/sbin:/sbin:/usr/bin:/bin:/usr/local/bin" + + +def _launch_prefix(): + """How the policy process is dropped to uid 1001. + + Measured during the build: wrapping the launch in `setsid runuser -u agent` + inserts a PAM fork, so the pid the solver process holds is the wrapper and + the policy ends up in a different session. `killpg` on a hung policy then + misses it and the run leaks a process that competes with the rest of the + panel for the 8 CPUs. So the solver process drops privilege itself + (`drop_to_uid`, setgroups/setgid/setuid before exec) with + `start_new_session=True`, i.e. setsid(2) in the child: the policy process is + the session leader, uid 1001, and the whole session is killable by pid. + + An explicit prefix is still supported for a host without a root verifier; + `runuser` is resolved here so that path stays available. + """ + if os.geteuid() == 0: + return [] + runuser = shutil.which("runuser", path=SBIN) + setsid = shutil.which("setsid", path=SBIN) + if runuser and setsid: + return [setsid, runuser, "-u", "agent", "--"] + return [] + + +LAUNCH_PREFIX = _launch_prefix() + +WORKERS = 8 +SOLVE_TIMEOUT = 120.0 +STARTUP_TIMEOUT = 30.0 +PANEL_TIMEOUT = 1900.0 +RUN_HARD_TIMEOUT = SOLVE_TIMEOUT + STARTUP_TIMEOUT + 45.0 + +_RESULT = None + + +def _validate_submission(): + """Fail-closed contract checks on the deliverable directory.""" + if not SUBMISSION.is_dir(): + return False, f"{SUBMISSION} is not a directory" + entry = SUBMISSION / ENTRY_POINT + if not entry.is_file(): + return False, f"no {ENTRY_POINT} in {SUBMISSION}" + if entry.stat().st_size == 0: + return False, f"{entry} is empty" + total = 0 + root = SUBMISSION.resolve() + for dirpath, dirnames, filenames in os.walk(SUBMISSION, followlinks=False): + for name in list(dirnames) + list(filenames): + path = Path(dirpath) / name + if path.is_symlink(): + target = Path(os.path.realpath(path)) + if root not in target.parents and target != root: + return False, f"symlink escapes the submission: {path}" + else: + try: + total += path.stat().st_size + except OSError: + pass + if total > grader_core.MAX_SUBMISSION_BYTES: + return False, (f"submission is {total} bytes, over " + f"{grader_core.MAX_SUBMISSION_BYTES}") + return True, None + + +def _run_one(job): + """One graded run, in its own solver subprocess owned by the verifier.""" + seed, shift = job + cmd = [ + PYTHON, str(TESTS / "solve_run.py"), + "--seed", str(seed), "--shift", str(shift), + "--submission", str(SUBMISSION), + "--host-pkg-root", HOST_PKG_ROOT, + "--python", PYTHON, + "--time-limit", str(SOLVE_TIMEOUT), + "--startup-timeout", str(STARTUP_TIMEOUT), + "--launch-prefix", ",".join(LAUNCH_PREFIX), + "--drop-to-uid", str(AGENT_UID), + ] + started = time.monotonic() + try: + proc = subprocess.run(cmd, capture_output=True, text=True, + timeout=RUN_HARD_TIMEOUT) + record = json.loads(proc.stdout.strip().splitlines()[-1]) + except Exception as exc: + record = { + "seed": int(seed), "shift": int(shift), + "nodes": grader_core.NODE_CAP, "raw_nodes": None, + "status": "driver_failed", "proved_optimal": False, + "decisions": 0, "solve_seconds": 0.0, + "error": f"{type(exc).__name__}: {exc}"[:200], + "extra_processes": 0, + } + record["wall"] = round(time.monotonic() - started, 2) + return record + + +def _grade(): + """Grade once per pytest session and cache the outcome.""" + global _RESULT + if _RESULT is not None: + return _RESULT + + METRIC_PATH.parent.mkdir(parents=True, exist_ok=True) + payload = { + "panel": PANEL, + "valid": False, + "metric": None, + "reward": 0.0, + "invalid_reason": None, + "runs": [], + "launcher": LAUNCH_PREFIX or f"in-process setuid({AGENT_UID})", + } + try: + seeds, shifts = grader_core.load_panel(PANEL_DIR) + ok, reason = _validate_submission() + if not ok: + payload["invalid_reason"] = reason + else: + subprocess.run(["chmod", "-R", "go+rX", str(SUBMISSION)], + check=False, timeout=120) + jobs = [(s, k) for s in seeds for k in shifts] + deadline = time.monotonic() + PANEL_TIMEOUT + records = {} + with ProcessPoolExecutor(max_workers=WORKERS) as pool: + futures = {pool.submit(_run_one, job): job for job in jobs} + for fut in as_completed(futures): + rec = fut.result() + records[(rec["seed"], rec["shift"])] = rec + if time.monotonic() > deadline: + for pending in futures: + pending.cancel() + break + for job in jobs: + if job not in records: + records[job] = { + "seed": job[0], "shift": job[1], + "nodes": grader_core.NODE_CAP, "raw_nodes": None, + "status": "panel_budget_exhausted", + "proved_optimal": False, "decisions": 0, + "solve_seconds": 0.0, "error": None, + "extra_processes": 0, "wall": 0.0, + } + runs = [records[job] for job in jobs] + nodes = [r["nodes"] for r in runs] + metric = grader_core.shifted_geomean(nodes) + payload.update({ + "valid": True, + "metric": round(metric, 4), + "reward": grader_core.reward_from_metric( + metric, m0=grader_core.m0_for(PANEL)), + "runs": runs, + "n_runs": len(runs), + "n_proved_optimal": sum(1 for r in runs if r["proved_optimal"]), + "n_charged_cap": sum(1 for r in runs + if not r["proved_optimal"]), + "node_min": min(nodes), + "node_max": max(nodes), + "m0": grader_core.m0_for(PANEL), + "baseline_score": grader_core.BASELINE_SCORE, + }) + except Exception as exc: + payload["invalid_reason"] = f"grader error: {type(exc).__name__}: {exc}" + payload["valid"] = False + payload["reward"] = 0.0 + METRIC_PATH.write_text(json.dumps(payload, indent=1)) + _RESULT = payload + return payload + + +def test_deliverable_contract(): + """The submission directory satisfies the contract stated in the task. + + An entry point that is missing, empty, oversized, or reaching outside the + submission directory through a symlink is scored 0 and nothing is executed. + """ + result = _grade() + assert result["invalid_reason"] is None, result["invalid_reason"] + + +def test_graded_panel(): + """Every run of the sealed panel executed and the metric was aggregated. + + The node count of a run is the solver's own count, taken in a process that + never loaded submission code; a run that fails to prove optimality inside + the caps is charged the node cap. + """ + result = _grade() + assert result["valid"], result["invalid_reason"] + assert result["n_runs"] == len(result["runs"]) + assert result["metric"] is not None and result["metric"] > 0 + print(f"panel={result['panel']} metric={result['metric']} " + f"charged_cap={result['n_charged_cap']}/{result['n_runs']}") + + +def test_reward_is_bounded(): + """The reward derived from the metric is finite and inside [0, 1].""" + result = _grade() + assert 0.0 <= float(result["reward"]) <= 1.0 diff --git a/tasks/tgat-milp-branching-node-count/environment/docker-compose.yaml b/tasks/tgat-milp-branching-node-count/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..575a78207b7a13b297e9ad88ac0bf70226ef5445 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/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/submission + + 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/submission" + ARE_AGENT_UID: "1001" + ARE_GRADE_TIMEOUT_SEC: "2700" + volumes: + - are-deliverable-0:/run/are-deliverable/app/submission + - 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/submission" + 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/tgat-milp-branching-node-count/task.toml b/tasks/tgat-milp-branching-node-count/task.toml index e214fc7f877d5c0e6b55c4d0638bae3ce28889fd..52e6193928ceadc45b12cbfca3f5e53a23b4c9ff 100644 --- a/tasks/tgat-milp-branching-node-count/task.toml +++ b/tasks/tgat-milp-branching-node-count/task.toml @@ -1,56 +1,71 @@ schema_version = "1.4" -artifacts = [ "/app/submission",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/tgat-milp-branching-node-count" -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 = "Reinforcement Learning" -task_objective = [ "Implement", "Optimize",] -artifact_type = [ "Single script or program", "Generated output artifact",] +task_objective = [ + "Implement", + "Optimize", +] +artifact_type = [ + "Single script or program", + "Generated output artifact", +] expert_time_estimate_hours = 6.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 = 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 = 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/tgat-milp-branching-node-count/tests/Dockerfile b/tasks/tgat-milp-branching-node-count/tests/Dockerfile index 12dd31a81502a2bf7d7b3a504e57e28ac9a061f1..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/tgat-milp-branching-node-count/tests/Dockerfile +++ b/tasks/tgat-milp-branching-node-count/tests/Dockerfile @@ -1,37 +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/submission /logs/verifier - -COPY ./bnbenv /opt/bnbenv - -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 {} + \ - && chmod 0700 /usr/local/lib/python3.13/site-packages/pyscipopt - -WORKDIR /tests - -ENV HF_HUB_OFFLINE=1 -ENV TRANSFORMERS_OFFLINE=1 +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/tgat-milp-branching-node-count/tests/finalize.py b/tasks/tgat-milp-branching-node-count/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/tgat-milp-branching-node-count/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/tgat-milp-branching-node-count/tests/test.sh b/tasks/tgat-milp-branching-node-count/tests/test.sh index a592fd0f679078052c765b37ab7bc84f28a8cb7b..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/tgat-milp-branching-node-count/tests/test.sh +++ b/tasks/tgat-milp-branching-node-count/tests/test.sh @@ -1,18 +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 - -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 +python3 /tests/finalize.py diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/.dockerignore b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/Dockerfile b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..575b7103a0920970d780baf999455a063a1fc122 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,45 @@ +FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV PYTHONHASHSEED=0 +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PIP_NO_CACHE_DIR=1 +ENV PIP_DISABLE_PIP_VERSION_CHECK=1 +ENV OMP_NUM_THREADS=1 +ENV MKL_NUM_THREADS=1 +ENV OPENBLAS_NUM_THREADS=1 +ENV NUMEXPR_NUM_THREADS=1 +ENV CUBLAS_WORKSPACE_CONFIG=:4096:8 +ENV TQDM_DISABLE=1 +ENV TOKENIZERS_PARALLELISM=false + +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 mkdir -p /app/output /logs/verifier + +COPY ./build_assets.py /opt/build_assets.py +RUN /usr/bin/python3 /opt/build_assets.py --role verifier --assets /opt/assets \ + --eval-out /opt/eval --label-out /tests/hidden_data --dataset-cache /tmp/ds_cache \ + --panel-seed 20240817 --stride 1 \ + && rm -rf /tmp/ds_cache /opt/assets/pretrained/.cache /opt/assets/sun397/.cache \ + && rm -rf /opt/assets/cars/.cache /opt/assets/resisc45/.cache /opt/assets/eurosat/.cache \ + && rm -rf /opt/assets/svhn/.cache /opt/assets/gtsrb/.cache /opt/assets/mnist/.cache \ + && rm -rf /opt/assets/dtd/.cache + +COPY . /tests + +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/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/Dockerfile.are b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..56451ab1308b1be923f17ac74e973a295555e2fa --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,63 @@ +FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 + +ENTRYPOINT [] +ENV PYTHONPATH= +ENV PYTHONSAFEPATH=1 +ENV PYTHONHASHSEED=0 +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PIP_NO_CACHE_DIR=1 +ENV PIP_DISABLE_PIP_VERSION_CHECK=1 +ENV OMP_NUM_THREADS=1 +ENV MKL_NUM_THREADS=1 +ENV OPENBLAS_NUM_THREADS=1 +ENV NUMEXPR_NUM_THREADS=1 +ENV CUBLAS_WORKSPACE_CONFIG=:4096:8 +ENV TQDM_DISABLE=1 +ENV TOKENIZERS_PARALLELISM=false + +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 mkdir -p /app/output /logs/verifier + +COPY ./build_assets.py /opt/build_assets.py +RUN /usr/bin/python3 /opt/build_assets.py --role verifier --assets /opt/assets \ + --eval-out /opt/eval --label-out /tests/hidden_data --dataset-cache /tmp/ds_cache \ + --panel-seed 20240817 --stride 1 \ + && rm -rf /tmp/ds_cache /opt/assets/pretrained/.cache /opt/assets/sun397/.cache \ + && rm -rf /opt/assets/cars/.cache /opt/assets/resisc45/.cache /opt/assets/eurosat/.cache \ + && rm -rf /opt/assets/svhn/.cache /opt/assets/gtsrb/.cache /opt/assets/mnist/.cache \ + && rm -rf /opt/assets/dtd/.cache + +COPY . /tests + +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 /opt/eval/final; fi +ENV ARE_ROLE=$ARE_ROLE +CMD ["/opt/are/venv/bin/python", "/opt/are/server.py"] diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/are/drain.py b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/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/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/are/server.py b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/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/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/build_assets.py b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/build_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..821d5f844cd9882dffe9da2a2bfc329f84c0460b --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/build_assets.py @@ -0,0 +1,347 @@ +from __future__ import annotations + +import argparse +import glob +import hashlib +import io +import json +import multiprocessing as mp +import os +import time +from pathlib import Path + +os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") +os.environ.setdefault("HF_DATASETS_DISABLE_PROGRESS_BARS", "1") + +import numpy as np + + +MODELS = { + "pretrained": ("openai/clip-vit-large-patch14", "32bd64288804d66eefd0ccbe215aa642df71cc41"), + "sun397": ("tanganke/clip-vit-large-patch14_sun397", "3b814ef1bd89d1f4044018d41a09bf468a5e4d34"), + "cars": ("tanganke/clip-vit-large-patch14_stanford-cars", "e863c1cb4999e1f630868d349de346db775e8242"), + "resisc45": ("tanganke/clip-vit-large-patch14_resisc45", "18076dfd48e5a590057ded82835288bfa3f27ff9"), + "eurosat": ("tanganke/clip-vit-large-patch14_eurosat", "61f5f8b50e9804c9f2b6482fd421d44fba7ffb66"), + "svhn": ("tanganke/clip-vit-large-patch14_svhn", "c43d85753b6aecd2435acca76bcc8aae8f8061b2"), + "gtsrb": ("tanganke/clip-vit-large-patch14_gtsrb", "6eacfe7af7432984b5352a676735d00e5a1ae9c4"), + "mnist": ("tanganke/clip-vit-large-patch14_mnist", "721ec5961afb977071c4124d43cf7f5fa4ba76af"), + "dtd": ("tanganke/clip-vit-large-patch14_dtd", "c55d192f53fe864a1955168593b7f03ab474daa4"), +} + +DATASETS = { + "sun397": ("tanganke/sun397", "9c4afd6174afa3974f209a0ef099dbbe244dfd27", "data/test-*.parquet"), + "cars": ("tanganke/stanford_cars", "9abf6cf7d6dfa7b95152a0d6e791ea9435b47a40", "data/test-*.parquet"), + "resisc45": ("tanganke/resisc45", "5c484982a196dcb501b8e79c6cf4680dc6f2ccdf", "data/test-*.parquet"), + "eurosat": ("tanganke/eurosat", "43750fc422c7fbd4289e2df3f7473617a5937acc", "data/test-*.parquet"), + "svhn": ("ufldl-stanford/svhn", "f9e1717d73324ebbc1ece84267ccd80d0aca0690", "cropped_digits/test-*.parquet"), + "gtsrb": ("tanganke/gtsrb", "ea889fff70dda7b09e94a4b207dded438deca549", "data/test-*.parquet"), + "mnist": ("ylecun/mnist", "77f3279092a1c1579b2250db8eafed0ad422088c", "mnist/test-*.parquet"), + "dtd": ("tanganke/dtd", "d2afa97d9f335b1a6b3b09c637aef667f98f966e", "data/test-*.parquet"), +} + +TASKS = ["sun397", "cars", "resisc45", "eurosat", "svhn", "gtsrb", "mnist", "dtd"] + +TEMPLATES = { + "sun397": ["a photo of a {}.", "a photo of the {}."], + "cars": [ + "a photo of a {}.", "a photo of the {}.", "a photo of my {}.", "i love my {}!", + "a photo of my dirty {}.", "a photo of my clean {}.", "a photo of my new {}.", + "a photo of my old {}.", + ], + "resisc45": [ + "satellite imagery of {}.", "aerial imagery of {}.", "satellite photo of {}.", + "aerial photo of {}.", "satellite view of {}.", "aerial view of {}.", + "satellite imagery of a {}.", "aerial imagery of a {}.", "satellite photo of a {}.", + "aerial photo of a {}.", "satellite view of a {}.", "aerial view of a {}.", + "satellite imagery of the {}.", "aerial imagery of the {}.", "satellite photo of the {}.", + "aerial photo of the {}.", "satellite view of the {}.", "aerial view of the {}.", + ], + "eurosat": [ + "a centered satellite photo of {}.", "a centered satellite photo of a {}.", + "a centered satellite photo of the {}.", + ], + "svhn": ['a photo of the number: "{}".'], + "gtsrb": [ + 'a zoomed in photo of a "{}" traffic sign.', + 'a centered photo of a "{}" traffic sign.', + 'a close up photo of a "{}" traffic sign.', + ], + "mnist": ['a photo of the number: "{}".'], + "dtd": [ + "a photo of a {} texture.", "a photo of a {} pattern.", "a photo of a {} thing.", + "a photo of a {} object.", "a photo of the {} texture.", "a photo of the {} pattern.", + "a photo of the {} thing.", "a photo of the {} object.", + ], +} + +IMAGE_SIDE = 224 +CHUNK = 512 +NEAR_DUP_AUDIT_BITS = 6 +_POPCOUNT = np.array([bin(i).count("1") for i in range(256)], dtype=np.uint8) + +_PROC = None + + +def _clean(name: str) -> str: + return str(name).replace("_", " ").replace("/", " ").strip() + + + + +def _init_worker(pretrained_dir: str) -> None: + global _PROC + from transformers import CLIPImageProcessor + + _PROC = CLIPImageProcessor.from_pretrained(pretrained_dir) + + +def _decode_one(raw: bytes) -> np.ndarray: + """bytes -> uint8 [3, 224, 224] via the pinned CLIPImageProcessor resize + center crop.""" + from PIL import Image + + with Image.open(io.BytesIO(raw)) as im: + im = im.convert("RGB") + out = _PROC(images=im, do_rescale=False, do_normalize=False, + return_tensors="np")["pixel_values"][0] + arr = np.asarray(out) + if arr.shape[0] != 3: + arr = np.transpose(arr, (2, 0, 1)) + assert arr.shape == (3, IMAGE_SIDE, IMAGE_SIDE), arr.shape + return np.rint(arr).clip(0, 255).astype(np.uint8) + + +def dhash(arr: np.ndarray) -> np.ndarray: + """480-bit difference hash of one uint8 [3, 224, 224] image, packed into 60 bytes. + + A 16x16 grid of block means, then the horizontal and vertical comparisons between adjacent + cells. Far more discriminative than an 8x8 average hash, which is why the audit below can + report a meaningful distance instead of a coin flip. + """ + grey = arr.astype(np.float32).mean(axis=0) + grid = grey.reshape(16, IMAGE_SIDE // 16, 16, IMAGE_SIDE // 16).mean(axis=(1, 3)) + bits = np.concatenate([(grid[:, 1:] > grid[:, :-1]).ravel(), + (grid[1:, :] > grid[:-1, :]).ravel()]) + return np.packbits(bits) + + +def min_hamming(sealed: np.ndarray, dev: np.ndarray) -> np.ndarray: + """For every sealed hash row, the minimum Hamming distance to any dev hash row.""" + out = np.full(len(sealed), 480, dtype=np.int32) + if len(dev) == 0 or len(sealed) == 0: + return out + for start in range(0, len(sealed), 128): + blk = sealed[start:start + 128] + x = np.bitwise_xor(blk[:, None, :], dev[None, :, :]) + out[start:start + 128] = _POPCOUNT[x].sum(axis=2).min(axis=1) + return out + + +def content_key(arr: np.ndarray) -> bytes: + """SHA-256 of the decoded pixels: an exact duplicate and nothing looser.""" + return hashlib.sha256(np.ascontiguousarray(arr).tobytes()).digest() + + + + +def build_heads(assets: Path) -> None: + import torch + from transformers import CLIPModel, CLIPTokenizerFast + + torch.manual_seed(0) + pre = assets / "pretrained" + model = CLIPModel.from_pretrained(str(pre), dtype=torch.float32).eval() + tok = CLIPTokenizerFast.from_pretrained(str(pre)) + + heads = {} + with torch.no_grad(): + for task in TASKS: + names = json.loads((assets / "classes" / f"{task}.json").read_text()) + rows = [] + for name in names: + prompts = [t.format(_clean(name)) for t in TEMPLATES[task]] + batch = tok(prompts, padding=True, return_tensors="pt") + out = model.get_text_features(**batch) + emb = (out if isinstance(out, torch.Tensor) else out.pooler_output).float() + emb = emb / emb.norm(dim=-1, keepdim=True) + emb = emb.mean(dim=0) + rows.append(emb / emb.norm()) + head = torch.stack(rows).contiguous().float() + assert head.shape == (len(names), 768), (task, head.shape) + heads[task] = head + print(f"head {task}: {tuple(head.shape)}", flush=True) + proj = model.visual_projection.weight.detach().clone().float() + assert proj.shape == (768, 1024), proj.shape + torch.save({"heads": heads, "visual_projection": proj}, assets / "heads.pt") + print("heads.pt written", flush=True) + + + + +def panel_indices(n_rows: int, stride: int) -> dict[str, np.ndarray]: + idx = np.arange(n_rows) + out = {"dev": idx[idx % 2 == 0], + "intermediate": idx[idx % 4 == 1], + "final": idx[idx % 4 == 3]} + if stride > 1: + out = {k: v[::stride] for k, v in out.items()} + return out + + +def _fetch_split(task: str, cache: Path): + from huggingface_hub import snapshot_download + import datasets as hfds + + repo, rev, pattern = DATASETS[task] + root = snapshot_download(repo_id=repo, repo_type="dataset", revision=rev, + local_dir=str(cache / task), allow_patterns=[pattern]) + files = sorted(glob.glob(os.path.join(root, pattern))) + if not files: + raise RuntimeError(f"{task}: no parquet matched {pattern} at {rev}") + return hfds.load_dataset("parquet", data_files={"test": files}, split="test") + + +def materialize(args: argparse.Namespace) -> None: + import datasets as hfds + + assets = Path(args.assets) + (assets / "classes").mkdir(parents=True, exist_ok=True) + cache = Path(args.dataset_cache) + verifier = args.role == "verifier" + + for task in TASKS: + t0 = time.time() + ds = _fetch_split(task, cache) + image_col = "image" if "image" in ds.column_names else ds.column_names[0] + label_col = "label" if "label" in ds.column_names else ds.column_names[-1] + names = [_clean(x) for x in ds.features[label_col].names] + (assets / "classes" / f"{task}.json").write_text(json.dumps(names, indent=1)) + + labels_all = np.asarray(ds[label_col], dtype=np.int64) + n_rows = len(labels_all) + panels = panel_indices(n_rows, args.stride) + assert not (set(panels["dev"]) & set(panels["intermediate"])) + assert not (set(panels["dev"]) & set(panels["final"])) + assert not (set(panels["intermediate"]) & set(panels["final"])) + raw = ds.cast_column(image_col, hfds.Image(decode=False)) + + need = sorted(set(panels["dev"]).union(panels["intermediate"], panels["final"])) \ + if verifier else sorted(panels["dev"]) + hashes: dict[int, np.ndarray] = {} + keys: dict[int, bytes] = {} + arrays: dict[int, np.ndarray] = {} + store = set(panels["dev"]) if not verifier else \ + set(panels["intermediate"]) | set(panels["final"]) + with mp.Pool(args.workers, initializer=_init_worker, + initargs=(str(assets / "pretrained"),)) as pool: + for start in range(0, len(need), CHUNK): + rows = need[start:start + CHUNK] + blobs = [b["bytes"] for b in raw[rows][image_col]] + for row, arr in zip(rows, pool.map(_decode_one, blobs, chunksize=8)): + if verifier: + hashes[row] = dhash(arr) + keys[row] = content_key(arr) + if row in store: + arrays[row] = arr + + keep, audit = {}, {} + wanted = ["intermediate", "final"] if verifier else ["dev"] + dev_h = np.stack([hashes[int(r)] for r in panels["dev"]]) if verifier else None + dev_keys = {keys[int(r)] for r in panels["dev"]} if verifier else set() + for panel in wanted: + sel = np.asarray(panels[panel], dtype=np.int64) + dropped, remaining, achieved, near = 0, 0, 480, 0 + if verifier: + mask = np.array([keys[int(r)] not in dev_keys for r in sel], dtype=bool) + dropped = int((~mask).sum()) + sel = sel[mask] + remaining = int(sum(1 for r in sel if keys[int(r)] in dev_keys)) + d = min_hamming(np.stack([hashes[int(r)] for r in sel]), dev_h) \ + if len(sel) else np.zeros(0, dtype=np.int32) + achieved = int(d.min()) if len(sel) else 480 + near = int((d <= NEAR_DUP_AUDIT_BITS).sum()) + rng = np.random.default_rng(args.panel_seed + TASKS.index(task)) + rng.shuffle(sel) + keep[panel] = sel + audit[panel] = {"task": task, "split_rows": int(n_rows), + "panel_rows_before_dedup": int(len(panels[panel])), + "panel_rows": int(len(sel)), + "dropped_exact_duplicates_of_dev": dropped, + "exact_duplicates_remaining": remaining, + "min_dhash_bits_to_dev": achieved, + "sealed_rows_within_audit_bits_of_dev": near, + "near_dup_audit_bits": NEAR_DUP_AUDIT_BITS, + "num_classes": len(names), "stride": args.stride} + + for panel, sel in keep.items(): + if panel == "dev": + d = Path(args.out) / "data" / "dev" / task + ld = d + else: + d = Path(args.eval_out) / panel / task + ld = Path(args.label_out) / panel / task + d.mkdir(parents=True, exist_ok=True) + ld.mkdir(parents=True, exist_ok=True) + mm = np.lib.format.open_memmap( + d / "images.npy", mode="w+", dtype=np.uint8, + shape=(len(sel), 3, IMAGE_SIDE, IMAGE_SIDE)) + for pos, row in enumerate(sel): + mm[pos] = arrays[int(row)] + mm.flush() + del mm + np.save(ld / "labels.npy", labels_all[sel]) + (ld / "classes.json").write_text(json.dumps(names, indent=1)) + (ld / "split_audit.json").write_text(json.dumps(audit[panel], indent=1)) + if panel == "dev": + view = Path(args.out) / "data" / "dev_unlabeled" / task + view.mkdir(parents=True, exist_ok=True) + link = view / "images.npy" + if not link.is_symlink(): + os.symlink(os.path.relpath(d / "images.npy", view), link) + print(f"{task}/{panel}: {audit[panel]}", flush=True) + arrays.clear() + hashes.clear() + print(f"{task}: {n_rows} rows in {time.time() - t0:.1f}s", flush=True) + + + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--role", choices=["agent", "verifier"], required=True) + ap.add_argument("--assets", default="/opt/assets") + ap.add_argument("--out", default="/app") + ap.add_argument("--eval-out", default="/opt/eval") + ap.add_argument("--label-out", default="/tests/hidden_data") + ap.add_argument("--dataset-cache", default="/tmp/ds_cache") + ap.add_argument("--panel-seed", type=int, default=0) + ap.add_argument("--stride", type=int, default=1) + ap.add_argument("--workers", type=int, default=max(2, (os.cpu_count() or 4) - 2)) + ap.add_argument("--skip-models", action="store_true") + ap.add_argument("--skip-data", action="store_true") + args = ap.parse_args() + if args.role == "verifier" and args.panel_seed == 0: + raise SystemExit("--panel-seed must be set for the verifier role") + + assets = Path(args.assets) + assets.mkdir(parents=True, exist_ok=True) + if not args.skip_models: + from huggingface_hub import snapshot_download + + for name, (repo, rev) in MODELS.items(): + allow = ["config.json", "model.safetensors"] + if name == "pretrained": + allow += ["tokenizer.json", "tokenizer_config.json", "vocab.json", + "merges.txt", "special_tokens_map.json", "preprocessor_config.json"] + t0 = time.time() + snapshot_download(repo_id=repo, revision=rev, local_dir=str(assets / name), + allow_patterns=allow) + print(f"fetched {name} in {time.time() - t0:.1f}s", flush=True) + + if not args.skip_data: + materialize(args) + build_heads(assets) + print("BUILD_ASSETS_DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/compute_reward.py b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..e4edea0b5744a2fd889d920d5c1ac5596e988870 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/compute_reward.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +import json +import math +import os +import sys +from pathlib import Path + +METRIC_PATH = Path("/logs/verifier/metric.json") +REWARD_PATH = Path("/logs/verifier/reward.txt") + + +def clamp(value: object) -> float: + """Any object -> a finite float in [0, 1]. Never raises, never returns NaN, inf or -0.0.""" + try: + if isinstance(value, bool) or not isinstance(value, (int, float, str)): + return 0.0 + x = float(value) + except BaseException: + return 0.0 + if not math.isfinite(x): + return 0.0 + if not x > 0.0: + return 0.0 + return 1.0 if x > 1.0 else x + + +def render(x: float) -> str: + """A clamped float -> its decimal text, re-parsed to prove the bound survived formatting.""" + try: + text = f"{x:.12g}" + back = float(text) + except BaseException: + return "0" + if not math.isfinite(back) or back < 0.0 or back > 1.0: + return "0" + return text + + +def emit(text: str) -> None: + """Replace reward.txt atomically, so no reader ever sees a partial or stale token.""" + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + tmp = REWARD_PATH.with_name(REWARD_PATH.name + ".tmp") + with open(tmp, "w") as fh: + fh.write(text + "\n") + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, REWARD_PATH) + + +def emit_zero_hard() -> None: + """Last resort when the atomic write failed: clear whatever occupies the path, write 0.""" + try: + REWARD_PATH.parent.mkdir(parents=True, exist_ok=True) + except BaseException: + pass + try: + if REWARD_PATH.is_dir(): + os.rmdir(REWARD_PATH) + elif REWARD_PATH.exists(): + os.unlink(REWARD_PATH) + except BaseException: + pass + REWARD_PATH.write_text("0\n") + + +def main() -> None: + note = "" + try: + payload = json.loads(METRIC_PATH.read_text()) + text = render(clamp(payload["reward"] if isinstance(payload, dict) else None)) + except BaseException as exc: + text, note = "0", f" (fallback: {exc})" + try: + emit(text) + print(f"reward={text}{note}") + except BaseException as exc: + try: + emit_zero_hard() + print(f"reward=0 (fallback: {exc})") + except BaseException: + pass + + +def selftest() -> None: + """Every adversarial input the contract names, checked at the clamp and at the text.""" + huge = 1e308 + cases = [ + float("nan"), float("inf"), float("-inf"), -huge * huge, huge / 1e-308, + -0.0, -1.0, -1e-300, 2.0, 1e309, 10 ** 400, "nan", "-inf", "-1", "1e400", "", + "0.5", 0.5, 1.0, 0.0, None, True, False, [], {}, object(), + ] + for case in cases: + c = clamp(case) + assert isinstance(c, float) and math.isfinite(c) and 0.0 <= c <= 1.0, (case, c) + assert math.copysign(1.0, c) > 0.0, (case, "negative zero") + t = render(c) + assert 0.0 <= float(t) <= 1.0 and not t.startswith("-"), (case, t) + assert render(clamp(0.0)) == "0" and render(clamp(float("nan"))) == "0" + assert render(clamp(2.0)) == "1" and render(clamp(0.5)) == "0.5" + print(f"selftest ok: {len(cases)} inputs clamped into [0, 1]") + + +if __name__ == "__main__": + if "--selftest" in sys.argv[1:]: + selftest() + else: + main() diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/grader_core.py b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..949a84cc4673b28acb5b1d8bcce2b55dcc8bde64 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +import json +import math +import os +from pathlib import Path + +import numpy as np + +TASKS = ("sun397", "cars", "resisc45", "eurosat", "svhn", "gtsrb", "mnist", "dtd") + +ASSETS = Path("/opt/assets") +EVAL_ROOT = Path("/opt/eval") +HIDDEN_ROOT = Path("/tests/hidden_data") + +IMAGE_SIDE = 224 +EVAL_BATCH = 256 +SEED = 0 + +MERGE_BUDGET_SEC = 1200.0 +OVERHEAD_ALLOWANCE_SEC = 600.0 + +CLIP_MEAN = (0.48145466, 0.4578275, 0.40821073) +CLIP_STD = (0.26862954, 0.26130258, 0.27577711) + +DEGENERATE_REWARD = 0.10 +M_FLOOR = 65.23 +M0 = 80.05 +BASELINE_SCORE = 86.00 +HIGHER_IS_BETTER = True + + +def graded_reward(metric: float | None, valid: bool) -> float: + """metric -> reward in [0, 1]. The invalid path short-circuits before any arithmetic.""" + if not valid or metric is None or not math.isfinite(float(metric)): + return 0.0 + m = float(metric) + sigma = 1.0 if HIGHER_IS_BETTER else -1.0 + x = sigma * (m - M0) + x_ref = sigma * (BASELINE_SCORE - M0) + assert x_ref > 0, "malformed task: the baseline score does not beat the trivial baseline" + c = DEGENERATE_REWARD + g = sigma * (M0 - M_FLOOR) + if c <= 0.0 or g <= 0: + u = max(0.0, x) / x_ref + return u / (1.0 + u) + if x < 0: + v = max(0.0, sigma * (m - M_FLOOR)) / g + return c * v + u = x / x_ref + return c + (1.0 - c) * (u / (1.0 + u)) + + + + +def determinism_env() -> dict[str, str]: + """The pins handed to every process that runs torch, root grader and candidate alike.""" + return { + "PYTHONHASHSEED": "0", + "PYTHONDONTWRITEBYTECODE": "1", + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", + "CUBLAS_WORKSPACE_CONFIG": ":4096:8", + "TQDM_DISABLE": "1", + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + "HF_HUB_DISABLE_PROGRESS_BARS": "1", + "TOKENIZERS_PARALLELISM": "false", + } + + +def pin_determinism() -> None: + import random + + import torch + + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + random.seed(SEED) + np.random.seed(SEED) + torch.manual_seed(SEED) + torch.cuda.manual_seed_all(SEED) + torch.set_num_threads(1) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + torch.backends.cudnn.allow_tf32 = False + torch.backends.cuda.matmul.allow_tf32 = False + torch.use_deterministic_algorithms(True) + + + + +def vision_config(): + from transformers import CLIPVisionConfig + + return CLIPVisionConfig.from_pretrained(str(ASSETS / "pretrained")) + + +def canonical_keys() -> set[str]: + """The 391 keys CLIPVisionModel itself owns. The pretrained checkpoint carries one extra + buffer (`vision_model.embeddings.position_ids`) that this transformers version dropped, so + the key set comes from the module and never from the file.""" + import torch + from transformers import CLIPVisionModel + + with torch.device("meta"): + return set(CLIPVisionModel(vision_config()).state_dict()) + + +def reference_state_dict() -> dict: + """The pretrained CLIPVisionModel state dict -- the key set and shapes a merge must return.""" + from safetensors.torch import load_file + + raw = load_file(str(ASSETS / "pretrained" / "model.safetensors")) + keys = canonical_keys() + out = {k: v.float() for k, v in raw.items() if k in keys} + assert set(out) == keys, f"pretrained checkpoint is missing {sorted(keys - set(out))[:3]}" + return out + + +def eval_assets(device: str): + """The frozen heads and visual projection. Public, and identical in both images.""" + import torch + + blob = torch.load(str(ASSETS / "heads.pt"), map_location="cpu", weights_only=True) + heads = {t: blob["heads"][t].to(device=device, dtype=torch.float32) for t in TASKS} + proj = blob["visual_projection"].to(device=device, dtype=torch.float32) + assert proj.shape == (768, 1024), proj.shape + for t, h in heads.items(): + assert h.ndim == 2 and h.shape[1] == 768, (t, tuple(h.shape)) + norms = h.norm(dim=-1) + assert bool(((norms - 1.0).abs() < 1e-3).all()), f"{t}: head rows are not unit norm" + return heads, proj + + + +VALIDATION_FAILURES = ( + "missing_key", "unexpected_key", "shape_mismatch", "non_finite", "not_castable", +) + + +def validate_state_dict(candidate: dict, reference: dict) -> str | None: + """None when the returned state dict is gradeable, else a short machine-readable reason.""" + import torch + + if not isinstance(candidate, dict): + return "not_a_dict" + cand_keys, ref_keys = set(candidate), set(reference) + if ref_keys - cand_keys: + return f"missing_key:{sorted(ref_keys - cand_keys)[0]}" + if cand_keys - ref_keys: + return f"unexpected_key:{sorted(cand_keys - ref_keys)[0]}" + for k in sorted(ref_keys): + v = candidate[k] + if not torch.is_tensor(v): + return f"not_castable:{k}" + if tuple(v.shape) != tuple(reference[k].shape): + return f"shape_mismatch:{k}" + try: + f = v.detach().to(dtype=torch.float32) + except Exception: + return f"not_castable:{k}" + if not bool(torch.isfinite(f).all()): + return f"non_finite:{k}" + return None + + + + +def panel_dirs(panel: str) -> tuple[Path, Path]: + return EVAL_ROOT / panel, HIDDEN_ROOT / panel + + +def audit_panel(panel: str) -> dict: + """Fail-closed split audit: every task present, and no sealed row duplicates a dev row.""" + _, labels_root = panel_dirs(panel) + out = {} + for task in TASKS: + info = json.loads((labels_root / task / "split_audit.json").read_text()) + assert info["task"] == task + assert info["panel_rows"] > 0, f"{panel}/{task}: empty panel" + assert info["exact_duplicates_remaining"] == 0, ( + f"{panel}/{task}: a sealed row is a pixel-exact duplicate of a dev row") + assert info["panel_rows"] + info["dropped_exact_duplicates_of_dev"] == \ + info["panel_rows_before_dedup"], f"{panel}/{task}: audit row counts disagree" + out[task] = info + return out + + +def evaluate(state_dict: dict, panel: str, device: str = "cuda", + batch: int = EVAL_BATCH) -> dict: + """Per-task top-1 accuracy (percent) and their unweighted mean, on one sealed panel.""" + import torch + + images_root, labels_root = panel_dirs(panel) + heads, proj = eval_assets(device) + + from transformers import CLIPVisionModel + + model = CLIPVisionModel(vision_config()) + model.load_state_dict({k: v.detach().to(dtype=torch.float32) for k, v in state_dict.items()}, + strict=True) + model = model.to(device=device, dtype=torch.float32).eval() + + mean = torch.tensor(CLIP_MEAN, dtype=torch.float32, device=device).view(1, 3, 1, 1) + std = torch.tensor(CLIP_STD, dtype=torch.float32, device=device).view(1, 3, 1, 1) + + per_task, counts = {}, {} + with torch.inference_mode(): + for task in TASKS: + imgs = np.load(images_root / task / "images.npy", mmap_mode="r") + labels = np.load(labels_root / task / "labels.npy") + assert imgs.shape[0] == labels.shape[0], task + assert imgs.shape[1:] == (3, IMAGE_SIDE, IMAGE_SIDE), (task, imgs.shape) + head = heads[task] + assert int(labels.max()) < head.shape[0], (task, int(labels.max()), head.shape) + correct = 0 + for start in range(0, imgs.shape[0], batch): + chunk = np.ascontiguousarray(imgs[start:start + batch]) + x = torch.from_numpy(chunk).to(device=device, non_blocking=False) + x = x.to(dtype=torch.float32).div_(255.0).sub_(mean).div_(std) + pooled = model(pixel_values=x).pooler_output + emb = pooled @ proj.t() + emb = emb / emb.norm(dim=-1, keepdim=True) + pred = (emb @ head.t()).argmax(dim=-1).cpu().numpy() + correct += int((pred == labels[start:start + batch]).sum()) + per_task[task] = 100.0 * correct / int(imgs.shape[0]) + counts[task] = int(imgs.shape[0]) + metric = sum(per_task[t] for t in TASKS) / len(TASKS) + return {"per_task_accuracy": per_task, "panel_rows": counts, "metric": metric} diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/hidden_data/README.md b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/hidden_data/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0b347c03aa833da52c969ecb31be112f150c3ca0 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/hidden_data/README.md @@ -0,0 +1,12 @@ +# hidden_data — sealed, 0700 root + +Empty in the build context on purpose. `tests/Dockerfile` runs `build_assets.py --role verifier` +above `COPY . /tests`, which materializes + + hidden_data///labels.npy int64 class ids, row-aligned with the panel images + hidden_data///classes.json the dataset's ClassLabel names, head row order + hidden_data///split_audit.json row counts and the dedup audit asserted at grade time + +for `panel` in {intermediate, final} and the eight tasks. The panels' IMAGES live outside this +tree, under /opt/eval, because merge() is handed them unlabeled; only the labels are sealed. +A later layer chmods this directory to 0700 root, so the uid-1001 candidate cannot read it. diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/intermediate.sh b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..6798c4ab08bec990b083e427b69e379aaa977e8a --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,31 @@ +#!/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 + +chmod -R go-rwx /tests + +export PDK_PANEL=intermediate +export CUBLAS_WORKSPACE_CONFIG=:4096:8 +export PYTHONHASHSEED=0 +export PYTHONDONTWRITEBYTECODE=1 +export OMP_NUM_THREADS=1 +export MKL_NUM_THREADS=1 +export OPENBLAS_NUM_THREADS=1 +export NUMEXPR_NUM_THREADS=1 +export TQDM_DISABLE=1 +export TOKENIZERS_PARALLELISM=false + +cd /tests +PYTEST_CAP=6600 +if command -v timeout >/dev/null 2>&1; then + timeout -k 30 "$PYTEST_CAP" /usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +else + /usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +fi +/usr/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/requirements-verifier.txt b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..8e349698b9284c50f63044df493a8efd9ce72e70 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/requirements-verifier.txt @@ -0,0 +1,2 @@ +pytest==8.4.2 +pytest-json-ctrf==0.3.5 diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/run_merge.py b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/run_merge.py new file mode 100644 index 0000000000000000000000000000000000000000..f7981f8dbfab8b1b97fd44b4ca0eff2c9f0baa98 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/run_merge.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +import argparse +import json +import os +import random +import signal +import sys +import time +import traceback +from pathlib import Path + +import numpy as np + +TASKS = ("sun397", "cars", "resisc45", "eurosat", "svhn", "gtsrb", "mnist", "dtd") + + +class MergeTimeout(Exception): + pass + + +def _alarm(signum, frame): + raise MergeTimeout("merge() exceeded its wall-clock budget") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--solution", required=True) + ap.add_argument("--unlabeled", required=True) + ap.add_argument("--assets", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--budget", type=float, required=True) + ap.add_argument("--device", default="cuda") + args = ap.parse_args() + + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + report = {"status": "error", "reason": "unset", "merge_seconds": None} + + def flush(code: int) -> int: + (out / "report.json").write_text(json.dumps(report, indent=1)) + return code + + import torch + + torch.set_num_threads(1) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + torch.backends.cudnn.allow_tf32 = False + torch.backends.cuda.matmul.allow_tf32 = False + random.seed(0) + np.random.seed(0) + torch.manual_seed(0) + + try: + report["cuda_device_count"] = int(torch.cuda.device_count()) + probe = (torch.ones(64, 64, device=args.device) @ torch.eye(64, device=args.device)).sum() + report["cuda_probe_sum"] = float(probe.item()) + except Exception as exc: + report["reason"] = f"cuda_unavailable_to_uid_{os.getuid()}: {exc!r}" + print(f"[runner] CUDA unavailable to uid {os.getuid()}: {exc!r}", file=sys.stderr) + return flush(3) + + from safetensors.torch import load_file, save_file + + entry = Path(args.solution) / "merge.py" + if not entry.is_file() or entry.stat().st_size == 0: + report["reason"] = "missing_or_empty_entry_point" + return flush(5) + + sys.path.insert(0, str(Path(args.solution).resolve())) + try: + import importlib.util + + spec = importlib.util.spec_from_file_location("candidate_merge", str(entry)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + except BaseException as exc: + report["reason"] = f"import_failed: {exc!r}" + traceback.print_exc() + return flush(6) + + fn = getattr(module, "merge", None) + if not callable(fn): + report["reason"] = "no_callable_merge" + return flush(7) + + assets = Path(args.assets) + try: + from transformers import CLIPVisionConfig, CLIPVisionModel + + cfg = CLIPVisionConfig.from_pretrained(str(assets / "pretrained")) + with torch.device("meta"): + canon = set(CLIPVisionModel(cfg).state_dict()) + pretrained = {k: v.float() for k, v in + load_file(str(assets / "pretrained" / "model.safetensors")).items() + if k in canon} + if set(pretrained) != canon: + report["reason"] = "asset_keyset_mismatch:pretrained" + return flush(4) + experts = {} + for task in TASKS: + experts[task] = {k: v.float() for k, v in + load_file(str(assets / task / "model.safetensors")).items()} + missing = set(pretrained) ^ set(experts[task]) + if missing: + report["reason"] = f"asset_keyset_mismatch:{task}" + return flush(4) + except Exception as exc: + report["reason"] = f"asset_load_failed: {exc!r}" + traceback.print_exc() + return flush(4) + + signal.signal(signal.SIGALRM, _alarm) + signal.setitimer(signal.ITIMER_REAL, args.budget) + t0 = time.monotonic() + try: + merged = fn(pretrained, experts, str(args.unlabeled), args.device) + except MergeTimeout: + report["reason"] = "merge_timeout" + report["merge_seconds"] = time.monotonic() - t0 + return flush(8) + except BaseException as exc: + report["reason"] = f"merge_raised: {exc!r}" + report["merge_seconds"] = time.monotonic() - t0 + traceback.print_exc() + return flush(9) + finally: + signal.setitimer(signal.ITIMER_REAL, 0.0) + report["merge_seconds"] = time.monotonic() - t0 + + if not isinstance(merged, dict): + report["reason"] = "return_not_a_dict" + return flush(10) + absent = sorted(set(pretrained) - set(merged)) + if absent: + report["reason"] = f"missing_key:{absent[0]}" + return flush(10) + extra = sorted(set(merged) - set(pretrained)) + if extra: + report["reason"] = f"unexpected_key:{extra[0]}" + return flush(10) + try: + tensors = {} + for k in sorted(pretrained): + v = merged[k] + t = v if torch.is_tensor(v) else torch.as_tensor(v) + tensors[k] = t.detach().to(device="cpu", dtype=torch.float32).contiguous().clone() + save_file(tensors, str(out / "merged.safetensors")) + except Exception as exc: + report["reason"] = f"return_unserializable: {exc!r}" + traceback.print_exc() + return flush(11) + + report["status"] = "ok" + report["reason"] = "ok" + report["returned_keys"] = len(tensors) + return flush(0) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/test.sh b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4fdd69632abd0667671530cc6895332f2dee9103 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/test.sh @@ -0,0 +1,31 @@ +#!/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 + +chmod -R go-rwx /tests + +export PDK_PANEL=final +export CUBLAS_WORKSPACE_CONFIG=:4096:8 +export PYTHONHASHSEED=0 +export PYTHONDONTWRITEBYTECODE=1 +export OMP_NUM_THREADS=1 +export MKL_NUM_THREADS=1 +export OPENBLAS_NUM_THREADS=1 +export NUMEXPR_NUM_THREADS=1 +export TQDM_DISABLE=1 +export TOKENIZERS_PARALLELISM=false + +cd /tests +PYTEST_CAP=6600 +if command -v timeout >/dev/null 2>&1; then + timeout -k 30 "$PYTEST_CAP" /usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +else + /usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA +fi +/usr/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/test_state.py b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed7d069778c7a0770076ece0578e81bdbc1774b --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/are-grader-ctx/test_state.py @@ -0,0 +1,400 @@ +from __future__ import annotations + +import json +import math +import os +import shutil +import signal +import stat +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import build_assets as ba +import grader_core as gc + +PANEL = os.environ.get("PDK_PANEL", "final") +LOGS = Path("/logs/verifier") +DELIVERABLE = Path("/app/output") +ENTRY_NAME = "merge.py" +STAGE_ROOT = Path("/tmp/pdk_candidate") +AGENT_UID = 1001 +AGENT_GID = 1001 +RUNNER_SRC = Path(__file__).resolve().parent / "run_merge.py" +REAP_GRACE_SEC = 60.0 + +_RESULT: dict | None = None + + + + +def _write_metric(payload: dict) -> None: + LOGS.mkdir(parents=True, exist_ok=True) + (LOGS / "metric.json").write_text(json.dumps(payload, indent=1)) + print("metric.json:", json.dumps({k: v for k, v in payload.items() + if k != "candidate_stderr"})) + + +def _invalid(reason: str, **extra) -> dict: + payload = {"panel": PANEL, "valid": False, "failure_reason": reason, + "metric": None, "per_task_accuracy": None, "reward": 0.0} + payload.update(extra) + _write_metric(payload) + return payload + + +def scan_submission(root: Path) -> str | None: + """Reject a submitted tree containing any symlink or any hard-linked file. + + A privileged copy that followed a submitted symlink would materialize verifier files into + the directory the score is computed from; harbor preserves symlinks across the artifact + hop, and a read-only bind mount does not remove hard links already present. + """ + if not root.exists(): + return "missing_deliverable_directory" + stack = [root] + seen = 0 + while stack: + d = stack.pop() + try: + entries = list(os.scandir(d)) + except OSError as exc: + return f"unreadable_directory:{exc.strerror}" + for e in entries: + st = os.lstat(e.path) + rel = os.path.relpath(e.path, root) + if stat.S_ISLNK(st.st_mode): + return f"symlink_in_submission:{rel}" + if stat.S_ISDIR(st.st_mode): + stack.append(Path(e.path)) + continue + if not stat.S_ISREG(st.st_mode): + return f"non_regular_file_in_submission:{rel}" + if st.st_nlink != 1: + return f"hard_link_in_submission:{rel}" + seen += 1 + if seen > 20000: + return "too_many_files_in_submission" + return None + + +def check_surface(root: Path) -> str | None: + """Enforce the file list instruction.md declares a solution may change. + + The deliverable directory is the whole of it, and its one required member is a non-empty + regular `merge.py` directly inside it -- not in a subdirectory, not a symlink to elsewhere. + Extra files and nested directories under the same root are permitted and travel with it; + nothing outside it is ever read, so nothing outside it needs rejecting. + """ + entry = root / ENTRY_NAME + try: + st = os.lstat(entry) + except OSError: + return f"missing_entry_point:{ENTRY_NAME}" + if not stat.S_ISREG(st.st_mode): + return f"entry_point_not_a_regular_file:{ENTRY_NAME}" + if st.st_size == 0: + return f"empty_entry_point:{ENTRY_NAME}" + return None + + +def stage(root: Path) -> tuple[Path, Path, Path]: + """Fresh, root-owned read-only copy of the submission plus writable scratch for uid 1001.""" + if STAGE_ROOT.exists(): + shutil.rmtree(STAGE_ROOT) + STAGE_ROOT.mkdir(parents=True) + os.chmod(STAGE_ROOT, 0o755) + solution = STAGE_ROOT / "solution" + shutil.copytree(root, solution, symlinks=True) + for p in [solution, *solution.rglob("*")]: + os.chmod(p, 0o555 if p.is_dir() else 0o444) + runner = STAGE_ROOT / "run_merge.py" + shutil.copyfile(RUNNER_SRC, runner) + os.chmod(runner, 0o444) + for name in ("out", "work"): + d = STAGE_ROOT / name + d.mkdir() + os.lchown(d, AGENT_UID, AGENT_GID) + os.chmod(d, 0o700) + return solution, runner, STAGE_ROOT + + +def candidate_env() -> dict[str, str]: + env = { + "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "HOME": "/home/agent", + "LANG": "C.UTF-8", + "PYTHONPATH": "", + "PYTHONSAFEPATH": "1", + } + env.update(gc.determinism_env()) + for k, v in os.environ.items(): + if k.startswith("NVIDIA_") or k in ("LD_LIBRARY_PATH", "CUDA_HOME", "CUDA_PATH"): + env[k] = v + return env + + + + +def grade() -> dict: + global _RESULT + if _RESULT is not None: + return _RESULT + try: + _RESULT = _grade() + except BaseException as exc: + import traceback + + traceback.print_exc() + _RESULT = _invalid(f"verifier_error:{exc!r}") + return _RESULT + + +def _grade() -> dict: + gc.pin_determinism() + + try: + audit = gc.audit_panel(PANEL) + except BaseException as exc: + return _invalid(f"verifier_split_audit_failed:{exc!r}") + + rejected = scan_submission(DELIVERABLE) + if rejected is not None: + return _invalid(rejected) + + off_surface = check_surface(DELIVERABLE) + if off_surface is not None: + return _invalid(off_surface) + + solution, runner, root = stage(DELIVERABLE) + argv = ["setsid", "runuser", "-u", "agent", "--", sys.executable, str(runner), + "--solution", str(solution), + "--unlabeled", str(gc.EVAL_ROOT / PANEL), + "--assets", str(gc.ASSETS), + "--out", str(root / "out"), + "--budget", repr(gc.MERGE_BUDGET_SEC), + "--device", "cuda"] + hard_cap = gc.MERGE_BUDGET_SEC + gc.OVERHEAD_ALLOWANCE_SEC + t0 = time.monotonic() + try: + proc = subprocess.Popen(argv, cwd=str(root / "work"), env=candidate_env(), + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, errors="replace", start_new_session=True) + except BaseException as exc: + return _invalid(f"candidate_launch_failed:{exc!r}", + verifier_cuda_devices=_root_device_count()) + try: + out, _ = proc.communicate(timeout=hard_cap) + rc = proc.returncode + except subprocess.TimeoutExpired: + try: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + except OSError: + pass + try: + out, _ = proc.communicate(timeout=REAP_GRACE_SEC) + except (subprocess.TimeoutExpired, OSError): + proc.kill() + out = None + rc, out = -9, (out or "") + "\n[verifier] candidate killed at the hard cap\n" + wall = time.monotonic() - t0 + + tail = (out or "")[-4000:] + report = {} + rp = root / "out" / "report.json" + if rp.is_file(): + try: + report = json.loads(rp.read_text()) + except Exception: + report = {"status": "unparseable_report"} + diag = {"candidate_returncode": rc, "candidate_wall_seconds": round(wall, 2), + "candidate_report": report, "candidate_stderr": tail, + "verifier_cuda_devices": _root_device_count()} + + artifact = root / "out" / "merged.safetensors" + if rc != 0 or not artifact.is_file() or artifact.stat().st_size == 0: + reason = report.get("reason") if isinstance(report, dict) else None + if rc == -9: + reason = "hard_cap_exceeded" + return _invalid(f"deliverable_failed:{reason or 'no_artifact'}", **diag) + + if not isinstance(report, dict) or report.get("status") != "ok": + return _invalid("runner_report_missing_or_unparseable", **diag) + + reported = report.get("merge_seconds") + if isinstance(reported, bool) or not isinstance(reported, (int, float)) or \ + not math.isfinite(float(reported)): + return _invalid("runner_report_missing_merge_timing", **diag) + if float(reported) > gc.MERGE_BUDGET_SEC: + return _invalid("merge_budget_exceeded", **diag) + + from safetensors.torch import load_file + + try: + candidate = load_file(str(artifact)) + except Exception as exc: + return _invalid(f"artifact_unreadable:{exc!r}", **diag) + + reference = gc.reference_state_dict() + bad = gc.validate_state_dict(candidate, reference) + if bad is not None: + return _invalid(f"invalid_state_dict:{bad}", **diag) + + scored = gc.evaluate(candidate, PANEL, device="cuda") + metric = float(scored["metric"]) + reward = float(gc.graded_reward(metric, True)) + payload = {"panel": PANEL, "valid": True, "failure_reason": None, + "metric": metric, "per_task_accuracy": scored["per_task_accuracy"], + "panel_rows": scored["panel_rows"], "reward": reward, + "split_audit": {t: audit[t]["panel_rows"] for t in gc.TASKS}} + payload.update(diag) + _write_metric(payload) + return payload + + +def _root_device_count() -> int: + try: + import torch + + return int(torch.cuda.device_count()) + except Exception: + return -1 + + + + +def test_sealed_labels_are_root_only(): + """The sealed labels must be unreachable from the uid that runs the deliverable.""" + st = os.stat("/tests/hidden_data") + assert st.st_uid == 0, "hidden_data must be root-owned" + assert stat.S_IMODE(st.st_mode) == 0o700, oct(stat.S_IMODE(st.st_mode)) + assert not (gc.EVAL_ROOT / PANEL / "sun397" / "labels.npy").exists(), ( + "labels must never sit beside the unlabeled panel images") + + +def test_grading_inputs_are_outside_the_writable_surface(): + """Everything the scorer reads, apart from the declared `/app/output` surface, is root-owned + and unwritable to uid 1001: the sealed /tests tree with the trusted runner and grading code + in it, the checkpoints, and the sealed panel images. The candidate's environment adds nothing + importable of its own -- no inherited PYTHONPATH, `-P` semantics on -- so only the staged copy + of the declared surface can be imported, and bytecode caching is off so no import can write a + `__pycache__` back into that surface.""" + seal = stat.S_IMODE(os.stat("/tests").st_mode) + assert not (seal & 0o077), f"/tests must stay sealed to root: {oct(seal)}" + for p in ("/tests", str(RUNNER_SRC), "/tests/grader_core.py", str(gc.ASSETS), + str(gc.EVAL_ROOT)): + st = os.stat(p) + assert st.st_uid == 0, f"{p} must be root-owned" + assert not (stat.S_IMODE(st.st_mode) & 0o022), f"{p} is group/other writable" + + env = candidate_env() + assert env["PYTHONPATH"] == "" + assert env["PYTHONSAFEPATH"] == "1" + assert env["PYTHONDONTWRITEBYTECODE"] == "1" + + +def test_split_logic_rejects_duplicate_rows(): + """The shipped split logic: the three parity partitions are disjoint and cover the split, a + duplicated row that lands in a sealed panel while its twin is in dev is caught by the + content key, and the 480-bit dhash audit separates a near duplicate from an unrelated row. + Unique fixtures cannot catch grouped leakage, so this fixture deliberately contains an exact + duplicate and a near duplicate of rows on the other side of the split.""" + panels = ba.panel_indices(40, 1) + assert not (set(panels["dev"]) & set(panels["intermediate"])) + assert not (set(panels["dev"]) & set(panels["final"])) + assert not (set(panels["intermediate"]) & set(panels["final"])) + assert sorted(set(panels["dev"]) | set(panels["intermediate"]) | set(panels["final"])) == \ + list(range(40)) + + rng = np.random.default_rng(0) + base = (rng.random((6, 3, 224, 224)) * 255).astype(np.uint8) + dev_keys = {ba.content_key(base[i]) for i in range(3)} + dev_h = np.stack([ba.dhash(base[i]) for i in range(3)]) + exact = base[0].copy() + near = base[1].copy() + near[:, :2, :2] = 0 + fresh = base[4] + assert ba.content_key(exact) in dev_keys, "an exact cross-split duplicate must be dropped" + assert ba.content_key(near) not in dev_keys + assert ba.content_key(fresh) not in dev_keys + d = ba.min_hamming(np.stack([ba.dhash(exact), ba.dhash(near), ba.dhash(fresh)]), dev_h) + assert d[0] == 0 + assert d[1] <= ba.NEAR_DUP_AUDIT_BITS, "the audit must see a near duplicate" + assert d[2] > ba.NEAR_DUP_AUDIT_BITS, "an unrelated row must not read as a duplicate" + + +def test_shipped_panels_are_deduped_against_dev(): + """Fail closed on the split audit written when the panel was materialized.""" + audit = gc.audit_panel(PANEL) + for task in gc.TASKS: + assert audit[task]["exact_duplicates_remaining"] == 0 + assert audit[task]["panel_rows"] > 0 + print("split audit:", json.dumps({t: {k: audit[t][k] for k in ( + "panel_rows", "dropped_exact_duplicates_of_dev", "min_dhash_bits_to_dev", + "sealed_rows_within_audit_bits_of_dev")} for t in gc.TASKS})) + + +def test_metric_json_written(): + """Grading always leaves a metric record, whatever the deliverable did.""" + grade() + assert (LOGS / "metric.json").is_file() + payload = json.loads((LOGS / "metric.json").read_text()) + assert set(payload) >= {"valid", "metric", "reward", "panel"} + assert 0.0 <= float(payload["reward"]) <= 1.0 + + +def test_deliverable_graded(): + """The submission ran, returned a valid CLIPVisionModel state dict, and was scored.""" + r = grade() + if not r["valid"]: + pytest.fail(f"deliverable not gradeable: {r['failure_reason']}") + assert r["metric"] is not None + assert set(r["per_task_accuracy"]) == set(gc.TASKS) + for task, acc in r["per_task_accuracy"].items(): + assert 0.0 <= acc <= 100.0, (task, acc) + + +def test_trusted_runner_was_staged_out_of_tests(): + """uid 1001 is never pointed at a helper under the 0700 /tests seal. The root grader copies + the runner into a fresh 0755 candidate temp parent, as a root-owned read-only file, and + invokes that staged path -- so the seal is neither loosened nor bypassed.""" + grade() + if not STAGE_ROOT.is_dir(): + pytest.skip("submission was rejected before staging") + parent = os.stat(STAGE_ROOT) + assert parent.st_uid == 0, "the staging parent must be root-owned" + assert stat.S_IMODE(parent.st_mode) == 0o755, oct(stat.S_IMODE(parent.st_mode)) + + staged = STAGE_ROOT / "run_merge.py" + st = os.lstat(staged) + assert stat.S_ISREG(st.st_mode), "the staged runner must be a regular file, not a link" + assert st.st_uid == 0, "the staged runner must be root-owned" + assert not (stat.S_IMODE(st.st_mode) & 0o222), oct(stat.S_IMODE(st.st_mode)) + assert staged.read_bytes() == RUNNER_SRC.read_bytes(), ( + "the staged runner must be a byte-identical copy of the trusted one") + assert not str(staged).startswith("/tests") + + +def test_staged_surface_is_read_only_and_cache_free(): + """The declared surface, and only it, reaches the candidate -- as a root-owned read-only copy + the candidate cannot mutate mid-run. PYTHONDONTWRITEBYTECODE keeps grade-time imports from + depositing a `__pycache__` inside it; deleting caches before grading would not, because the + grade-time import recreates them.""" + grade() + solution = STAGE_ROOT / "solution" + if not solution.is_dir(): + pytest.skip("submission was rejected before staging") + assert (solution / ENTRY_NAME).is_file(), "the required entry point must have been staged" + for p in [solution, *solution.rglob("*")]: + st = os.lstat(p) + assert st.st_uid == 0, f"{p} must be root-owned in the staged copy" + assert not (stat.S_IMODE(st.st_mode) & 0o222), f"{p} is writable in the staged copy" + submitted = {str(p.relative_to(DELIVERABLE)) for p in DELIVERABLE.rglob("__pycache__")} + created = sorted({str(p.relative_to(solution)) + for p in solution.rglob("__pycache__")} - submitted) + assert not created, f"grade-time imports wrote bytecode caches into the surface: {created[:3]}" diff --git a/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/docker-compose.yaml b/tasks/ties-merging-clip-vitl14-eight-task-merge/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c270d01cd52b81bf9935458b0a80d49e315752b2 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/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: 8 + mem_limit: 65536m + 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: 8 + mem_limit: 65536m + 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/ties-merging-clip-vitl14-eight-task-merge/task.toml b/tasks/ties-merging-clip-vitl14-eight-task-merge/task.toml index 473e93fc2979a3805e9125b2deaa87635b60f0de..3e4898b2e62bb4ce3a3f7e0079e05a1e1d95bbdf 100644 --- a/tasks/ties-merging-clip-vitl14-eight-task-merge/task.toml +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/task.toml @@ -1,45 +1,74 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/ties-merging-clip-vitl14-eight-task-merge" -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 = "Computer vision" -task_objective = [ "Implement", "Optimize",] -artifact_type = [ "Single script or program", "Generated output artifact",] +task_objective = [ + "Implement", + "Optimize", +] +artifact_type = [ + "Single script or program", + "Generated output artifact", +] expert_time_estimate_hours = 6.0 +are_version = "1.1" +budget_seconds = 86400 [verifier] -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 = [ "deb.debian.org", "security.debian.org", "archive.ubuntu.com", "security.ubuntu.com", "developer.download.nvidia.com", "packages.cloud.google.com", "raw.githubusercontent.com", "nodejs.org", "registry.npmjs.org", "downloads.claude.ai", "api.openai.com", "api.anthropic.com",] +network_mode = "public" build_timeout_sec = 14400.0 os = "linux" cpus = 8 memory_mb = 65536 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/ties-merging-clip-vitl14-eight-task-merge/tests/Dockerfile b/tasks/ties-merging-clip-vitl14-eight-task-merge/tests/Dockerfile index 575b7103a0920970d780baf999455a063a1fc122..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/ties-merging-clip-vitl14-eight-task-merge/tests/Dockerfile +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/tests/Dockerfile @@ -1,45 +1,2 @@ -FROM --platform=linux/amd64 gcr.io/kaggle-gpu-images/python@sha256:37c64f7dd9c54116ecd1bcc88817c5469b88387388fade02bfa8bf3fc647d461 - -ENTRYPOINT [] -ENV PYTHONPATH= -ENV PYTHONSAFEPATH=1 -ENV PYTHONHASHSEED=0 -ENV PYTHONDONTWRITEBYTECODE=1 -ENV PIP_NO_CACHE_DIR=1 -ENV PIP_DISABLE_PIP_VERSION_CHECK=1 -ENV OMP_NUM_THREADS=1 -ENV MKL_NUM_THREADS=1 -ENV OPENBLAS_NUM_THREADS=1 -ENV NUMEXPR_NUM_THREADS=1 -ENV CUBLAS_WORKSPACE_CONFIG=:4096:8 -ENV TQDM_DISABLE=1 -ENV TOKENIZERS_PARALLELISM=false - -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 mkdir -p /app/output /logs/verifier - -COPY ./build_assets.py /opt/build_assets.py -RUN /usr/bin/python3 /opt/build_assets.py --role verifier --assets /opt/assets \ - --eval-out /opt/eval --label-out /tests/hidden_data --dataset-cache /tmp/ds_cache \ - --panel-seed 20240817 --stride 1 \ - && rm -rf /tmp/ds_cache /opt/assets/pretrained/.cache /opt/assets/sun397/.cache \ - && rm -rf /opt/assets/cars/.cache /opt/assets/resisc45/.cache /opt/assets/eurosat/.cache \ - && rm -rf /opt/assets/svhn/.cache /opt/assets/gtsrb/.cache /opt/assets/mnist/.cache \ - && rm -rf /opt/assets/dtd/.cache - -COPY . /tests - -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/ties-merging-clip-vitl14-eight-task-merge/tests/finalize.py b/tasks/ties-merging-clip-vitl14-eight-task-merge/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/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/ties-merging-clip-vitl14-eight-task-merge/tests/test.sh b/tasks/ties-merging-clip-vitl14-eight-task-merge/tests/test.sh index 4fdd69632abd0667671530cc6895332f2dee9103..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/ties-merging-clip-vitl14-eight-task-merge/tests/test.sh +++ b/tasks/ties-merging-clip-vitl14-eight-task-merge/tests/test.sh @@ -1,31 +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 - -chmod -R go-rwx /tests - -export PDK_PANEL=final -export CUBLAS_WORKSPACE_CONFIG=:4096:8 -export PYTHONHASHSEED=0 -export PYTHONDONTWRITEBYTECODE=1 -export OMP_NUM_THREADS=1 -export MKL_NUM_THREADS=1 -export OPENBLAS_NUM_THREADS=1 -export NUMEXPR_NUM_THREADS=1 -export TQDM_DISABLE=1 -export TOKENIZERS_PARALLELISM=false - -cd /tests -PYTEST_CAP=6600 -if command -v timeout >/dev/null 2>&1; then - timeout -k 30 "$PYTEST_CAP" /usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA -else - /usr/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA -fi -/usr/bin/python3 /tests/compute_reward.py - -exit 0 +python3 /tests/finalize.py diff --git a/tasks/vas-maskless-deployment-feasibility/environment/.dockerignore b/tasks/vas-maskless-deployment-feasibility/environment/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..13d7fb66efbb18cdda8c25bed714bb2aaea1e458 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/.dockerignore @@ -0,0 +1 @@ +are-grader-ctx diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/Dockerfile b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..67af4f3a56c42e23cd217e97e4b4fa4a21cefbb3 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/Dockerfile @@ -0,0 +1,35 @@ +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 \ + 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 cp -a /tests/agent_mirror/. /app/ + +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 diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/Dockerfile.are b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/Dockerfile.are new file mode 100644 index 0000000000000000000000000000000000000000..607e743796b0c8622d4504526dbc7be727cef2fd --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/Dockerfile.are @@ -0,0 +1,53 @@ +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 \ + 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 cp -a /tests/agent_mirror/. /app/ + +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 + + +# ---- 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/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/data/train_traj.npz b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/data/train_traj.npz new file mode 100644 index 0000000000000000000000000000000000000000..c93373d50210715bd0ea3736572c3b3d9367173d --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/data/train_traj.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c4545bd09d88bf201bb4a4987acfcd1201a1e6f077a8463913d226032008cc1 +size 9008256 diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/data/val_traj.npz b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/data/val_traj.npz new file mode 100644 index 0000000000000000000000000000000000000000..670fd57233b40f7c0b22124c26837b43a4d7fd52 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/data/val_traj.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a2632e047ac342eafb6f19aacc3a39bdf0bd917322529f7e8cc8943a84fa0f7 +size 1149856 diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/mdobs.py b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/mdobs.py new file mode 100644 index 0000000000000000000000000000000000000000..177ca599bcdd498e3313c217cde36d3ee9da6340 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/mdobs.py @@ -0,0 +1,78 @@ +import numpy as np + +N_BLOCKS = 16 +N_FLAGS = 4 +TILE_CHANNELS = N_BLOCKS + N_FLAGS +CROP = 5 +VIEW_DIM = CROP * CROP * TILE_CHANNELS +EXTRA_DIM = 14 +OBS_DIM = VIEW_DIM + EXTRA_DIM +N_ACTIONS = 24 +N_EXTRAS_RAW = 12 + +BLOCK_VOID = 0 +BLOCK_FLOOR = 1 +BLOCK_WALL = 2 +BLOCK_STONE = 3 +BLOCK_TREE = 4 +BLOCK_COAL = 5 +BLOCK_IRON = 6 +BLOCK_GEM = 7 +BLOCK_WATER = 8 +BLOCK_LAVA = 9 +BLOCK_TABLE = 10 +BLOCK_FURNACE = 11 +BLOCK_DOWN_LADDER = 12 +BLOCK_UP_LADDER = 13 +BLOCK_PLANT = 14 +BLOCK_SAND = 15 + +FLAG_MELEE = 1 +FLAG_PASSIVE = 2 +FLAG_RANGED = 4 +FLAG_ITEM = 8 + +MAX_STEPS = 500 + + +def build_obs_batch(crop_block, crop_flags, extras_raw): + """Vectorised encoder over (N, 25) uint8, (N, 25) uint8 and (N, 12) uint16 inputs. + + Returns a float32 array of shape (N, 514). + """ + crop_block = np.asarray(crop_block, dtype=np.uint8) + crop_flags = np.asarray(crop_flags, dtype=np.uint8) + extras_raw = np.asarray(extras_raw, dtype=np.uint16) + n = crop_block.shape[0] + + view = np.zeros((n, CROP * CROP, TILE_CHANNELS), dtype=np.float32) + rows = np.arange(n)[:, None] + cols = np.arange(CROP * CROP)[None, :] + view[rows, cols, crop_block.astype(np.intp)] = 1.0 + for bit in range(N_FLAGS): + view[:, :, N_BLOCKS + bit] = ((crop_flags >> bit) & 1).astype(np.float32) + + e = extras_raw.astype(np.float32) + flags = extras_raw[:, 10].astype(np.uint16) + extras = np.empty((n, EXTRA_DIM), dtype=np.float32) + extras[:, 0:5] = np.sqrt(e[:, 0:5]) / 10.0 + extras[:, 5] = e[:, 5] / 3.0 + extras[:, 6] = e[:, 6] / 3.0 + extras[:, 7] = e[:, 7] / 10.0 + extras[:, 8] = e[:, 8] / 10.0 + extras[:, 9] = np.sqrt(e[:, 9]) / 10.0 + extras[:, 10] = (flags & 1).astype(np.float32) + extras[:, 11] = ((flags >> 1) & 1).astype(np.float32) + extras[:, 12] = ((flags >> 2) & 1).astype(np.float32) + extras[:, 13] = e[:, 11] / float(MAX_STEPS) + + return np.concatenate([view.reshape(n, VIEW_DIM), extras], axis=1) + + +def build_obs(crop_block, crop_flags, extras_raw): + """Single-observation encoder. Returns a float32 array of shape (514,).""" + return build_obs_batch( + np.asarray(crop_block, dtype=np.uint8)[None, :], + np.asarray(crop_flags, dtype=np.uint8)[None, :], + np.asarray(extras_raw, dtype=np.uint16)[None, :], + )[0] diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/policy_weights.npz b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/policy_weights.npz new file mode 100644 index 0000000000000000000000000000000000000000..8f9112c935432d160f108d0f126cbf9203af1306 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/policy_weights.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f3d72d7db954aad42641ca33b39de5c2b818e3b71346c7fee358947bf968a46 +size 1080278 diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/reference_policy.py b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/reference_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..df74294bed2ec4a48b5e1810f40ebf379bf43cc6 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/agent_mirror/reference_policy.py @@ -0,0 +1,48 @@ +import numpy as np + +N_ACTIONS = 24 +OBS_DIM = 514 + + +class ReferencePolicy: + """Loads the frozen weights and evaluates the policy's pre-mask logits.""" + + def __init__(self, weights_path): + z = np.load(weights_path) + self.layers = [] + i = 1 + while ("W%d" % i) in z: + self.layers.append((z["W%d" % i].astype(np.float32), z["b%d" % i].astype(np.float32))) + i += 1 + if not self.layers: + raise ValueError("no layers found in %s" % weights_path) + + def logits_batch(self, obs): + """Pre-mask logits for a batch. obs is (N, 514) float32; returns (N, 24) float32.""" + h = np.asarray(obs, dtype=np.float32) + if h.ndim != 2 or h.shape[1] != OBS_DIM: + raise ValueError("expected (N, %d) observations" % OBS_DIM) + for k, (w, b) in enumerate(self.layers): + h = h @ w + b + if k + 1 < len(self.layers): + np.maximum(h, 0.0, out=h) + return h + + def logits(self, obs): + """Pre-mask logits for one observation. obs is (514,); returns (24,) float32.""" + return self.logits_batch(np.asarray(obs, dtype=np.float32)[None, :])[0] + + def masked_probs(self, obs, mask): + """Action distribution after forcing the logits of masked-out actions to -inf. + + `mask` is a length-24 boolean array; True means the action is left available. + Returns a (24,) float32 array that sums to 1, or all zeros if `mask` is empty. + """ + mask = np.asarray(mask, dtype=bool) + z = self.logits(obs) + if not mask.any(): + return np.zeros(N_ACTIONS, dtype=np.float32) + z = np.where(mask, z, -np.inf) + z = z - z.max() + p = np.exp(z) + return (p / p.sum()).astype(np.float32) diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/are/drain.py b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/are/drain.py new file mode 100644 index 0000000000000000000000000000000000000000..d497e7d949a8b9ddfc54f52942938ad8f58a801b --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/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/vas-maskless-deployment-feasibility/environment/are-grader-ctx/are/server.py b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/are/server.py new file mode 100644 index 0000000000000000000000000000000000000000..03256f2770535416051025ea926d2badbad32ea0 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/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/vas-maskless-deployment-feasibility/environment/are-grader-ctx/compute_reward.py b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/compute_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9e15b401b12e61fefb55b65821dcb363caa013 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/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") +METRIC_PATH = Path("/logs/verifier/metric.json") + +try: + payload = json.loads(METRIC_PATH.read_text()) + 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.parent.mkdir(parents=True, exist_ok=True) + REWARD_PATH.write_text(reward + "\n") + print(f"reward={reward} metric={payload.get('mean_return')}") +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/vas-maskless-deployment-feasibility/environment/are-grader-ctx/grader_core.py b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/grader_core.py new file mode 100644 index 0000000000000000000000000000000000000000..12cb370df5529570987907dd235e72d8ff5d990e --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/grader_core.py @@ -0,0 +1,99 @@ +import json +import os +import sys +from pathlib import Path + +import numpy as np + +TESTS_DIR = Path(__file__).resolve().parent +sys.path.insert(0, str(TESTS_DIR)) +sys.path.insert(1, str(TESTS_DIR / "agent_mirror")) + +import mdenv as E +from reference_policy import ReferencePolicy + +GRADE_SPLIT = os.environ.get("GRADE_SPLIT", "final") +HIDDEN_DIR = TESTS_DIR / "hidden_data" / GRADE_SPLIT +N_EVAL_EPISODES = 256 +N_ACTIONS = E.N_ACTIONS +OBS_DIM = 514 +OBS_BYTES = OBS_DIM * 4 + +INIT_BUDGET_S = 600.0 +EPISODE_BUDGET_S = 2.0 +TOTAL_BUDGET_S = 1500.0 + +M0 = 3.205078125 +BASELINE_SCORE = 28.6 +HIGHER_IS_BETTER = True + +METRIC_NAME = ( + "mean episode return of the frozen MiniDungeon reference policy over the 256 sealed " + "evaluation maps when every action-selection step is masked by the submission's " + "predicted validity mask" +) + + +class MaskError(Exception): + """The deliverable failed to produce a usable mask for the current step.""" + + +def eval_seeds(): + return list(json.loads((HIDDEN_DIR / "eval_seeds.json").read_text())["seeds"]) + + +def load_policy(): + """Load the frozen weights from the verifier's own root-owned copy under /tests.""" + return ReferencePolicy(TESTS_DIR / "agent_mirror" / "policy_weights.npz") + + +def run_episode(policy, seed, source): + """Play one sealed episode with `source` supplying the mask at every step. + + `source` must expose begin_episode(), reset(obs) and predict(obs); predict returns + a (24,) bool array or raises MaskError. A MaskError ends the episode and the return + accumulated so far is kept. + + Returns (episode_return, status). + """ + env = E.MiniDungeon(seed) + act_rng = np.random.default_rng(np.random.SeedSequence([0xAC7, int(seed)])) + obs = env.observation() + total = 0.0 + source.begin_episode() + try: + source.reset(obs) + except MaskError as exc: + return total, "reset:%s" % exc + while not env.done: + try: + mask = source.predict(obs) + except MaskError as exc: + return total, "predict:%s" % exc + logits = policy.logits(obs) + draw = float(act_rng.random()) + available = np.flatnonzero(mask) + if available.size: + z = logits[available] + z = z - z.max() + p = np.exp(z) + p /= p.sum() + k = int(np.searchsorted(np.cumsum(p), draw, side="right")) + action = int(available[min(k, available.size - 1)]) + else: + action = E.A_NOOP + obs, reward, _ = env.step(action) + total += reward + return total, "ok" + + +def graded_reward(metric, valid): + """rational_squash: 0 at the strongest trivial baseline, 0.5 at the baseline score.""" + if not valid: + return 0.0 + sigma = 1.0 if HIGHER_IS_BETTER else -1.0 + x = sigma * (float(metric) - M0) + x_ref = sigma * (BASELINE_SCORE - M0) + assert x_ref > 0, "malformed task: the baseline score does not beat the trivial baseline" + u = max(0.0, x) / x_ref + return u / (1.0 + u) diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/hidden_data/final/eval_seeds.json b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/hidden_data/final/eval_seeds.json new file mode 100644 index 0000000000000000000000000000000000000000..069b8da9c67ce9cb7de9ae6780aba6d263f09888 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/hidden_data/final/eval_seeds.json @@ -0,0 +1 @@ +{"seeds": [90001, 90003, 90005, 90007, 90009, 90011, 90013, 90015, 90017, 90019, 90021, 90023, 90025, 90027, 90029, 90031, 90033, 90035, 90037, 90039, 90041, 90043, 90045, 90047, 90049, 90051, 90053, 90055, 90057, 90059, 90061, 90063, 90065, 90067, 90069, 90071, 90073, 90075, 90077, 90079, 90081, 90083, 90085, 90087, 90089, 90091, 90093, 90095, 90097, 90099, 90101, 90103, 90105, 90107, 90109, 90111, 90113, 90115, 90117, 90119, 90121, 90123, 90125, 90127, 90129, 90131, 90133, 90135, 90137, 90139, 90141, 90143, 90145, 90147, 90149, 90151, 90153, 90155, 90157, 90159, 90161, 90163, 90165, 90167, 90169, 90171, 90173, 90175, 90177, 90179, 90181, 90183, 90185, 90187, 90189, 90191, 90193, 90195, 90197, 90199, 90201, 90203, 90205, 90207, 90209, 90211, 90213, 90215, 90217, 90219, 90221, 90223, 90225, 90227, 90229, 90231, 90233, 90235, 90237, 90239, 90241, 90243, 90245, 90247, 90249, 90251, 90253, 90255, 90257, 90259, 90261, 90263, 90265, 90267, 90269, 90271, 90273, 90275, 90277, 90279, 90281, 90283, 90285, 90287, 90289, 90291, 90293, 90295, 90297, 90299, 90301, 90303, 90305, 90307, 90309, 90311, 90313, 90315, 90317, 90319, 90321, 90323, 90325, 90327, 90329, 90331, 90333, 90335, 90337, 90339, 90341, 90343, 90345, 90347, 90349, 90351, 90353, 90355, 90357, 90359, 90361, 90363, 90365, 90367, 90369, 90371, 90373, 90375, 90377, 90379, 90381, 90383, 90385, 90387, 90389, 90391, 90393, 90395, 90397, 90399, 90401, 90403, 90405, 90407, 90409, 90411, 90413, 90415, 90417, 90419, 90421, 90423, 90425, 90427, 90429, 90431, 90433, 90435, 90437, 90439, 90441, 90443, 90445, 90447, 90449, 90451, 90453, 90455, 90457, 90459, 90461, 90463, 90465, 90467, 90469, 90471, 90473, 90475, 90477, 90479, 90481, 90483, 90485, 90487, 90489, 90491, 90493, 90495, 90497, 90499, 90501, 90503, 90505, 90507, 90509, 90511]} diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/hidden_data/intermediate/eval_seeds.json b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/hidden_data/intermediate/eval_seeds.json new file mode 100644 index 0000000000000000000000000000000000000000..37b51060b00ecc65b92c07cbbadf6b86e633ac43 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/hidden_data/intermediate/eval_seeds.json @@ -0,0 +1 @@ +{"seeds": [90000, 90002, 90004, 90006, 90008, 90010, 90012, 90014, 90016, 90018, 90020, 90022, 90024, 90026, 90028, 90030, 90032, 90034, 90036, 90038, 90040, 90042, 90044, 90046, 90048, 90050, 90052, 90054, 90056, 90058, 90060, 90062, 90064, 90066, 90068, 90070, 90072, 90074, 90076, 90078, 90080, 90082, 90084, 90086, 90088, 90090, 90092, 90094, 90096, 90098, 90100, 90102, 90104, 90106, 90108, 90110, 90112, 90114, 90116, 90118, 90120, 90122, 90124, 90126, 90128, 90130, 90132, 90134, 90136, 90138, 90140, 90142, 90144, 90146, 90148, 90150, 90152, 90154, 90156, 90158, 90160, 90162, 90164, 90166, 90168, 90170, 90172, 90174, 90176, 90178, 90180, 90182, 90184, 90186, 90188, 90190, 90192, 90194, 90196, 90198, 90200, 90202, 90204, 90206, 90208, 90210, 90212, 90214, 90216, 90218, 90220, 90222, 90224, 90226, 90228, 90230, 90232, 90234, 90236, 90238, 90240, 90242, 90244, 90246, 90248, 90250, 90252, 90254, 90256, 90258, 90260, 90262, 90264, 90266, 90268, 90270, 90272, 90274, 90276, 90278, 90280, 90282, 90284, 90286, 90288, 90290, 90292, 90294, 90296, 90298, 90300, 90302, 90304, 90306, 90308, 90310, 90312, 90314, 90316, 90318, 90320, 90322, 90324, 90326, 90328, 90330, 90332, 90334, 90336, 90338, 90340, 90342, 90344, 90346, 90348, 90350, 90352, 90354, 90356, 90358, 90360, 90362, 90364, 90366, 90368, 90370, 90372, 90374, 90376, 90378, 90380, 90382, 90384, 90386, 90388, 90390, 90392, 90394, 90396, 90398, 90400, 90402, 90404, 90406, 90408, 90410, 90412, 90414, 90416, 90418, 90420, 90422, 90424, 90426, 90428, 90430, 90432, 90434, 90436, 90438, 90440, 90442, 90444, 90446, 90448, 90450, 90452, 90454, 90456, 90458, 90460, 90462, 90464, 90466, 90468, 90470, 90472, 90474, 90476, 90478, 90480, 90482, 90484, 90486, 90488, 90490, 90492, 90494, 90496, 90498, 90500, 90502, 90504, 90506, 90508, 90510]} diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/intermediate.sh b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/intermediate.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3a7094a66503a90f1b78ef6d9e846579bdecc9c --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/intermediate.sh @@ -0,0 +1,23 @@ +#!/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_default_reward() { + if [ ! -s /logs/verifier/reward.txt ]; then + printf '0\n' > /logs/verifier/reward.txt + fi +} +trap write_default_reward EXIT HUP INT TERM + +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 -q -s --no-header +/usr/local/bin/python3 /tests/compute_reward.py + +exit 0 diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/mdenv.py b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/mdenv.py new file mode 100644 index 0000000000000000000000000000000000000000..7b3da654c997a48ad0fa5128e47b95ba7a1464d7 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/mdenv.py @@ -0,0 +1,527 @@ +import numpy as np + +from mdobs import ( + BLOCK_COAL, + BLOCK_DOWN_LADDER, + BLOCK_FLOOR, + BLOCK_FURNACE, + BLOCK_GEM, + BLOCK_IRON, + BLOCK_LAVA, + BLOCK_PLANT, + BLOCK_SAND, + BLOCK_STONE, + BLOCK_TABLE, + BLOCK_TREE, + BLOCK_UP_LADDER, + BLOCK_VOID, + BLOCK_WALL, + BLOCK_WATER, + FLAG_ITEM, + FLAG_MELEE, + FLAG_PASSIVE, + FLAG_RANGED, + MAX_STEPS, + N_ACTIONS, + build_obs, +) + +GRID = 14 +PAD = 2 +N_FLOORS = 5 +KILLS_TO_DESCEND = 8 +MAX_MOBS = 3 + +A_NORTH, A_SOUTH, A_WEST, A_EAST = 0, 1, 2, 3 +A_DO = 4 +A_PLACE_STONE, A_PLACE_TABLE, A_PLACE_FURNACE, A_PLACE_PLANT = 5, 6, 7, 8 +A_CRAFT_WOOD_PICK, A_CRAFT_STONE_PICK, A_CRAFT_IRON_PICK = 9, 10, 11 +A_CRAFT_WOOD_SWORD, A_CRAFT_STONE_SWORD, A_CRAFT_IRON_SWORD = 12, 13, 14 +A_CRAFT_ARMOR, A_CRAFT_AMULET = 15, 16 +A_DRINK_POTION, A_DRINK_WATER = 17, 18 +A_ENCHANT = 19 +A_DESCEND, A_ASCEND, A_REST, A_NOOP = 20, 21, 22, 23 + +DELTA = ((-1, 0), (1, 0), (0, -1), (0, 1)) + +WALKABLE = np.zeros(16, dtype=bool) +WALKABLE[[BLOCK_FLOOR, BLOCK_SAND, BLOCK_DOWN_LADDER, BLOCK_UP_LADDER]] = True + +MOB_FLAG_ANY = FLAG_MELEE | FLAG_PASSIVE | FLAG_RANGED + +ACHIEVEMENTS = ( + ("collect_wood", 1), + ("place_table", 1), + ("craft_wood_pickaxe", 1), + ("craft_wood_sword", 1), + ("collect_stone", 1), + ("place_stone", 1), + ("place_furnace", 1), + ("place_plant", 1), + ("defeat_slime", 1), + ("drink_water", 1), + ("craft_stone_pickaxe", 3), + ("craft_stone_sword", 3), + ("collect_coal", 3), + ("reach_floor_2", 3), + ("defeat_bat", 3), + ("drink_potion", 3), + ("collect_iron", 5), + ("craft_iron_pickaxe", 5), + ("craft_iron_sword", 5), + ("reach_floor_3", 5), + ("craft_armor", 5), + ("defeat_golem", 5), + ("collect_gem", 8), + ("craft_gem_amulet", 8), + ("reach_floor_4", 8), + ("reach_floor_5", 8), + ("enchant_sword", 8), +) +N_ACH = len(ACHIEVEMENTS) +ACH_REWARD = np.array([r for _, r in ACHIEVEMENTS], dtype=np.float32) +ACH_INDEX = {name: i for i, (name, _) in enumerate(ACHIEVEMENTS)} +MAX_RETURN = float(ACH_REWARD.sum()) + +RESOURCE_P = ( + (0.32, 0.30, 0.06, 0.00, 0.00), + (0.16, 0.34, 0.10, 0.09, 0.00), + (0.10, 0.32, 0.10, 0.13, 0.03), + (0.08, 0.30, 0.08, 0.10, 0.09), + (0.06, 0.30, 0.06, 0.08, 0.13), +) +RESOURCE_BLOCK = (BLOCK_TREE, BLOCK_STONE, BLOCK_COAL, BLOCK_IRON, BLOCK_GEM) + +MINE_YIELD = { + BLOCK_TREE: ("wood", 2, "collect_wood", 0), + BLOCK_PLANT: ("wood", 1, "collect_wood", 0), + BLOCK_STONE: ("stone", 2, "collect_stone", 1), + BLOCK_COAL: ("coal", 1, "collect_coal", 1), + BLOCK_IRON: ("iron", 1, "collect_iron", 2), + BLOCK_GEM: ("gem", 1, "collect_gem", 3), +} + +MOB_HP = (2, 3, 4, 5) +MOB_DAMAGE = (1, 1, 2, 2) +MOB_FLAG = (FLAG_MELEE, FLAG_RANGED, FLAG_MELEE, FLAG_MELEE) +MOB_ACH = ("defeat_slime", "defeat_bat", "defeat_golem", None) +FLOOR_MOBS = ((0,), (0, 1), (1, 2), (2, 3), (2, 3)) + + +def _generate_floor(rng, level): + grid = np.full((GRID, GRID), BLOCK_WALL, dtype=np.uint8) + centres = [] + for _ in range(4): + h = int(rng.integers(3, 6)) + w = int(rng.integers(3, 6)) + y = int(rng.integers(1, GRID - 1 - h)) + x = int(rng.integers(1, GRID - 1 - w)) + grid[y : y + h, x : x + w] = BLOCK_FLOOR + centres.append((y + h // 2, x + w // 2)) + for (y0, x0), (y1, x1) in zip(centres, centres[1:]): + grid[y0, min(x0, x1) : max(x0, x1) + 1] = BLOCK_FLOOR + grid[min(y0, y1) : max(y0, y1) + 1, x1] = BLOCK_FLOOR + + floor_mask = grid == BLOCK_FLOOR + touching = np.zeros((GRID, GRID), dtype=bool) + touching[1:, :] |= floor_mask[:-1, :] + touching[:-1, :] |= floor_mask[1:, :] + touching[:, 1:] |= floor_mask[:, :-1] + touching[:, :-1] |= floor_mask[:, 1:] + candidates = np.argwhere((grid == BLOCK_WALL) & touching) + draws = rng.random(len(candidates)) + edges = np.cumsum(RESOURCE_P[level]) + for (y, x), d in zip(candidates, draws): + for k, edge in enumerate(edges): + if d < edge: + grid[y, x] = RESOURCE_BLOCK[k] + break + + open_cells = np.argwhere(grid == BLOCK_FLOOR) + order = rng.permutation(len(open_cells)) + picks = [tuple(int(v) for v in open_cells[i]) for i in order] + for cell in picks[:2]: + grid[cell] = BLOCK_WATER + if level >= 3: + grid[picks[2]] = BLOCK_LAVA + if level >= 1: + grid[picks[3]] = BLOCK_SAND + + open_cells = np.argwhere(grid == BLOCK_FLOOR) + order = rng.permutation(len(open_cells)) + shuffled = open_cells[order] + start = tuple(int(v) for v in shuffled[0]) + dist = np.abs(shuffled - np.array(start)).sum(axis=1) + if level < N_FLOORS - 1: + ladder = tuple(int(v) for v in shuffled[int(np.argmax(dist))]) + grid[ladder] = BLOCK_DOWN_LADDER + if level >= 1: + grid[start] = BLOCK_UP_LADDER + return grid, start + + +class MiniDungeon: + """One MiniDungeon episode, fully determined by its map seed.""" + + def __init__(self, map_seed): + self.map_seed = int(map_seed) + gen_rng = np.random.default_rng(np.random.SeedSequence([0xD1CE, self.map_seed])) + self.grids = [] + self.starts = [] + for level in range(N_FLOORS): + grid, start = _generate_floor(gen_rng, level) + self.grids.append(grid) + self.starts.append(start) + self.rng = np.random.default_rng(np.random.SeedSequence([0xB0B, self.map_seed])) + + self.floor = 0 + self.pos = self.starts[0] + self.t = 0 + self.done = False + self.kills_on_floor = 0 + self.health = 10 + self.food = 10 + self.wood = 0 + self.stone = 0 + self.coal = 0 + self.iron = 0 + self.gem = 0 + self.potions = 0 + self.pickaxe = 0 + self.sword = 0 + self.armor = 0 + self.amulet = 0 + self.enchanted = 0 + self.achieved = np.zeros(N_ACH, dtype=bool) + self.mobs = [[] for _ in range(N_FLOORS)] + self.items = [set() for _ in range(N_FLOORS)] + self._padded = np.full((GRID + 2 * PAD, GRID + 2 * PAD), BLOCK_VOID, dtype=np.uint8) + self._flags = np.zeros((GRID + 2 * PAD, GRID + 2 * PAD), dtype=np.uint8) + self._sync_padded() + + + def _sync_padded(self): + self._padded[PAD:-PAD, PAD:-PAD] = self.grids[self.floor] + + def _sync_flags(self): + self._flags[:] = 0 + for m in self.mobs[self.floor]: + self._flags[m[0] + PAD, m[1] + PAD] |= MOB_FLAG[m[2]] + for (y, x) in self.items[self.floor]: + self._flags[y + PAD, x + PAD] |= FLAG_ITEM + + def _in_bounds(self, y, x): + return 0 <= y < GRID and 0 <= x < GRID + + def _block_at(self, y, x): + if not self._in_bounds(y, x): + return BLOCK_VOID + return int(self.grids[self.floor][y, x]) + + def _mob_at(self, y, x): + for m in self.mobs[self.floor]: + if m[0] == y and m[1] == x: + return m + return None + + def _neighbours(self): + y, x = self.pos + return [(y + dy, x + dx) for dy, dx in DELTA] + + def _nearby(self, block): + """True if `block` occurs in the 3x3 neighbourhood of the player.""" + y, x = self.pos + sub = self._padded[y + PAD - 1 : y + PAD + 2, x + PAD - 1 : x + PAD + 2] + return bool((sub == block).any()) + + def compact_state(self): + """The (crop_block, crop_flags, extras_raw) triple mdobs.build_obs consumes.""" + y, x = self.pos + self._sync_flags() + crop_block = self._padded[y : y + 2 * PAD + 1, x : x + 2 * PAD + 1].reshape(-1).copy() + crop_flags = self._flags[y : y + 2 * PAD + 1, x : x + 2 * PAD + 1].reshape(-1).copy() + flags = self.armor | (self.amulet << 1) | (self.enchanted << 2) + extras = np.array( + [ + self.wood, + self.stone, + self.coal, + self.iron, + self.gem, + self.pickaxe, + self.sword, + max(0, self.health), + max(0, self.food), + self.potions, + flags, + self.t, + ], + dtype=np.uint16, + ) + return crop_block, crop_flags, extras + + def observation(self): + return build_obs(*self.compact_state()) + + + def _do_target(self): + """The neighbour `do` would act on, as (kind, cell), scanning N, S, W, E. + + kind is 'mob', 'item', 'mine' or None. + """ + for cell in self._neighbours(): + y, x = cell + if not self._in_bounds(y, x): + continue + if self._mob_at(y, x) is not None: + return "mob", cell + for cell in self._neighbours(): + if cell in self.items[self.floor]: + return "item", cell + for cell in self._neighbours(): + spec = MINE_YIELD.get(self._block_at(*cell)) + if spec is not None and self.pickaxe >= spec[3]: + return "mine", cell + return None, None + + def _place_target(self, allow_liquid=False): + for cell in self._neighbours(): + b = self._block_at(*cell) + if b in (BLOCK_FLOOR, BLOCK_SAND) and self._mob_at(*cell) is None: + return cell + if allow_liquid and b in (BLOCK_WATER, BLOCK_LAVA): + return cell + return None + + def _water_adjacent(self): + return any(self._block_at(*cell) == BLOCK_WATER for cell in self._neighbours()) + + + def valid_mask(self): + """Ground-truth action validity at the current state. Shape (24,) bool.""" + v = np.zeros(N_ACTIONS, dtype=bool) + y, x = self.pos + for a in range(4): + dy, dx = DELTA[a] + ny, nx = y + dy, x + dx + v[a] = ( + self._in_bounds(ny, nx) + and bool(WALKABLE[self._block_at(ny, nx)]) + and self._mob_at(ny, nx) is None + ) + + v[A_DO] = self._do_target()[0] is not None + + solid_target = self._place_target(allow_liquid=False) is not None + v[A_PLACE_STONE] = self.stone >= 3 and self._place_target(allow_liquid=True) is not None + v[A_PLACE_TABLE] = self.wood >= 4 and solid_target + v[A_PLACE_FURNACE] = self.stone >= 4 and solid_target + v[A_PLACE_PLANT] = self.wood >= 3 and solid_target + + table = self._nearby(BLOCK_TABLE) + furnace = self._nearby(BLOCK_FURNACE) + v[A_CRAFT_WOOD_PICK] = table and self.wood >= 1 and self.pickaxe == 0 + v[A_CRAFT_STONE_PICK] = table and self.wood >= 1 and self.stone >= 1 and self.pickaxe == 1 + v[A_CRAFT_IRON_PICK] = ( + table and furnace and self.wood >= 1 and self.coal >= 1 and self.iron >= 1 and self.pickaxe == 2 + ) + v[A_CRAFT_WOOD_SWORD] = table and self.wood >= 1 and self.sword == 0 + v[A_CRAFT_STONE_SWORD] = table and self.wood >= 1 and self.stone >= 1 and self.sword == 1 + v[A_CRAFT_IRON_SWORD] = ( + table and furnace and self.wood >= 1 and self.coal >= 1 and self.iron >= 1 and self.sword == 2 + ) + v[A_CRAFT_ARMOR] = table and furnace and self.iron >= 2 and self.coal >= 1 and self.armor == 0 + v[A_CRAFT_AMULET] = table and furnace and self.gem >= 1 and self.iron >= 1 and self.amulet == 0 + v[A_ENCHANT] = table and furnace and self.gem >= 1 and self.sword >= 3 and self.enchanted == 0 + + v[A_DRINK_POTION] = self.potions >= 1 and self.health <= 6 + v[A_DRINK_WATER] = self.food <= 8 and self._water_adjacent() + + here = self._block_at(y, x) + v[A_DESCEND] = ( + here == BLOCK_DOWN_LADDER + and self.kills_on_floor >= KILLS_TO_DESCEND + and self.floor < N_FLOORS - 1 + ) + v[A_ASCEND] = here == BLOCK_UP_LADDER and self.floor >= 1 + + self._sync_flags() + crop_flags = self._flags[y : y + 2 * PAD + 1, x : x + 2 * PAD + 1] + v[A_REST] = self.health <= 6 and not bool((crop_flags & MOB_FLAG_ANY).any()) + v[A_NOOP] = True + return v + + + def _unlock(self, name): + self.achieved[ACH_INDEX[name]] = True + + def _apply(self, action): + if action < 4: + dy, dx = DELTA[action] + self.pos = (self.pos[0] + dy, self.pos[1] + dx) + return + if action == A_DO: + kind, cell = self._do_target() + if kind == "mob": + mob = self._mob_at(*cell) + mob[3] -= 1 + self.sword + self.enchanted + if mob[3] <= 0: + self.mobs[self.floor].remove(mob) + self.kills_on_floor += 1 + name = MOB_ACH[mob[2]] + if name is not None: + self._unlock(name) + if self.rng.random() < 0.5: + self.items[self.floor].add(cell) + elif kind == "item": + self.items[self.floor].discard(cell) + self.potions += 1 + elif kind == "mine": + field, amount, ach, _ = MINE_YIELD[self._block_at(*cell)] + setattr(self, field, getattr(self, field) + amount) + self._unlock(ach) + self.grids[self.floor][cell] = BLOCK_FLOOR + self._sync_padded() + return + if action == A_PLACE_STONE: + self.stone -= 1 + self.grids[self.floor][self._place_target(allow_liquid=True)] = BLOCK_STONE + self._unlock("place_stone") + self._sync_padded() + return + if action in (A_PLACE_TABLE, A_PLACE_FURNACE, A_PLACE_PLANT): + cell = self._place_target() + if action == A_PLACE_TABLE: + self.wood -= 4 + self.grids[self.floor][cell] = BLOCK_TABLE + self._unlock("place_table") + elif action == A_PLACE_FURNACE: + self.stone -= 4 + self.grids[self.floor][cell] = BLOCK_FURNACE + self._unlock("place_furnace") + else: + self.wood -= 1 + self.grids[self.floor][cell] = BLOCK_PLANT + self._unlock("place_plant") + self._sync_padded() + return + if action == A_CRAFT_WOOD_PICK: + self.wood -= 1 + self.pickaxe = 1 + self._unlock("craft_wood_pickaxe") + elif action == A_CRAFT_STONE_PICK: + self.wood -= 1 + self.stone -= 1 + self.pickaxe = 2 + self._unlock("craft_stone_pickaxe") + elif action == A_CRAFT_IRON_PICK: + self.wood -= 1 + self.coal -= 1 + self.iron -= 1 + self.pickaxe = 3 + self._unlock("craft_iron_pickaxe") + elif action == A_CRAFT_WOOD_SWORD: + self.wood -= 1 + self.sword = 1 + self._unlock("craft_wood_sword") + elif action == A_CRAFT_STONE_SWORD: + self.wood -= 1 + self.stone -= 1 + self.sword = 2 + self._unlock("craft_stone_sword") + elif action == A_CRAFT_IRON_SWORD: + self.wood -= 1 + self.coal -= 1 + self.iron -= 1 + self.sword = 3 + self._unlock("craft_iron_sword") + elif action == A_CRAFT_ARMOR: + self.iron -= 2 + self.coal -= 1 + self.armor = 1 + self._unlock("craft_armor") + elif action == A_CRAFT_AMULET: + self.gem -= 1 + self.iron -= 1 + self.amulet = 1 + self._unlock("craft_gem_amulet") + elif action == A_ENCHANT: + self.gem -= 1 + self.enchanted = 1 + self._unlock("enchant_sword") + elif action == A_DRINK_POTION: + self.potions -= 1 + self.health = min(10, self.health + 3) + self._unlock("drink_potion") + elif action == A_DRINK_WATER: + self.food = min(10, self.food + 4) + self._unlock("drink_water") + elif action == A_DESCEND: + self.floor += 1 + self.pos = self.starts[self.floor] + self.kills_on_floor = 0 + self._sync_padded() + self._unlock("reach_floor_%d" % (self.floor + 1)) + elif action == A_ASCEND: + self.floor -= 1 + self.pos = self.starts[self.floor] + self.kills_on_floor = 0 + self._sync_padded() + elif action == A_REST: + self.health = min(10, self.health + 1) + + def _mob_phase(self): + floor_mobs = self.mobs[self.floor] + py, px = self.pos + for m in floor_mobs: + if m[4] > 0: + m[4] -= 1 + if max(abs(py - m[0]), abs(px - m[1])) <= 1: + if m[4] == 0: + self.health -= max(0, MOB_DAMAGE[m[2]] - self.armor) + m[4] = 4 + continue + if self.rng.random() < 0.75: + dy = int(np.sign(py - m[0])) + dx = int(np.sign(px - m[1])) + cand = [] + if dy != 0: + cand.append((m[0] + dy, m[1])) + if dx != 0: + cand.append((m[0], m[1] + dx)) + for ny, nx in cand: + if ( + self._in_bounds(ny, nx) + and WALKABLE[self._block_at(ny, nx)] + and (ny, nx) != self.pos + and self._mob_at(ny, nx) is None + ): + m[0], m[1] = ny, nx + break + if len(floor_mobs) < MAX_MOBS and self.rng.random() < 0.22: + open_cells = np.argwhere(WALKABLE[self.grids[self.floor]]) + if len(open_cells): + pick = open_cells[self.rng.integers(len(open_cells))] + sy, sx = int(pick[0]), int(pick[1]) + if max(abs(sy - py), abs(sx - px)) >= 3 and self._mob_at(sy, sx) is None: + kinds = FLOOR_MOBS[self.floor] + kind = int(kinds[self.rng.integers(len(kinds))]) + floor_mobs.append([sy, sx, kind, MOB_HP[kind], 0]) + + def step(self, action): + """Apply `action`. An invalid action is a silent no-op: no reward, no penalty.""" + if self.done: + return self.observation(), 0.0, True + before = self.achieved.copy() + if self.valid_mask()[int(action)]: + self._apply(int(action)) + self._mob_phase() + self.t += 1 + if self.t % 60 == 0: + self.food = max(0, self.food - 1) + if self.food == 0 and self.t % 10 == 0: + self.health -= 1 + reward = float(ACH_REWARD[self.achieved & ~before].sum()) + if self.health <= 0 or self.t >= MAX_STEPS: + self.done = True + return self.observation(), reward, self.done diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/predict_worker.py b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/predict_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..496e959da387fe5b31042a095156e228ac4c32c7 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/predict_worker.py @@ -0,0 +1,93 @@ +import importlib.util +import os +import random +import sys +import traceback + +import numpy as np + +_SEED = int(os.environ.get("PYTHONHASHSEED", "0")) +random.seed(_SEED) +np.random.seed(_SEED) +try: + import torch + + torch.manual_seed(_SEED) + torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", "1"))) +except ImportError: + pass + +OBS_DIM = 514 +OBS_BYTES = OBS_DIM * 4 +N_ACTIONS = 24 + + +def _read_exact(stream, count): + chunks = [] + got = 0 + while got < count: + piece = stream.read(count - got) + if not piece: + return None + chunks.append(piece) + got += len(piece) + return b"".join(chunks) + + +def main(): + deliverable = os.path.abspath(sys.argv[1]) + sys.path.insert(0, deliverable) + sys.path.append("/app") + + inp = sys.stdin.buffer + out = sys.stdout.buffer + + try: + entry = os.path.join(deliverable, "predictor.py") + spec = importlib.util.spec_from_file_location("submission_predictor", entry) + if spec is None or spec.loader is None: + raise ImportError("cannot load %s" % entry) + module = importlib.util.module_from_spec(spec) + sys.modules["submission_predictor"] = module + spec.loader.exec_module(module) + predictor = module.MaskPredictor(deliverable) + except BaseException: + traceback.print_exc(file=sys.stderr) + out.write(b"F") + out.flush() + return 1 + + out.write(b"I") + out.flush() + + while True: + op = inp.read(1) + if not op or op == b"Q": + return 0 + if op not in (b"R", b"P"): + return 1 + raw = _read_exact(inp, OBS_BYTES) + if raw is None: + return 1 + obs = np.frombuffer(raw, dtype=np.float32).copy() + try: + if op == b"R": + predictor.reset(obs) + out.write(b"K") + else: + mask = predictor.predict(obs) + if not isinstance(mask, np.ndarray): + raise TypeError("predict returned %r, not a numpy array" % type(mask)) + if mask.dtype != np.bool_: + raise TypeError("predict returned dtype %s, not bool" % mask.dtype) + if mask.shape != (N_ACTIONS,): + raise ValueError("predict returned shape %r, not (24,)" % (mask.shape,)) + out.write(b"K" + mask.astype(np.uint8).tobytes()) + except BaseException: + traceback.print_exc(file=sys.stderr) + out.write(b"E") + out.flush() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/requirements-verifier.txt b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/requirements-verifier.txt new file mode 100644 index 0000000000000000000000000000000000000000..ef379ee675b7b6767715aa8f76f38b9ebca7208c --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/requirements-verifier.txt @@ -0,0 +1,2 @@ +pytest==9.1.1 +pytest-json-ctrf==0.5.3 diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/requirements.txt b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3205c2e9b4c634f74d76cdf97034b4f4f6b32896 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/requirements.txt @@ -0,0 +1,8 @@ +--index-url https://download.pytorch.org/whl/cpu +--extra-index-url https://pypi.org/simple +numpy==2.5.1 +scipy==1.18.0 +scikit-learn==1.9.0 +joblib==1.5.2 +threadpoolctl==3.6.0 +torch==2.13.0+cpu diff --git a/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/test.sh b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..dc0c09f0ccc95dc8c69b4cf55aa01290587a1e12 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/test.sh @@ -0,0 +1,23 @@ +#!/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_default_reward() { + if [ ! -s /logs/verifier/reward.txt ]; then + printf '0\n' > /logs/verifier/reward.txt + fi +} +trap write_default_reward EXIT HUP INT TERM + +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/vas-maskless-deployment-feasibility/environment/are-grader-ctx/test_state.py b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/test_state.py new file mode 100644 index 0000000000000000000000000000000000000000..67d541e61bf36649e87bc9248223f75bf4bac4d1 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/environment/are-grader-ctx/test_state.py @@ -0,0 +1,389 @@ +import json +import os +import random +import select +import shutil +import signal +import stat +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +import pytest + +_SEED = int(os.environ.get("PYTHONHASHSEED", "0")) +random.seed(_SEED) +np.random.seed(_SEED) +try: + import torch + + torch.manual_seed(_SEED) + torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", "1"))) +except ImportError: + pass + +TESTS_DIR = Path(__file__).resolve().parent +sys.path.insert(0, str(TESTS_DIR)) + +import grader_core as G + +PYTHON = "/usr/local/bin/python3" +DELIVERABLE_SRC = Path("/app/output") +RUN_DIR = Path("/tmp/mdrun") +LOG_DIR = Path("/logs/verifier") +METRIC_PATH = LOG_DIR / "metric.json" +AGENT_USER = "agent" +AGENT_UID = 1001 +AGENT_GID = 1001 + + +def _tool(name, candidates): + for path in candidates: + if os.path.isfile(path) and os.access(path, os.X_OK): + return path + return shutil.which(name) + + +SETSID = _tool("setsid", ["/usr/bin/setsid", "/bin/setsid"]) +RUNUSER = _tool("runuser", ["/usr/sbin/runuser", "/sbin/runuser", "/usr/bin/runuser"]) + + +def _drop_to_agent(): + """Fallback privilege drop, used when runuser/setsid are absent from the image. + + Does exactly what `setsid runuser -u agent` does: a new session, so the process + group can be killed as a unit, then uid/gid 1001 with no supplementary groups. + """ + os.setsid() + os.setgroups([]) + os.setgid(AGENT_GID) + os.setuid(AGENT_UID) + + +class WorkerMaskSource: + """Drives the low-privilege predictor process and enforces its time budgets.""" + + def __init__(self, deliverable, worker_script, stderr_path): + env = { + "PATH": "/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin", + "HOME": "/home/agent", + "TMPDIR": str(RUN_DIR / "tmp"), + "PYTHONPATH": "", + "PYTHONSAFEPATH": "1", + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONHASHSEED": "0", + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", + } + self._stderr = open(stderr_path, "wb") + target = [PYTHON, str(worker_script), str(deliverable)] + if SETSID and RUNUSER: + argv = [SETSID, RUNUSER, "-u", AGENT_USER, "--"] + target + preexec = None + else: + argv = target + preexec = _drop_to_agent + self.proc = subprocess.Popen( + argv, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=self._stderr, + cwd=str(RUN_DIR), + env=env, + close_fds=True, + preexec_fn=preexec, + ) + self.alive = True + self._deadline = 0.0 + self.spent = 0.0 + + + def _kill(self): + self.alive = False + try: + os.killpg(os.getpgid(self.proc.pid), signal.SIGKILL) + except (ProcessLookupError, PermissionError): + try: + self.proc.kill() + except ProcessLookupError: + pass + try: + self.proc.wait(timeout=10) + except subprocess.TimeoutExpired: + pass + + def _read_exact(self, count): + fd = self.proc.stdout.fileno() + chunks = [] + got = 0 + while got < count: + remaining = self._deadline - time.monotonic() + if remaining <= 0: + self._kill() + raise G.MaskError("time budget exhausted") + ready, _, _ = select.select([fd], [], [], min(remaining, 5.0)) + if not ready: + continue + piece = os.read(fd, count - got) + if not piece: + self._kill() + raise G.MaskError("predictor process exited") + chunks.append(piece) + got += len(piece) + return b"".join(chunks) + + def _send(self, payload): + try: + self.proc.stdin.write(payload) + self.proc.stdin.flush() + except (BrokenPipeError, ValueError): + self._kill() + raise G.MaskError("predictor process exited") + + def wait_ready(self, budget): + self._deadline = time.monotonic() + budget + started = time.monotonic() + reply = self._read_exact(1) + self.init_seconds = time.monotonic() - started + if reply != b"I": + self._kill() + raise G.MaskError("construction failed") + + + def begin_episode(self): + self._deadline = time.monotonic() + G.EPISODE_BUDGET_S + + def _call(self, opcode, obs): + if not self.alive: + raise G.MaskError("predictor process is gone") + started = time.monotonic() + try: + self._send(opcode + np.ascontiguousarray(obs, dtype=np.float32).tobytes()) + head = self._read_exact(1) + if head == b"E": + raise G.MaskError("predictor raised or broke the mask contract") + if head != b"K": + self._kill() + raise G.MaskError("protocol violation") + if opcode == b"P": + raw = self._read_exact(G.N_ACTIONS) + buf = np.frombuffer(raw, dtype=np.uint8) + if buf.max(initial=0) > 1: + self._kill() + raise G.MaskError("mask bytes out of range") + return buf.astype(bool) + return None + finally: + self.spent += time.monotonic() - started + + def reset(self, obs): + self._call(b"R", obs) + + def predict(self, obs): + return self._call(b"P", obs) + + def close(self): + if self.alive: + try: + self._send(b"Q") + self.proc.wait(timeout=10) + except (G.MaskError, subprocess.TimeoutExpired): + self._kill() + self.alive = False + try: + self._stderr.close() + except OSError: + pass + + +def _copy_no_symlinks(src, dst): + """Copy a tree, skipping symlinks entirely. + + A symlink in the artifact would otherwise be dereferenced by this root process and + its target copied into a directory the predictor process can read, which is a route + out of the sealed verifier tree. + """ + dst.mkdir(parents=True, exist_ok=True) + for entry in sorted(src.iterdir()): + if entry.is_symlink(): + continue + if entry.is_dir(): + _copy_no_symlinks(entry, dst / entry.name) + elif entry.is_file(): + shutil.copyfile(entry, dst / entry.name) + + +def _chown_tree(path): + os.chown(path, AGENT_UID, AGENT_GID) + for root, dirs, files in os.walk(path): + for name in dirs + files: + os.chown(os.path.join(root, name), AGENT_UID, AGENT_GID) + + +def _stage_deliverable(): + """Copy the artifact into a scratch tree the agent uid owns, and place the runner.""" + if RUN_DIR.exists(): + shutil.rmtree(RUN_DIR, ignore_errors=True) + RUN_DIR.mkdir(parents=True) + (RUN_DIR / "tmp").mkdir() + target = RUN_DIR / "deliverable" + if DELIVERABLE_SRC.is_dir(): + _copy_no_symlinks(DELIVERABLE_SRC, target) + else: + target.mkdir() + worker = RUN_DIR / "predict_worker.py" + shutil.copyfile(TESTS_DIR / "predict_worker.py", worker) + worker.chmod(0o755) + _chown_tree(target) + os.chown(RUN_DIR / "tmp", AGENT_UID, AGENT_GID) + RUN_DIR.chmod(0o755) + return target, worker + + +def _blank_result(reason): + return { + "metric_name": G.METRIC_NAME, + "metric": 0.0, + "valid": False, + "invalid_reason": reason, + "mean_return": 0.0, + "n_episodes": 0, + "reward": 0.0, + "m0": G.M0, + "baseline_score": G.BASELINE_SCORE, + } + + +def _seal_violations(): + """Paths in the sealed tree that uid 1001 could reach. Must be empty before grading.""" + bad = [] + for path in (TESTS_DIR, G.HIDDEN_DIR, TESTS_DIR / "mdenv.py", TESTS_DIR / "grader_core.py"): + try: + mode = stat.S_IMODE(path.stat().st_mode) + except OSError as exc: + bad.append("%s: %s" % (path, exc)) + continue + if mode & 0o077: + bad.append("%s mode %o" % (path, mode)) + return bad + + +def _grade(): + violations = _seal_violations() + if violations: + return _blank_result("verifier tree not sealed: %s" % "; ".join(violations)) + + entry = DELIVERABLE_SRC / "predictor.py" + if not entry.is_file(): + return _blank_result("no /app/output/predictor.py") + if entry.stat().st_size == 0: + return _blank_result("/app/output/predictor.py is empty") + + seeds = G.eval_seeds() + policy = G.load_policy() + deliverable, worker = _stage_deliverable() + source = WorkerMaskSource(deliverable, worker, RUN_DIR / "worker_stderr.log") + try: + try: + source.wait_ready(G.INIT_BUDGET_S) + except G.MaskError as exc: + return _blank_result("construction: %s" % exc) + + returns = [] + statuses = {} + started = time.monotonic() + for seed in seeds: + if time.monotonic() - started > G.TOTAL_BUDGET_S: + statuses["global_budget_exhausted"] = statuses.get("global_budget_exhausted", 0) + 1 + returns.append(0.0) + continue + if not source.alive: + statuses["worker_gone"] = statuses.get("worker_gone", 0) + 1 + returns.append(0.0) + continue + value, status = G.run_episode(policy, seed, source) + returns.append(float(value)) + key = status if status == "ok" else status.split(":", 1)[0] + "_error" + statuses[key] = statuses.get(key, 0) + 1 + arr = np.asarray(returns, dtype=np.float64) + metric = float(arr.mean()) + return { + "metric_name": G.METRIC_NAME, + "metric": metric, + "valid": True, + "invalid_reason": None, + "mean_return": metric, + "median_return": float(np.median(arr)), + "min_return": float(arr.min()), + "max_return": float(arr.max()), + "n_episodes": int(arr.size), + "episode_returns": [round(float(v), 4) for v in arr], + "episode_statuses": statuses, + "init_seconds": round(getattr(source, "init_seconds", 0.0), 3), + "predictor_seconds": round(source.spent, 3), + "grading_seconds": round(time.monotonic() - started, 3), + "reward": G.graded_reward(metric, True), + "m0": G.M0, + "baseline_score": G.BASELINE_SCORE, + "reward_map": "rational_squash", + } + finally: + source.close() + + +@pytest.fixture(scope="module") +def result(): + LOG_DIR.mkdir(parents=True, exist_ok=True) + try: + payload = _grade() + except BaseException as exc: + payload = _blank_result("verifier error: %r" % exc) + payload["reward"] = min(1.0, max(0.0, float(payload.get("reward", 0.0)))) + METRIC_PATH.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + return payload + + +def test_verifier_tree_is_sealed(): + """The sealed grader tree and the eval ground truth must be unreadable to uid 1001. + + This is the boundary the two-process split rests on, so it is checked rather than + assumed: if the mode ever regressed, the predictor process could read the eval map + seeds and the validity oracle instead of predicting them. `_grade` applies the same + check as a fail-closed precondition; this test is what makes a regression visible in + the report rather than only as a zero. + """ + assert _seal_violations() == [] + + +def test_deliverable_constructed(result): + """The submitted predictor imported and constructed inside its declared budget. + + A failure here is the invalid path: the reward is already 0 and the run produced no + episodes, so nothing downstream is meaningful. + """ + assert result["valid"], result["invalid_reason"] + assert result["init_seconds"] <= G.INIT_BUDGET_S + + +def test_all_sealed_episodes_were_played(result): + """Every one of the sealed maps in this split contributed exactly one episode return. + + Guards against a partially-completed sweep silently averaging over fewer maps, which + would make the metric incomparable between submissions. + """ + assert result["n_episodes"] == len(G.eval_seeds()) == G.N_EVAL_EPISODES + + +def test_reward_is_bounded_and_recorded(result): + """The reward written for the platform is finite and inside [0, 1]. + + compute_reward.py clamps as well; this fails the report loudly if the map itself + ever produced something outside the contract. + """ + reward = result["reward"] + assert np.isfinite(reward) and 0.0 <= reward <= 1.0 + assert METRIC_PATH.is_file() diff --git a/tasks/vas-maskless-deployment-feasibility/environment/docker-compose.yaml b/tasks/vas-maskless-deployment-feasibility/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b8f0bdfaeed29e8807097e790814d29cca77037 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/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: "2400" + 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: "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/vas-maskless-deployment-feasibility/task.toml b/tasks/vas-maskless-deployment-feasibility/task.toml index 41ce86c06453e261e7a9f9342453ae252278a5f2..0c81670cb7d3b8766b39ca86bb7a72f98c2fb9e3 100644 --- a/tasks/vas-maskless-deployment-feasibility/task.toml +++ b/tasks/vas-maskless-deployment-feasibility/task.toml @@ -1,57 +1,72 @@ schema_version = "1.4" -artifacts = [ "/app/output",] +artifacts = [ + { source = "/var/lib/are", service = "grader" }, +] [task] name = "bespokelabs/vas-maskless-deployment-feasibility" -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 = "Model Training and ML Infrastructure" subcategory = "Reinforcement learning" -task_objective = [ "Implement", "Optimize",] -artifact_type = [ "Single script or program", "Generated output artifact",] +task_objective = [ + "Implement", + "Optimize", +] +artifact_type = [ + "Single script or program", + "Generated output artifact", +] expert_time_estimate_hours = 3.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/vas-maskless-deployment-feasibility/tests/Dockerfile b/tasks/vas-maskless-deployment-feasibility/tests/Dockerfile index 67af4f3a56c42e23cd217e97e4b4fa4a21cefbb3..d2750cc0bbcdf7b6d2227fa69c3556cfa123b4a6 100644 --- a/tasks/vas-maskless-deployment-feasibility/tests/Dockerfile +++ b/tasks/vas-maskless-deployment-feasibility/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 \ - MKL_NUM_THREADS=1 \ - OPENBLAS_NUM_THREADS=1 \ - 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 cp -a /tests/agent_mirror/. /app/ - -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 +FROM python:3.12-slim +COPY . /tests/ diff --git a/tasks/vas-maskless-deployment-feasibility/tests/finalize.py b/tasks/vas-maskless-deployment-feasibility/tests/finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..65ac6c9544bb4996809a090b19e911c5f751c0d2 --- /dev/null +++ b/tasks/vas-maskless-deployment-feasibility/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/vas-maskless-deployment-feasibility/tests/test.sh b/tasks/vas-maskless-deployment-feasibility/tests/test.sh index dc0c09f0ccc95dc8c69b4cf55aa01290587a1e12..51263a157ae44f1275daf34b67b0fa99a3d64338 100644 --- a/tasks/vas-maskless-deployment-feasibility/tests/test.sh +++ b/tasks/vas-maskless-deployment-feasibility/tests/test.sh @@ -1,23 +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_default_reward() { - if [ ! -s /logs/verifier/reward.txt ]; then - printf '0\n' > /logs/verifier/reward.txt - fi -} -trap write_default_reward EXIT HUP INT TERM - -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 +python3 /tests/finalize.py