File size: 10,748 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""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.
Where the package gives each instance its own time limit (PRACTICE_CAPS in package_common.py),
each practice instance runs at its own, as grading runs each sealed one at its own; --budget then
applies only to an instance without one.
Where package_common.TIMING is "single-core", grading runs GRADING_CORES sealed instances at once,
each on one CPU, so the rehearsal runs that many copies of each practice instance at once, each on
one CPU, and scores the first copy: its run is timed beside the same load as a graded one.
"""

from __future__ import annotations

import argparse
import functools
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")
# {practice id: seconds}, each at most the per-run budget as grading holds a sealed one; {} = the budget for all
PRACTICE_CAPS = {i: min(float(sec), pc.PER_RUN_BUDGET_SEC)
                 for i, sec in (getattr(pc, "PRACTICE_CAPS", None) or {}).items()}


def final(value: float, status: str) -> int:
    print(json.dumps({"score": value, "status": status}))
    return 0 if status == "ok" else 1


def copies(run_one, cpus: list):
    """Single-core timing: runner.stage_and_run (run_one), but each call runs len(cpus) copies of itself at
    once, copy j on cpus[j] alone (runner.run_wave), as grading runs its sealed instances side by side; the
    first copy's run is the one handed back. The method directory is made read-only before the first, as
    grading makes it."""
    started = []

    def run(method, inputs, outputs, budget, *rest):
        if not started:
            runner.read_only_method(Path(method))
            started.append(True)
        uid = rest[0][0] if rest and rest[0] is not None else None
        call = functools.partial(run_one, method, inputs, outputs, budget, *rest)
        first = runner.run_wave([call] * len(cpus), cpus, uid)[0]
        runner.LAST_RUN_SEC = first["last_run_sec"]
        return first["status"], first["texts"]
    return run


def caps_note() -> None:
    """Each practice instance's own time limit, where the package sets them, in place of the budget shown."""
    if PRACTICE_CAPS:
        print("each instance runs at its own time limit: "
              + ", ".join(f"{i} {sec:g} s" for i, sec in PRACTICE_CAPS.items()))


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."""
    budget = PRACTICE_CAPS.get(iid, budget)
    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:")
    caps_note()
    default = budget
    for iid, inputs, answers_root in instances:
        budget = PRACTICE_CAPS.get(iid, default)
        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
    if getattr(pc, "TIMING", "lane") == "single-core":
        try:
            cpus = runner.core_cpus(int(pc.GRADING_CORES))
        except RuntimeError as e:
            print(f"cannot rehearse the way grading runs: {e}")
            return final(pc.FLOOR, "cores_unavailable")
        runner.stage_and_run = copies(runner.stage_and_run, cpus)
        print(f"grading runs {len(cpus)} sealed instances at once, each on one CPU; this rehearsal runs "
              f"{len(cpus)} copies of each practice instance at once, on CPUs {cpus}, and scores the first")
    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]
    caps_note()
    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())