File size: 6,843 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 | """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.
"""
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
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")
finally:
shutil.rmtree(root, ignore_errors=True)
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")
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.")
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())
|