zzqsb's picture
Release the REE tasks and dataset card.
7f50cd1
Raw History Blame Contribute Delete
8.06 kB
"""Rehearse a submission on the practice instances.
python3 /app/selfcheck.py rehearse [method dir] [--budget SECONDS]
Runs build.sh if the method has one, then runs the method on every practice instance with grading's
per-run limits (the per-instance time limit unless --budget changes it, the unprivileged account, a
read-only copy of the inputs) and scores what it wrote with the same metric.
With several practice instances each one is scored separately and printed on its own line, and
the reported score aggregates them with `package_common.aggregate`, the function the grader applies
to the sealed instances: the plain mean unless AGGREGATE is geometric. An instance whose run fails
takes the floor instead of being dropped, so abandoning a hard one can never improve what you see.
Where the metric scores a whole set rather than one instance, every practice instance runs first
and one metric call scores them together, the way the grader scores the sealed side.
The last line printed is {"score": …, "status": …}. It is a rehearsal, not the score you will be given.
With several practice instances scored one by one, the line before it lists each one's score.
Where the metric scores a whole set, that line holds each instance scored alone with the same
metric: a diagnostic beside the set's score, which the grader records the same way.
"""
from __future__ import annotations
import argparse
import json
import shutil
import sys
import tempfile
import time
from pathlib import Path
sys.path.insert(0, "/app")
import package_common as pc # noqa: E402 (shared with the grader)
import runner # noqa: E402
METHOD = Path("/app/methods/main")
def final(value: float, status: str) -> int:
print(json.dumps({"score": value, "status": status}))
return 0 if status == "ok" else 1
def rehearse_one(method, solver, budget, iid: str, inputs: Path, answers_root: Path | None) -> dict:
"""One practice instance, run and scored exactly as grading does it."""
t0 = time.time()
status, texts = runner.stage_and_run(method, inputs, pc.OUTPUTS, budget, solver)
elapsed = time.time() - t0
if status != "ok":
return {"id": iid, "score": pc.FLOOR, "status": status, "sec": elapsed, "stdout": ""}
answers = pc.answers_for(answers_root, iid) if answers_root is not None else None
pc.ELAPSED = getattr(runner, "LAST_RUN_SEC", None) # as the grader hands it to {elapsed}
m = pc.score_outputs(texts, inputs, answers)
return {"id": iid, "score": m["score"], "status": m["status"], "sec": elapsed,
"stdout": m["stdout"]}
def score_set(runs: list) -> dict:
"""One metric call over every practice instance, laid out as the grader lays out the sealed side.
`runs` is [(id, inputs, answers or None, run status, output texts)]. Each instance's inputs,
answers and outputs sit under `<id>/`; an instance whose run failed contributes no output.
"""
root = Path(tempfile.mkdtemp(prefix="rehearsal_set_"))
try:
has_answers = False
for iid, inputs, answers, status, texts in runs:
shutil.copytree(inputs, root / "instance" / iid)
if answers is not None: # arranged as the grader's: <id>/ or <id>/<file>
has_answers = True
dst = root / "answers" / iid
if answers.is_dir():
shutil.copytree(answers, dst)
else:
dst.mkdir(parents=True)
shutil.copyfile(answers, dst / answers.name)
pc.write_outputs(texts if status == "ok" else {}, root / "output" / iid)
return pc.metric_call(root / "instance", root / "answers" if has_answers else None,
root / "output", timeout=pc.whole_side_timeout(len(runs)))
finally:
shutil.rmtree(root, ignore_errors=True)
def score_alone(run) -> float:
"""One practice instance scored alone, as a set of one: a diagnostic; the floor if it cannot be."""
if run[3] != "ok":
return pc.FLOOR
try:
return score_set([run])["score"]
except Exception: # noqa: BLE001 - a diagnostic never costs the score line
return pc.FLOOR
def rehearse_set(method, solver, budget, instances) -> int:
"""The metric scores a whole set: run every practice instance, then score them in one call."""
runs = []
print(f"{len(instances)} practice instance(s), budget {budget:g} s each; the metric scores them "
"as one set:")
for iid, inputs, answers_root in instances:
t0 = time.time()
status, texts = runner.stage_and_run(method, inputs, pc.OUTPUTS, budget, solver)
answers = pc.answers_for(answers_root, iid) if answers_root is not None else None
runs.append((iid, inputs, answers, status, texts))
mark = "" if status == "ok" else " <- no output is scored for it"
print(f" {iid:<16}{status:>18} ({time.time() - t0:.0f}s){mark}")
m = score_set(runs)
if m["stdout"]:
print("metric output:")
print(m["stdout"].rstrip())
print(f"\n one metric call over ALL {len(runs)} instances: {m['score']:.6g}"
f" <- the grader scores the sealed side the same way")
failed = [r[0] for r in runs if r[3] != "ok"]
status = m["status"] if m["status"] != "ok" else ("ok" if not failed else "partial")
if len(runs) > 1: # each instance alone: a diagnostic, never the score
each = {r[0]: score_alone(r) for r in runs}
print(" each instance scored alone (a diagnostic; the score is the call over the set): "
+ ", ".join(f"{i} {v:.6g}" for i, v in each.items()))
print(json.dumps({"per_instance": each}))
return final(m["score"], status)
def rehearse(args) -> int:
method = Path(args.method) if args.method else METHOD
solver = runner.solver_ids()
ok, note = runner.build_submission(method, solver)
if not ok:
print(f"build.sh failed: {note}")
return final(pc.FLOOR, "build_failed")
instances = pc.practice_dirs()
if pc.SCOPE == "set":
return rehearse_set(method, solver, args.budget, instances)
results = [rehearse_one(method, solver, args.budget, iid, inputs, answers)
for iid, inputs, answers in instances]
if len(results) == 1:
r = results[0]
print(f"method finished with status {r['status']} after {r['sec']:.1f} s "
f"(budget {args.budget:g} s)")
if r["stdout"]:
print("metric output:")
print(r["stdout"].rstrip())
return final(r["score"], r["status"])
failed = [r["id"] for r in results if r["status"] != "ok"]
print(f"{len(results)} practice instances, budget {args.budget:g} s each "
f"(a failed instance takes the floor, {pc.FLOOR!r}):")
for r in results:
mark = "" if r["status"] == "ok" else f" <- {r['status']}, floored"
print(f" {r['id']:<16}{r['score']:>18.6g} ({r['sec']:.0f}s){mark}")
mean = pc.aggregate([r["score"] for r in results])
print(f"\n {pc.AGGREGATE} over ALL {len(results)} instances: {mean:.6g}"
f" <- the grader aggregates the sealed side the same way")
if failed:
print(f" {len(failed)} failed ({', '.join(failed)}); a failed instance cannot be made to "
"disappear from this number.")
print(json.dumps({"per_instance": {r["id"]: r["score"] for r in results}}))
return final(mean, "ok" if not failed else "partial")
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="command", required=True)
r = sub.add_parser("rehearse")
r.add_argument("method", nargs="?")
r.add_argument("--budget", type=float, default=pc.PER_RUN_BUDGET_SEC)
r.set_defaults(func=rehearse)
args = ap.parse_args()
return args.func(args)
if __name__ == "__main__":
sys.exit(main())