#!/usr/bin/env python3 """Restartable, observable Ritz step for the even-signature engine. The expensive part of a certificate is the high-precision Whitening Ritz vector (`arb` Cholesky + inverse + product), which is minutes for `n = 846` and ~46 min for the `k = 50, eps = 1/25, d = 25` control. This module wraps that pipeline so the work is *banked* and observable: * heartbeat -- a daemon thread rewrites `heartbeat.json` every `HEARTBEAT_S` seconds with stage, elapsed, `n`, `pid` and whether a stop has been requested; it keeps ticking during the monolithic FLINT calls, so a long stage is never silent; * checkpoints -- stage artefacts under a run directory: meta.json parameter fingerprint dg.npy equilibration diagonal (float64) Ld.npy Cholesky factor, double rounding (float64) Af.npy whitened symmetric matrix (float64) vec.npz rationalised top eigenvector (exact rational) A restart loads the newest valid stage and skips it; * stop -- a `STOP` sentinel (in the checkpoint dir or given explicitly) raises `StopRequested` at the next stage/row boundary after saving what is complete; the process exits with code 75 (EX_TEMPFAIL) and re-running resumes. No work is lost that a stage checkpoint covers. Honest limitation (stated, not hidden): the exact `arb` factor `L` is not disk-serialisable within the 1 GB disk budget at `n = 1780` (each `arb_mat` is hundreds of MB, and a double rounding of `L` is *not* enough to form the whitened matrix because `cond(L) = sqrt(cond(S1))` is astronomically large). Therefore the stage checkpoints let a restart skip the build/equilibration and the final eigen-solve, and always skip a *completed* vector; a stop in the middle of the `inv`/product stage resumes at the start of that stage. The heartbeat makes the remaining work and its stage explicit. Usage (module): from ritz_ckpt import ritz_vector_resumable, StopRequested ef, c_f, lam, c_rat = ritz_vector_resumable(50, Fr(1,25), 25, prec=1024, ckpt_dir="out/ckpt_k50_eps1_25_d25") """ from __future__ import annotations import json import os import sys import threading import time from fractions import Fraction as Fr import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) # the exact engine and blocked arb Cholesky live in the sibling programme 0022 _ALT = os.path.normpath(os.path.join(HERE, "..", "..", "0022", "src")) if os.path.isdir(_ALT): sys.path.insert(0, _ALT) from even_engine import EvenEngine # noqa: E402 from flint_chol import chol_arb # noqa: E402 HEARTBEAT_S = 10.0 ENGINE_TAG = "even_engine/v1" EX_TEMPFAIL = 75 class StopRequested(Exception): """Raised when a STOP sentinel is seen; the run is restartable.""" def _fp(k, eps, d, prec): return {"k": int(k), "eps": str(eps), "d": int(d), "prec": int(prec), "engine": ENGINE_TAG} def _read_json(path, default=None): try: with open(path, encoding="utf-8") as stream: return json.load(stream) except FileNotFoundError: return default def _atomic_json(path, obj): tmp = path + ".tmp" with open(tmp, "w") as f: json.dump(obj, f, indent=2) os.replace(tmp, path) class Heartbeat: """Daemon heartbeat writer: one JSON file, rewritten atomically.""" def __init__(self, path, state): self.path = path self.state = dict(state) self.state["pid"] = os.getpid() self.state["started"] = time.time() self._stop = threading.Event() self._thread = threading.Thread(target=self._loop, daemon=True) self._thread.start() def set(self, **kw): self.state.update(kw) self.state["updated"] = time.time() def _loop(self): while not self._stop.is_set(): self.state["elapsed_s"] = round(time.time() - self.state["started"], 1) self.state["stop_requested"] = bool(self.state.get("stop_requested")) try: _atomic_json(self.path, self.state) except Exception: pass self._stop.wait(HEARTBEAT_S) def close(self): self.state["elapsed_s"] = round(time.time() - self.state["started"], 1) try: _atomic_json(self.path, self.state) except Exception: pass self._stop.set() class Ckpt: def __init__(self, ckpt_dir, k, eps, d, prec, stop_path=None, heartbeat=True): self.dir = ckpt_dir os.makedirs(self.dir, exist_ok=True) self.fp = _fp(k, eps, d, prec) self.stop_path = stop_path or os.path.join(self.dir, "STOP") meta_path = os.path.join(self.dir, "meta.json") meta = _read_json(meta_path) if meta is None and os.path.exists(meta_path): raise ValueError("checkpoint metadata must not be null") artifacts = ("dg.npy", "Ld.npy", "Af.npy", "vec.npz") if meta is None and any(os.path.exists(self.path(name)) for name in artifacts): raise ValueError("checkpoint artifacts lack their parameter manifest") if meta is not None and meta != self.fp: raise ValueError(f"checkpoint fingerprint mismatch: {meta} != {self.fp}") _atomic_json(os.path.join(self.dir, "meta.json"), self.fp) self.hb = None if heartbeat: self.hb = Heartbeat(os.path.join(self.dir, "heartbeat.json"), dict(self.fp, stage="init", n=None)) def path(self, name): return os.path.join(self.dir, name) def stop_requested(self): return os.path.exists(self.stop_path) def check_stop(self): if self.hb: self.hb.set(stop_requested=self.stop_requested()) if self.stop_requested(): raise StopRequested(f"STOP sentinel present at {self.stop_path}") def stage(self, name, n=None, **kw): if self.hb: self.hb.set(stage=name, n=n, **kw) # ---- artefacts ------------------------------------------------------- def save_dg(self, dg): np.save(self.path("dg.npy"), np.asarray(dg, dtype=np.float64)) def load_dg(self): p = self.path("dg.npy") return np.load(p) if os.path.exists(p) else None def save_Ld(self, Ld): np.save(self.path("Ld.npy"), np.asarray(Ld, dtype=np.float64)) def load_Ld(self): p = self.path("Ld.npy") return np.load(p) if os.path.exists(p) else None def save_Af(self, Af): np.save(self.path("Af.npy"), np.asarray(Af, dtype=np.float64)) def load_Af(self): p = self.path("Af.npy") return np.load(p) if os.path.exists(p) else None def save_vec(self, c_float, c_rat, lam): np.savez(self.path("vec.npz"), c_float=np.asarray(c_float, dtype=np.float64), num=np.array([x.numerator for x in c_rat], dtype=object), den=np.array([x.denominator for x in c_rat], dtype=object), lam=np.asarray([lam], dtype=np.float64)) if self.hb: self.hb.set(stage="done", lam=float(lam)) def load_vec(self): p = self.path("vec.npz") if not os.path.exists(p): return None z = np.load(p, allow_pickle=True) c_rat = [Fr(int(a), int(b)) for a, b in zip(z["num"], z["den"])] return z["c_float"], c_rat, float(z["lam"][0]) def _build_arb_checked(ef, prec, hb_stage, check_stop, chunk=64): """`EvenEngine.arb_matrices` with a stop check and heartbeat every `chunk` rows, so the build stage is interruptible (the stock method is monolithic).""" import flint from flint import arb, arb_mat flint.ctx.prec = prec n = ef.n A1 = arb_mat(n, n) A2 = arb_mat(n, n) for i in range(n): if i % chunk == 0: hb_stage("build", n=n, rows=i) check_stop() for j in range(i, n): a1 = arb(ef.M1(i, j)) a2 = arb(ef.M2(i, j)) A1[i, j] = a1 A1[j, i] = a1 A2[i, j] = a2 A2[j, i] = a2 return A1, A2 def _whiten_and_solve(ef, prec, block, hb_stage, check_stop): """The staged pipeline. Returns (dg, c_float, lam). Calls back to the checkpoint object at each stage boundary.""" import flint from flint import arb, arb_mat flint.ctx.prec = prec n = ef.n A1, A2 = _build_arb_checked(ef, prec, hb_stage, check_stop) check_stop() hb_stage("equil", n=n) dg_arb = [arb(1) / A1[i, i].sqrt() for i in range(n)] S1 = arb_mat(n, n) S2 = arb_mat(n, n) for i in range(n): if i % 64 == 0: hb_stage("equil", n=n, rows=i) check_stop() for j in range(i, n): v1 = A1[i, j] * dg_arb[i] * dg_arb[j] v2 = A2[i, j] * dg_arb[i] * dg_arb[j] S1[i, j] = v1 S1[j, i] = v1 S2[i, j] = v2 S2[j, i] = v2 check_stop() hb_stage("chol", n=n) L = chol_arb(S1, block=block, prec=prec) check_stop() hb_stage("whiten", n=n) Li = L.inv() A = Li * S2 * Li.transpose() check_stop() hb_stage("eig", n=n) Af = np.array([[float(A[i, j].mid()) for j in range(n)] for i in range(n)]) Af = (Af + Af.T) / 2 w, V = np.linalg.eigh(Af) y = V[:, -1] Ld = np.array([[float(L[i, j].mid()) for j in range(n)] for i in range(n)]) x = np.linalg.solve(Ld.T, y) dg = np.array([float(z.mid()) for z in dg_arb]) c = dg * x return dg, Ld, Af, c, float(w[-1]) def ritz_vector_resumable(k, eps, d, prec=1024, block=128, ckpt_dir=None, stop_path=None, denom=10 ** 9, force=False, log=print): """Restartable Ritz vector. Returns (ef_or_None, c_float, lam, c_rat). On the resume path the even-signature engine is *not* built (it is a real cost at d = 25/27), so the first return value is `None`; build it via `EvenEngine(k, Fr(eps), d, "fmpq")` if the caller needs it. """ eps = Fr(eps) if ckpt_dir is None: ckpt_dir = os.path.join(HERE, "..", "out", f"ckpt_k{k}_eps{str(eps).replace('/', '_')}_d{d}") ck = Ckpt(ckpt_dir, k, eps, d, prec, stop_path=stop_path) try: if not force: got = ck.load_vec() if got is not None: c_f, c_rat, lam = got ck.stage("resumed-vector", n=len(c_rat), lam=lam) log(f"[ckpt] {ckpt_dir}: resumed finished vector " f"(lam={lam:.9f}, n={len(c_rat)}) -- no recomputation") # the exact engine (tens of seconds to build at d = 25/27) is # deliberately NOT built on the resume path return None, c_f, lam, c_rat ck.check_stop() ef = EvenEngine(k, eps, d, "fmpq") dg, Ld, Af, c, lam = _whiten_and_solve( ef, prec, block, ck.stage, ck.check_stop) ck.save_dg(dg) ck.save_Ld(Ld) ck.save_Af(Af) c_rat = [Fr(float(x)).limit_denominator(denom) for x in c] ck.save_vec(c, c_rat, lam) log(f"[ckpt] {ckpt_dir}: computed and banked vector " f"(lam={lam:.9f}, n={ef.n})") return ef, c, lam, c_rat finally: if ck.hb: ck.hb.close() if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("k", type=int) ap.add_argument("eps") ap.add_argument("d", type=int) ap.add_argument("--prec", type=int, default=1024) ap.add_argument("--ckpt", default=None) ap.add_argument("--stop", dest="stop_path", default=None) ap.add_argument("--force", action="store_true") a = ap.parse_args() try: _, c, lam, c_rat = ritz_vector_resumable( a.k, Fr(a.eps), a.d, prec=a.prec, ckpt_dir=a.ckpt, stop_path=a.stop_path, force=a.force) print("OK lam=%.9f n=%d" % (lam, len(c))) except StopRequested as e: print("STOPPED (restartable):", e) sys.exit(EX_TEMPFAIL)