QDpy
Loading...
Searching...
No Matches
retry_sweep.py
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-3.0-or-later
3
4"""Run a QDpy retry plan through Rundra and verify the fetched results."""
5
6import argparse
7import json
8from pathlib import Path
9from shutil import copyfile
10import subprocess
11from tempfile import TemporaryDirectory
12
13from qdpy.reporting import make_retry_plan
14
15
16def _attempt_status(directory, job):
17 group = job["group"]
18 plan = make_retry_plan({group: directory}, [job["seed"]], {group: job["config"]})
19 if plan["blocked"]:
20 raise ValueError(f"Cannot verify retry result at {directory}: {plan['blocked'][0]['reason']}.")
21 return plan["jobs"][0] if plan["jobs"] else None
22
23
24
25def retry_sweep(plan_path, output, *, experiment, targets, profile="local", trust_checkpoints=False):
26 """Run still-pending jobs in fresh attempt directories and return failed run IDs.
27
28 Use one coordinator per output directory. The experiment should stage
29 ``search.py`` and optional ``retry-input`` and fetch ``results/**``.
30 Reverify original results and prior retry attempts before submitting.
31 Only pass ``trust_checkpoints=True`` for checkpoints from a trusted source.
32 """
33 plan = json.loads(Path(plan_path).read_text(encoding="utf-8"))
34 if plan["schema_version"] != 1:
35 raise ValueError("Unsupported retry plan version.")
36 inventory = plan["groups"]
37 current = make_retry_plan({group: row["results"] for group, row in inventory.items()}, plan["seeds"],
38 {group: row["config"] for group, row in inventory.items()})
39 if current["groups"] != inventory:
40 raise ValueError("A group configuration or resolved path changed. Generate a new retry plan.")
41 requested = {job["run_id"] for job in plan["jobs"]}
42 for row in current["blocked"]:
43 print(f"Blocked {row['group']} seed={row['seed']}: {row['reason']}", flush=True)
44 output = Path(output).resolve()
45 if any(output.is_relative_to(row["results"]) for row in inventory.values()):
46 raise ValueError("Keep the retry output outside the input groups so their manifests stay unambiguous.")
47 experiment, targets = Path(experiment).resolve(strict=True), Path(targets).resolve(strict=True)
48 example = Path(__file__).resolve().parent
49 queued = []
50 for job in current["jobs"]:
51 if job["run_id"] not in requested:
52 continue
53 root = output / job["run_id"]
54 attempts = sorted(root.glob("attempt-[0-9][0-9][0-9][0-9][0-9][0-9]"), reverse=True)
55 statuses = [_attempt_status(attempt, job) for attempt in attempts]
56 if None in statuses:
57 continue
58 recovery = next((row for row in statuses if row["action"] == "resume"), job)
59 if recovery["action"] == "resume" and not trust_checkpoints:
60 raise ValueError("Use --trust-checkpoints only after verifying the source of the native checkpoints.")
61 number = max((int(attempt.name.removeprefix("attempt-")) for attempt in attempts), default=0)
62 queued.append((root, number + 1, recovery))
63
64 print(f"Submitting {len(queued)} retry task(s).", flush=True)
65 failures = [row["run_id"] for row in current["blocked"]]
66 for root, number, job in queued:
67 destination = root / f"attempt-{number:06d}"
68 root.mkdir(parents=True, exist_ok=True)
69 print(f"{job['action']} {job['group']} seed={job['seed']}", flush=True)
70 with TemporaryDirectory(prefix="stage-", dir=root) as stage_dir:
71 stage = Path(stage_dir)
72 copyfile(example / "search.py", stage / "search.py")
73 config = stage / "config.yaml"
74 copyfile(job["config"], config)
75 if job["action"] == "resume":
76 inputs = stage / "retry-input"
77 inputs.mkdir()
78 copyfile(job["checkpoint"], inputs / "checkpoint.pkl")
79 copyfile(job["journal"], inputs / "evaluations.jsonl")
80 result = subprocess.run(
81 ["rundr", "run", str(experiment), "--project-file", str(example / "rundra.yaml"),
82 "--profile", profile, "--targets-file", str(targets), "--data-dir", str(output / "rundra-data"),
83 "--source-root", str(stage), "--config", str(config), "--seed", str(job["seed"]),
84 "--fetch-mode", "copy", "--destination", str(destination)], cwd=output, check=False,
85 )
86 if result.returncode or _attempt_status(destination, job) is not None:
87 failures.append(job["run_id"])
88 return failures
89
90
91def main():
92 """Run the local retry experiment or an equivalent user-supplied experiment."""
93 parser = argparse.ArgumentParser(description=__doc__)
94 example = Path(__file__).resolve().parent
95 parser.add_argument("plan", type=Path)
96 parser.add_argument("output", type=Path)
97 parser.add_argument("--experiment", type=Path, default=example / "experiment-local-retry.yaml")
98 parser.add_argument("--targets-file", type=Path, default=example / "targets-local.yaml")
99 parser.add_argument("--profile", default="local")
100 parser.add_argument("--trust-checkpoints", action="store_true")
101 args = parser.parse_args()
102 failures = retry_sweep(args.plan, args.output, experiment=args.experiment, targets=args.targets_file,
103 profile=args.profile, trust_checkpoints=args.trust_checkpoints)
104 if failures:
105 raise SystemExit(f"Unresolved run IDs: {', '.join(failures)}")
106
107
108if __name__ == "__main__":
109 main()