File size: 9,377 Bytes
7f50cd1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | """Verifier: run the submitted method on every sealed instance and score it with the core's metric.
For each sealed instance, in the order tests/sealed.json lists them, the method runs once through
runner.stage_and_run (the per-run budget, the solver account, a read-only copy of the inputs), then
the core's declared metric scores what it wrote. A method failure, a timeout, a non-zero metric exit
or an unreadable score gives the floor for that instance. The score is package_common.aggregate over
the instance scores, in the metric's own units and direction -- the plain mean unless AGGREGATE is
geometric, and the self-check calls the same function so a rehearsal cannot aggregate differently
(scope "instance") -- or the one score of a call over the whole side (scope "set"). A failed
build.sh scores the floor everywhere, and so does a grader failure. tests/reward_scale.py places
this score on the reward's [0, 1] scale.
Scope "set" also scores each instance alone with the same metric, onto its row: a diagnostic
that the score never reads (score_details.json says so in per_instance_scores).
"""
from __future__ import annotations
import json
import math
import os
import shutil
import sys
import tempfile
import time
import traceback
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import package_common as pc # noqa: E402
import runner # noqa: E402
SUBMISSION_DIR = Path(os.environ.get("SUBMISSION_DIR", "/app/methods/main"))
SEALED_DIR = HERE / "data"
ANSWERS_DIR = HERE / "data-answers"
# The sealed side's work list. It lives here, in the grader's image alone, and not in
# package_common.py, which the solver's image also holds: the ids disclose the sealed side's
# structure. It is read as data, never imported.
_SEALED = json.loads((HERE / "sealed.json").read_text())
SEALED_IDS = tuple(_SEALED["sealed_ids"])
SEALED_ANSWER_PATHS = _SEALED["answer_paths"]
def sealed_answers(iid: str) -> Path | None:
"""{answers} of one sealed instance -- pc.answers_for, against the grader's own table."""
rel = SEALED_ANSWER_PATHS.get(iid)
return None if rel is None else ANSWERS_DIR / rel
LOG_DIR = Path(os.environ.get("VERIFIER_LOG_DIR", "/logs/verifier"))
REWARD_FILES = ("reward.json", "reward.txt", "score_details.json")
HEAD_CHARS = 200 # of the first output file, quoted when an instance scores the floor
def clear_rewards() -> None:
for name in REWARD_FILES:
try:
os.unlink(LOG_DIR / name)
except FileNotFoundError:
pass
def write_safely(name: str, text: str) -> None:
"""Write one score file: remove whatever is at the path first, and never follow a link."""
path = LOG_DIR / name
try:
os.unlink(path)
except FileNotFoundError:
pass
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
with os.fdopen(fd, "w") as fh:
fh.write(text)
def write_reward(value: float, details: dict) -> None:
LOG_DIR.mkdir(parents=True, exist_ok=True)
if not math.isfinite(value):
value = pc.FLOOR
details["reward"] = value
write_safely("score_details.json", json.dumps(details, indent=1) + "\n")
write_safely("reward.txt", f"{value}\n")
write_safely("reward.json", json.dumps({"reward": value}) + "\n")
def base_details() -> dict:
return {"metric": "score", "direction": pc.DIRECTION, "floor": pc.FLOOR, "scope": pc.SCOPE,
"per_run_budget_sec": pc.PER_RUN_BUDGET_SEC, "instances": [], "per_instance": []}
def head(texts: dict) -> str | None:
text = texts.get(pc.OUTPUTS[0]) if pc.OUTPUTS else None
if text is None:
return None
return text[:HEAD_CHARS].decode("utf-8", "replace") if isinstance(text, bytes) else text[:HEAD_CHARS]
DIAGNOSTIC = ("diagnostic: each instance scored alone with the same metric; the reward is the one "
"call over the whole side (set_metric)")
def score_alone(rows: list, set_root: Path) -> None:
"""Scope "set": each row's score is the metric over that instance alone, a diagnostic.
The call is laid out as the call over the whole side is, holding only this instance's `<id>/`:
copies of its inputs, its answers and its output. A failed run's row takes the floor, and so
does a call that fails, with the metric's status. Nothing here can change the reward: the
reward is written before this runs, and an error leaves the row at the floor.
"""
for row in rows:
iid = row["id"]
if row["status"] != "ok":
row["score"] = pc.FLOOR
continue
one = None
try:
one = Path(tempfile.mkdtemp(prefix="one_instance_"))
shutil.copytree(SEALED_DIR / iid, one / "instance" / iid, symlinks=True)
answers = one / "answers" if SEALED_ANSWER_PATHS else None
if answers is not None:
answers.mkdir()
if (ANSWERS_DIR / iid).is_dir():
shutil.copytree(ANSWERS_DIR / iid, answers / iid, symlinks=True)
shutil.copytree(set_root / iid, one / "output" / iid)
m = pc.metric_call(one / "instance", answers, one / "output")
row.update(score=m["score"], metric_exit=m["exit"], metric_sec=m["metric_sec"])
if m["status"] != "ok":
row.update(status=m["status"], note=m["stdout"][-500:])
except Exception as e: # noqa: BLE001 - a diagnostic never costs the reward
row.update(score=pc.FLOOR, status="metric_failed", note=f"not scored alone: {e}"[:500])
finally:
if one is not None:
shutil.rmtree(one, ignore_errors=True)
def grade() -> tuple[float, dict]:
details = base_details()
solver = runner.solver_ids()
ok, note = runner.build_submission(SUBMISSION_DIR, solver)
if not ok:
details.update(status="build_failed", note=note, n_failed=len(SEALED_IDS))
return pc.FLOOR, details
set_root = Path(tempfile.mkdtemp(prefix="set_outputs_")) if pc.SCOPE == "set" else None
scores, failed, heads = [], 0, {}
try:
for iid in SEALED_IDS:
t0 = time.time()
status, texts = runner.stage_and_run(SUBMISSION_DIR, SEALED_DIR / iid, pc.OUTPUTS,
pc.PER_RUN_BUDGET_SEC, solver)
row = {"id": iid, "status": status, "run_sec": round(time.time() - t0, 3)}
row["solver_sec"] = getattr(runner, "LAST_RUN_SEC", None) # run.sh alone: what {elapsed} reads
if pc.SCOPE == "set":
pc.write_outputs(texts if status == "ok" else {}, set_root / iid)
failed += status != "ok"
heads[iid] = head(texts)
elif status == "ok":
pc.ELAPSED = row["solver_sec"]
m = pc.score_outputs(texts, SEALED_DIR / iid, sealed_answers(iid))
row.update(score=m["score"], metric_exit=m["exit"], metric_sec=m["metric_sec"])
if m["status"] != "ok":
row.update(status=m["status"], note=m["stdout"][-500:])
scores.append(m["score"])
else:
row["score"] = pc.FLOOR
scores.append(pc.FLOOR)
if pc.SCOPE == "instance":
failed += row["status"] != "ok"
if row["score"] == pc.FLOOR:
row["output_head"] = head(texts)
details["per_instance"].append(row)
details["instances"].append(iid)
if pc.SCOPE == "set":
m = pc.metric_call(SEALED_DIR, ANSWERS_DIR if SEALED_ANSWER_PATHS else None, set_root,
timeout=pc.whole_side_timeout(len(SEALED_IDS)))
details.update(set_metric={k: m[k] for k in ("status", "exit", "metric_sec")},
status="ok", n_failed=failed)
if m["score"] == pc.FLOOR: # quoted as the instance scope quotes a floored instance
for row in details["per_instance"]:
row["output_head"] = heads.get(row["id"])
write_reward(m["score"], dict(details)) # the reward first: the diagnostic cannot cost it
score_alone(details["per_instance"], set_root)
details["per_instance_scores"] = DIAGNOSTIC
return m["score"], details
finally:
if set_root is not None:
shutil.rmtree(set_root, ignore_errors=True)
details.update(status="ok", n_failed=failed)
return pc.aggregate(scores), details
def main() -> int:
LOG_DIR.mkdir(parents=True, exist_ok=True)
clear_rewards() # a leftover file must not survive as this score
try:
reward, details = grade()
except Exception: # noqa: BLE001 - fail closed
write_reward(pc.FLOOR, {**base_details(), "status": "grader_failed",
"error": traceback.format_exc()})
traceback.print_exc()
return 1
write_reward(reward, details)
print(f"score {reward:.6g} ({pc.DIRECTION} is better; status {details.get('status')}, "
f"{len(details['instances'])} instances, {details.get('n_failed')} failed)")
return 0
if __name__ == "__main__":
sys.exit(main())
|