Download server/phase2/src/finalize_phase2.py from lylybig8/mdm_coverage: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/datasets/lylybig8/mdm_coverage/resolve/main/server/phase2/src/finalize_phase2.py
- Command line
-
hf download hf://datasets/lylybig8/mdm_coverage/server/phase2/src/finalize_phase2.py
-
curl -L -o finalize_phase2.py https://huggingface.co/datasets/lylybig8/mdm_coverage/resolve/main/server/phase2/src/finalize_phase2.py
15.2 kB
| #!/usr/bin/env python3 | |
| """Recover only known K=4 solver timeouts into a new auditable run directory. | |
| The completed base run is never modified or restarted. Candidate parameters, | |
| the K=3 screening scores, and the selection/ranking remain frozen. Original | |
| errors are retained before narrowly scoped IPM recovery and recertification. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import datetime as dt | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import resource | |
| import shutil | |
| import subprocess | |
| import sys | |
| import time | |
| FROZEN_KEYS = ("id", "n", "tau", "weights", "probabilities", "budget", "head_bound") | |
| def digest(path): | |
| return hashlib.sha256(path.read_bytes()).hexdigest() | |
| def read_json(path): | |
| return json.loads(path.read_text()) | |
| def save_json(path, obj): | |
| temporary = path.with_name(path.name + ".pending") | |
| temporary.write_text(json.dumps(obj, indent=2, allow_nan=False) + "\n") | |
| temporary.replace(path) | |
| def frozen(witness): | |
| return {key: witness[key] for key in FROZEN_KEYS} | |
| def payload_witnesses(payload): | |
| if "witnesses" in payload: | |
| return payload["witnesses"] | |
| if "id" in payload and "cases" in payload: | |
| return [payload] | |
| raise ValueError("Retry artifact is not a candidate or witnesses payload") | |
| def utc_now(): | |
| return dt.datetime.now(dt.timezone.utc).isoformat() | |
| def main(args): | |
| started = time.monotonic() | |
| deadline = started + 1800 | |
| base = args.base_run.resolve(strict=True) | |
| output = args.output_run.resolve() | |
| source_dir = Path(__file__).resolve().parent | |
| if output.exists(): | |
| raise ValueError("Output directory must be new; existing results will not be overwritten") | |
| if output == base or base in output.parents: | |
| raise ValueError("New run must not be placed inside the immutable base run") | |
| for name in ("status.json", "search_results.json", "witnesses.json", "config.json"): | |
| if not (base / name).is_file(): | |
| raise ValueError(f"Missing required completed-run artifact: {name}") | |
| base_status = read_json(base / "status.json") | |
| search = read_json(base / "search_results.json") | |
| payload = read_json(base / "witnesses.json") | |
| config = read_json(args.config) | |
| if base_status.get("status", "").upper() == "RUNNING": | |
| raise ValueError("The base job is still marked RUNNING; wait for it to finish") | |
| failed_stages = [row for row in base_status.get("stages", []) | |
| if row.get("status") == "FAILED"] | |
| if any(row.get("stage") != "search" for row in failed_stages): | |
| raise ValueError("The base run has a non-search failure outside this recovery scope") | |
| if search.get("status") not in ("complete", "complete_with_errors"): | |
| raise ValueError("The frozen candidate search must have finished") | |
| if digest(args.config) != digest(base / "config.json"): | |
| raise ValueError("Provided configuration bytes differ from the frozen base configuration") | |
| if search["config"] != config: | |
| raise ValueError("Search configuration differs from the supplied non-smoke configuration") | |
| witnesses = payload["witnesses"] | |
| ids = [w["id"] for w in witnesses] | |
| if len(ids) != len(set(ids)) or set(ids) != set(search["selected_ids"]): | |
| raise ValueError("Witness IDs and frozen selected IDs disagree or contain duplicates") | |
| expected_count = len(config["n_values"]) * len(config["budgets"]) | |
| if len(witnesses) != expected_count: | |
| raise ValueError("Not all prespecified n/budget groups have a selected witness") | |
| expected_K = set(config["evaluation_K"]) | |
| if expected_K != {2, 3, 4}: | |
| raise ValueError("This narrowly scoped finalizer expects K=2,3,4") | |
| missing = {} | |
| for w in witnesses: | |
| present = [c["K"] for c in w["cases"]] | |
| if len(present) != len(set(present)) or not set(present) <= expected_K: | |
| raise ValueError(f"Duplicate or unexpected cases for {w['id']}") | |
| if expected_K - set(present): | |
| if expected_K - set(present) != {4}: | |
| raise ValueError(f"Only a missing K=4 case may be recovered: {w['id']}") | |
| missing[w["id"]] = w | |
| original_errors = copy.deepcopy(search.get("errors", [])) | |
| error_ids = [] | |
| for error in original_errors: | |
| message = str(error.get("error", "")).lower() | |
| if (error.get("K") != 4 or error.get("id") not in missing | |
| or "time limit" not in message or "lp" not in message): | |
| raise ValueError(f"Unexpected original error; no recovery attempted: {error}") | |
| error_ids.append(error["id"]) | |
| if set(error_ids) != set(missing) or len(error_ids) != len(set(error_ids)): | |
| raise ValueError("Missing cases must correspond one-to-one to retained K=4 timeouts") | |
| reusable = {} | |
| if args.reuse_retry: | |
| raw_retry = read_json(args.reuse_retry) | |
| if raw_retry.get("retry_metadata", {}).get("status") != "complete": | |
| raise ValueError("Reusable retry artifact is not marked complete") | |
| reusable = {w["id"]: w for w in payload_witnesses(raw_retry)} | |
| for witness_id, repaired in reusable.items(): | |
| if witness_id in missing and frozen(repaired) != frozen(missing[witness_id]): | |
| raise ValueError("Reusable retry differs from exact frozen parameters") | |
| # All preflight checks precede any new result-directory creation. | |
| shutil.copytree(base, output) | |
| for name in ("status.json", "search_results.json", "witnesses.json"): | |
| shutil.copy2(base / name, output / ("original_" + name)) | |
| if (output / "source").exists(): | |
| shutil.copytree(output / "source", output / "original_source") | |
| (output / "source").mkdir(exist_ok=True) | |
| for file in sorted(source_dir.glob("*.py")): | |
| shutil.copy2(file, output / "source" / file.name) | |
| (output / "logs").mkdir(exist_ok=True) | |
| (output / "retries").mkdir(exist_ok=True) | |
| (output / "figures").mkdir(exist_ok=True) | |
| files = sorted((output / "source").glob("*.py")) | |
| status = { | |
| "run_id": output.name, "status": "RUNNING", "started_utc": utc_now(), | |
| "scope": "Known K4 solver-timeout recovery only; original candidate search not rerun", | |
| "base_run": str(base), "base_status": base_status, | |
| "base_artifact_sha256": {name: digest(base / name) for name in | |
| ("status.json", "search_results.json", "witnesses.json", "config.json")}, | |
| "config_sha256": digest(output / "config.json"), | |
| "source_sha256": {f.name: digest(f) for f in files}, | |
| "historical_errors": original_errors, "recovery_records": [], "stages": [], | |
| "limits": {"total_seconds": 1800, "retry_stage_seconds": 180, | |
| "lp_seconds": 120, "address_space_gib": 8, "cpu_threads": 1}, | |
| } | |
| save_json(output / "status.json", status) | |
| env = os.environ.copy() | |
| env.update(OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1", | |
| NUMEXPR_NUM_THREADS="1", MPLBACKEND="Agg", PYTHONUNBUFFERED="1") | |
| def limits(): | |
| cap = 8 * 1024**3 | |
| resource.setrlimit(resource.RLIMIT_AS, (cap, cap)) | |
| def stage(name, command, cap_seconds=None): | |
| remaining = deadline - time.monotonic() | |
| if remaining <= 0: | |
| raise TimeoutError("Full recovery job exceeded its 1800-second budget") | |
| timeout = remaining if cap_seconds is None else min(remaining, cap_seconds) | |
| row = {"stage": name, "status": "RUNNING", "command": command, | |
| "timeout_seconds": timeout} | |
| status["stages"].append(row) | |
| save_json(output / "status.json", status) | |
| t0 = time.monotonic() | |
| print("START " + name, flush=True) | |
| try: | |
| with (output / "logs" / (name + ".log")).open("w") as log: | |
| completed = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, | |
| env=env, preexec_fn=limits, timeout=timeout) | |
| row.update(status="COMPLETE" if completed.returncode == 0 else "FAILED", | |
| returncode=completed.returncode, runtime_seconds=time.monotonic() - t0) | |
| if completed.returncode: | |
| raise RuntimeError(f"{name} failed; no automatic fallback is authorized") | |
| except Exception as exc: | |
| row.update(status="FAILED", error=repr(exc), runtime_seconds=time.monotonic() - t0) | |
| raise | |
| finally: | |
| save_json(output / "status.json", status) | |
| print("END " + name, flush=True) | |
| if args.reuse_retry: | |
| shutil.copy2(args.reuse_retry, output / "retries" / "reused_input.json") | |
| try: | |
| for witness in witnesses: | |
| if witness["id"] not in missing: | |
| continue | |
| record = {"id": witness["id"], "K": 4, "method": "highs-ipm"} | |
| if witness["id"] in reusable: | |
| repaired = reusable[witness["id"]] | |
| if frozen(repaired) != frozen(witness): | |
| raise ValueError("Reusable retry differs from exact frozen parameters") | |
| retry_path = output / "retries" / "reused_input.json" | |
| record["source"] = "reused verified IPM retry" | |
| else: | |
| retry_path = output / "retries" / (witness["id"] + "_K4_ipm.json") | |
| candidate_path = output / "candidates" / (witness["id"] + ".json") | |
| if frozen(read_json(candidate_path)) != frozen(witness): | |
| raise ValueError("Candidate artifact differs from selected witness parameters") | |
| stage("retry_" + witness["id"], [ | |
| sys.executable, str(output / "source" / "retry_lp_cases.py"), | |
| "--config", str(output / "config.json"), "--input", str(candidate_path), | |
| "--output", str(retry_path), "--method", "highs-ipm", "--K", "4", | |
| "--time-limit", "120"], cap_seconds=180) | |
| retry_payload = read_json(retry_path) | |
| if retry_payload.get("retry_metadata", {}).get("status") != "complete": | |
| raise ValueError("IPM retry did not complete cleanly") | |
| repaired = retry_payload | |
| record["source"] = "new bounded IPM retry" | |
| if frozen(repaired) != frozen(witness): | |
| raise ValueError("Repaired witness parameters differ from frozen input") | |
| additions = [case for case in repaired["cases"] if case["K"] == 4] | |
| if len(additions) != 1 or additions[0].get("lp_optimum") is None: | |
| raise ValueError("Recovery must provide exactly one successful K4 LP case") | |
| if additions[0].get("retry_provenance", {}).get("method") != "highs-ipm": | |
| raise ValueError("Recovered case was not produced by the authorized IPM retry") | |
| case = copy.deepcopy(additions[0]) | |
| if any(case["lp_optimum"] > old["lp_optimum"] + 2e-7 for old in witness["cases"]): | |
| raise ValueError("Recovered K4 objective violates fixed-oracle monotonicity") | |
| witness["cases"].append(case) | |
| witness["cases"].sort(key=lambda item: item["K"]) | |
| record.update(retry_artifact=str(retry_path.relative_to(output)), | |
| retry_artifact_sha256=digest(retry_path), | |
| lp_optimum=case["lp_optimum"], status="RESOLVED") | |
| status["recovery_records"].append(record) | |
| witness["recovery_metadata"] = record | |
| candidate_path = output / "candidates" / (witness["id"] + ".json") | |
| candidate = read_json(candidate_path) | |
| if frozen(candidate) != frozen(witness): | |
| raise ValueError("Selected candidate changed during recovery") | |
| candidate["cases"] = copy.deepcopy(witness["cases"]) | |
| candidate["recovery_metadata"] = record | |
| save_json(candidate_path, candidate) | |
| save_json(output / "witnesses.json", payload) | |
| save_json(output / "status.json", status) | |
| if any({c["K"] for c in w["cases"]} != expected_K for w in witnesses): | |
| raise ValueError("Incomplete cases remain after recovery") | |
| search["historical_errors"] = original_errors | |
| search["errors"] = [] | |
| search["status"] = "complete" | |
| search["recovery_metadata"] = {"base_run": str(base), | |
| "records": status["recovery_records"], | |
| "candidate_search_rerun": False, | |
| "candidate_parameters_and_K3_ranking_unchanged": True} | |
| payload["status"] = "complete" | |
| payload["recovery_metadata"] = search["recovery_metadata"] | |
| save_json(output / "search_results.json", search) | |
| save_json(output / "witnesses.json", payload) | |
| stage("recovery_certify", [sys.executable, str(output / "source" / "certify_witness.py"), | |
| "--input", str(output / "witnesses.json"), | |
| "--output", str(output / "certificates.json"), "--self-test"]) | |
| stage("recovery_validate_summary", [sys.executable, | |
| str(output / "source" / "normalize_results.py"), "--run-dir", str(output)]) | |
| stage("recovery_plots", [sys.executable, str(output / "source" / "plot_phase2.py"), | |
| "--run-dir", str(output)]) | |
| paragraph = ( | |
| "\n## 求解器超时与独立恢复记录\n\n" | |
| f"原冻结候选搜索完整结束,但其中 {len(original_errors)} 个 K=4 LP 达到 120 秒时限。" | |
| f"本目录在原运行的独立副本中,通过 HiGHS IPM 恢复了 {len(status['recovery_records'])} 个缺失组合;" | |
| "没有重新筛选候选、改变模型参数、改变预算或重新排列 K=3 排名。" | |
| "随后对全部入选模型和轮数组合重新进行了独立有理数认证。\n\n" | |
| "原始失败保存在 original_status.json、original_search_results.json、original_witnesses.json," | |
| "以及 search_results.json 的 historical_errors 字段;原代码保存在 original_source/。" | |
| "恢复方法、输入哈希、资源限制与日志见 status.json、retries/ 和 logs/。\n") | |
| for name in ("RESULTS_PHASE2.md", "README.md"): | |
| report = output / name | |
| prior = report.read_text() if report.exists() else "# Phase-two recovered run\n" | |
| report.write_text(prior + paragraph) | |
| status["status"] = "COMPLETE" | |
| except Exception as exc: | |
| status.update(status="FAILED", error=repr(exc)) | |
| raise | |
| finally: | |
| status.update(finished_utc=utc_now(), runtime_seconds=time.monotonic() - started) | |
| save_json(output / "status.json", status) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--base-run", type=Path, required=True) | |
| parser.add_argument("--output-run", type=Path, required=True) | |
| parser.add_argument("--config", type=Path, required=True) | |
| parser.add_argument("--reuse-retry", type=Path) | |
| main(parser.parse_args()) | |