File size: 9,911 Bytes
4bfaa5d | 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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | #!/usr/bin/env python3
"""exp00 self-check: builds/exercises core/{klinf,popquant,seqtest,par}.py and
writes results/exp00_selfcheck.json per specs/exp00_core.md.
python3 scripts/exp00_selfcheck.py [--toy]
No experiment-specific logic lives here; this only validates the shared core.
"""
import argparse
import json
import os
import sys
import time
import numpy as np
from scipy.optimize import minimize_scalar
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from core import par
from core.klinf import klinf_emp, klinf_emp_generic, klinf_path
from core.popquant import pop, beta_phi_closed_form
from core.seqtest import run_path
RESULTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "results")
def log(msg):
print(f"[exp00] {msg}", file=sys.stderr, flush=True)
# --------------------------------------------------------------------- primal
def _primal_maximize(x, m_o, T_max=40.0, xatol=1e-13):
"""Independent maximizer of F(lam)=mean(log(1-lam(x-m_o))) using a
log-distance-from-boundary substitution so the search stays well
conditioned right up to the singular endpoint. Cross-checks the dual
(Brent-on-Psi) solver in klinf_emp without sharing any code path."""
xbar = x.mean()
singular_at_hi = m_o > xbar
if singular_at_hi:
lo, hi = 0.0, 1.0 / (1.0 - m_o)
else:
lo, hi = -1.0 / m_o, 0.0
span = hi - lo
def lam_of_t(t):
if singular_at_hi:
return hi - np.exp(-t) * span
return lo + np.exp(-t) * span
def negF(t):
lam = lam_of_t(t)
denom = 1.0 - lam * (x - m_o)
if np.any(denom <= 0):
return 1e18
return -float(np.mean(np.log(denom)))
res = minimize_scalar(negF, bounds=(0.0, T_max), method="bounded", options=dict(xatol=xatol))
return -res.fun
# ---------------------------------------------------------------- trial funcs
def _dual_vs_primal_trial(seed):
rng = np.random.default_rng(seed)
n = int(rng.integers(5, 80))
a, b = rng.uniform(0.3, 6), rng.uniform(0.3, 6)
x = rng.beta(a, b, size=n)
m_o = rng.uniform(0.02, 0.98)
if x.mean() == m_o:
return 0.0
v_dual, _, _ = klinf_emp(x, m_o, use_fastpath=False)
v_primal = _primal_maximize(x, m_o)
return abs(v_dual - v_primal)
def _fastpath_trial(seed):
rng = np.random.default_rng(seed)
p = rng.uniform(0.0, 1.0)
n = int(rng.integers(5, 300))
m_o = rng.uniform(0.02, 0.98)
x = (rng.uniform(size=n) < p).astype(float)
if x.mean() == m_o:
return 0.0
v_fast, lam_fast, _ = klinf_emp(x, m_o, use_fastpath=True)
v_gen, lam_gen, _ = klinf_emp_generic(x, m_o)
return max(abs(v_fast - v_gen), abs(lam_fast - lam_gen))
def _path_trial(seed, n):
rng = np.random.default_rng(seed)
a, b = rng.uniform(0.5, 5), rng.uniform(0.5, 5)
x = rng.beta(a, b, size=n)
m_o = rng.uniform(0.1, 0.9)
path = klinf_path(x, m_o)
pointwise = np.array([klinf_emp(x[:k], m_o)[0] for k in range(1, n + 1)])
return float(np.max(np.abs(path - pointwise)))
def _ht_violation_count(seed, path_len):
"""eq (11)'s bound KL_inf <= 1/(1-m_o) is a fact about the '+' branch
(m_o >= running mean): pointwise, log(1-lam(x-m_o)) <= log(1+lam*m_o) <=
log(1/(1-m_o)) < 1/(1-m_o) for x in [0,1], lam in [0,lam_bar]. The
mirrored '-' branch (m_o < running mean) obeys the mirrored bound
1/m_o by the same argument. We check each step against whichever bound
matches its branch."""
rng = np.random.default_rng(seed)
dist_kind = rng.choice(["beta", "bernoulli"])
m_o = rng.uniform(0.05, 0.95)
if dist_kind == "beta":
a, b = rng.uniform(0.5, 5), rng.uniform(0.5, 5)
x = rng.beta(a, b, size=path_len)
else:
p = rng.uniform(0.05, 0.95)
x = (rng.uniform(size=path_len) < p).astype(float)
path = klinf_path(x, m_o)
running_mean = np.cumsum(x) / np.arange(1, path_len + 1)
branch_plus = m_o >= running_mean
bound = np.where(branch_plus, 1.0 / (1.0 - m_o), 1.0 / m_o)
return int(np.sum(path > bound + 1e-9))
def _beta_phi_trial(seed):
rng = np.random.default_rng(seed)
a, b = rng.uniform(1.05, 8), rng.uniform(1.05, 8)
mean = a / (a + b)
m_o = rng.uniform(mean, 0.995) # ensure '+' branch (m_o >= mean)
r = pop(("beta", a, b), m_o)
cf = beta_phi_closed_form(a, b, m_o)
if r["phi"] is None or not np.isfinite(cf) or cf == 0:
return 0.0
return abs(r["phi"] - cf) / abs(cf)
# ------------------------------------------------------------- determinism
def _determinism_replicate(rng, r):
n = 50 + r
x = rng.beta(2.0, 3.0, size=n)
m_o = 0.3 + 0.05 * (r % 5)
val, lam, case = klinf_emp(x, m_o)
return (val, lam, case)
def _check_determinism(n_reps, config_id=777):
r1 = par.make_parallel(n_jobs=1)(
__import__("joblib").delayed(_determinism_replicate)(par.rng_for(config_id, r), r)
for r in range(n_reps)
)
r2 = par.make_parallel(n_jobs=min(2, os.cpu_count() or 1))(
__import__("joblib").delayed(_determinism_replicate)(par.rng_for(config_id, r), r)
for r in range(n_reps)
)
return r1 == r2
# --------------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--toy", action="store_true")
args = ap.parse_args()
toy = args.toy
n_jobs = par.n_cores()
log(f"starting exp00 self-check (toy={toy}), JOB_CORES-derived n_jobs={n_jobs}")
if toy:
n_dual_primal, n_fastpath, n_path, n_ht, n_beta_phi, n_det = 20, 60, 6, 8, 12, 8
path_n, ht_path_len = 60, 300
else:
n_dual_primal, n_fastpath, n_path, n_ht, n_beta_phi, n_det = 300, 1500, 30, 60, 150, 16
path_n, ht_path_len = 400, 3000
t0 = time.time()
parallel = par.make_parallel(n_jobs=n_jobs)
joblib_delayed = __import__("joblib").delayed
log(f"running {n_dual_primal} dual-vs-primal trials")
dual_vs_primal_errs = parallel(joblib_delayed(_dual_vs_primal_trial)(i) for i in range(n_dual_primal))
dual_vs_primal_max_abs_err = float(max(dual_vs_primal_errs))
log(f" max abs err = {dual_vs_primal_max_abs_err:.3e}")
log(f"running {n_fastpath} Bernoulli fast-path trials")
fastpath_errs = parallel(joblib_delayed(_fastpath_trial)(i + 10_000) for i in range(n_fastpath))
bernoulli_fastpath_max_abs_err = float(max(fastpath_errs))
log(f" max abs err = {bernoulli_fastpath_max_abs_err:.3e}")
log(f"running {n_path} klinf_path-vs-pointwise trials (n={path_n})")
path_errs = parallel(joblib_delayed(_path_trial)(i + 20_000, path_n) for i in range(n_path))
klinf_path_vs_pointwise_max_abs_err = float(max(path_errs))
log(f" max abs err = {klinf_path_vs_pointwise_max_abs_err:.3e}")
log(f"running {n_ht} Honda-Takemura bound checks (path_len={ht_path_len})")
ht_counts = parallel(joblib_delayed(_ht_violation_count)(i + 30_000, ht_path_len) for i in range(n_ht))
ht_bound_violations = int(sum(ht_counts))
log(f" violations = {ht_bound_violations}")
log(f"running {n_beta_phi} Beta Phi closed-form checks")
beta_phi_errs = parallel(joblib_delayed(_beta_phi_trial)(i + 40_000) for i in range(n_beta_phi))
beta_phi_closed_form_max_rel_err = float(max(beta_phi_errs))
log(f" max rel err = {beta_phi_closed_form_max_rel_err:.3e}")
log(f"checking determinism across JOB_CORES (1 vs 2) on {n_det} replicates")
determinism_jobcores_1_vs_2 = bool(_check_determinism(n_det))
log(f" bit-identical = {determinism_jobcores_1_vs_2}")
log("smoke-testing run_path (raises on any internal invariant violation)")
def _run_path_smoke(seed):
rng = np.random.default_rng(seed)
sampler = lambda rng_, size: rng_.beta(2, 3, size=size)
run_path(rng, sampler, 0.5, [0.05, 0.1], "theory", n_max=2000 if not toy else 500)
return True
n_smoke = 6 if toy else 20
smoke_results = parallel(joblib_delayed(_run_path_smoke)(i + 50_000) for i in range(n_smoke))
assert all(smoke_results), "run_path invariant assertions failed on smoke paths"
log(f" {n_smoke} paths ran clean")
log("computing canonical case labels")
cases = {
"beta_3_2_mo_0.7": pop(("beta", 3, 2), 0.7)["case"],
"bern_0.6_mo_0.7": pop(("bernoulli", 0.6), 0.7)["case"],
"bern_0.6_mo_0.2": pop(("bernoulli", 0.6), 0.2)["case"],
}
log(f" cases = {cases}")
out = {
"dual_vs_primal_max_abs_err": dual_vs_primal_max_abs_err,
"bernoulli_fastpath_max_abs_err": bernoulli_fastpath_max_abs_err,
"klinf_path_vs_pointwise_max_abs_err": klinf_path_vs_pointwise_max_abs_err,
"ht_bound_violations": ht_bound_violations,
"beta_phi_closed_form_max_rel_err": beta_phi_closed_form_max_rel_err,
"determinism_jobcores_1_vs_2": determinism_jobcores_1_vs_2,
"cases": cases,
}
os.makedirs(RESULTS_DIR, exist_ok=True)
out_path = os.path.join(RESULTS_DIR, "exp00_selfcheck.json")
with open(out_path, "w") as f:
json.dump(out, f, indent=2)
elapsed = time.time() - t0
print(f"exp00 self-check complete in {elapsed:.1f}s -> {out_path}")
print(f" dual_vs_primal_max_abs_err = {dual_vs_primal_max_abs_err:.3e}")
print(f" bernoulli_fastpath_max_abs_err = {bernoulli_fastpath_max_abs_err:.3e}")
print(f" klinf_path_vs_pointwise_max_abs_err = {klinf_path_vs_pointwise_max_abs_err:.3e}")
print(f" ht_bound_violations = {ht_bound_violations}")
print(f" beta_phi_closed_form_max_rel_err = {beta_phi_closed_form_max_rel_err:.3e}")
print(f" determinism_jobcores_1_vs_2 = {determinism_jobcores_1_vs_2}")
print(f" cases = {cases}")
if __name__ == "__main__":
main()
|