#!/usr/bin/env python3 """exp01_theory — numerical verification of Claims 1, 2, 3 (theory). Part A: remainder scaling on P_quartic (D1a, D1b). Part B: measure convergence & flatness bias on P_dw (D2a, D2b, D2c) -> Claim 1. Part C: discretization / excess-risk rates on P_dw (D3, D4) -> Claims 2, 3. numpy/scipy/joblib only. CPU only. See specs/exp01_theory.md for the exact contract. """ import os # must precede numpy import: one BLAS thread per joblib worker for _v in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS"): os.environ.setdefault(_v, "1") import argparse import json import math import sys import time import numpy as np from scipy.optimize import curve_fit from joblib import Parallel, delayed ROOT = os.path.dirname(os.path.abspath(__file__)) BASE = os.path.dirname(ROOT) WORK_DIR = os.path.join(BASE, "work") RESULTS_DIR = os.path.join(BASE, "results") ETA = 0.1 def log(msg): print(msg, file=sys.stderr, flush=True) # --------------------------------------------------------------------------- P_quartic def quartic_g_sigma(theta, sigma): return theta ** 4 + 6 * theta ** 2 * sigma ** 2 + 3 * sigma ** 4 def quartic_v(theta, sigma): return theta ** 4 + 6 * theta ** 2 * sigma ** 2 # --------------------------------------------------------------------------- P_dw # u(theta) = 0.5*(theta^2-1)^2 - 0.6*exp(-8*(theta-1)^2) def dw_u(theta): return 0.5 * (theta ** 2 - 1) ** 2 - 0.6 * np.exp(-8 * (theta - 1) ** 2) def dw_up(theta): # d/dtheta [0.5(t^2-1)^2] = 2t(t^2-1) # d/dtheta [-0.6 exp(-8(t-1)^2)] = 9.6(t-1) exp(-8(t-1)^2) return 2 * theta * (theta ** 2 - 1) + 9.6 * (theta - 1) * np.exp(-8 * (theta - 1) ** 2) def dw_upp(theta): g = np.exp(-8 * (theta - 1) ** 2) return 6 * theta ** 2 - 2 + g * (9.6 - 153.6 * (theta - 1) ** 2) def _dw_up_scalar(theta): g = math.exp(-8.0 * (theta - 1.0) ** 2) return 2.0 * theta * (theta ** 2 - 1.0) + 9.6 * (theta - 1.0) * g def dw_v(theta, sigma): return dw_u(theta) + 0.5 * sigma ** 2 * dw_upp(theta) _GH_NODES, _GH_WEIGHTS = np.polynomial.hermite.hermgauss(256) def dw_g_sigma(theta, sigma): """E_eps~N(0,sigma^2)[u(theta+eps)] via 256-node Gauss-Hermite quadrature.""" theta = np.atleast_1d(np.asarray(theta, dtype=float)) x = theta[:, None] + math.sqrt(2.0) * sigma * _GH_NODES[None, :] vals = dw_u(x) out = (vals * _GH_WEIGHTS[None, :]).sum(axis=1) / math.sqrt(math.pi) return out # --------------------------------------------------------------------------- density / distance helpers def normalize_density(vals, dtheta): logw = -np.asarray(vals, dtype=float) # vals passed in are already the exponent argument's negative (i.e. -beta*f); shift for stability logw = logw - logw.max() w = np.exp(logw) total = w.sum() * dtheta return w / total def density_from_negpotential(neg_beta_f, dtheta): """neg_beta_f = -beta*f(theta) on the grid -> normalized pdf.""" m = neg_beta_f.max() w = np.exp(neg_beta_f - m) total = w.sum() * dtheta return w / total def kl_divergence(p, q, dtheta): mask = p > 0 return float(np.sum(p[mask] * np.log(p[mask] / np.maximum(q[mask], 1e-300)) * dtheta)) def cdf_from_pdf(pdf, dtheta): cdf = np.cumsum(pdf) * dtheta return cdf / cdf[-1] def inv_cdf_from_grid(theta, cdf, q_levels): cdf_u, idx = np.unique(cdf, return_index=True) theta_u = theta[idx] return np.interp(q_levels, cdf_u, theta_u) def wasserstein2_grid(theta, pdf1, pdf2, dtheta, q_levels): c1 = cdf_from_pdf(pdf1, dtheta) c2 = cdf_from_pdf(pdf2, dtheta) x1 = inv_cdf_from_grid(theta, c1, q_levels) x2 = inv_cdf_from_grid(theta, c2, q_levels) return float(math.sqrt(np.trapezoid((x1 - x2) ** 2, q_levels))) def empirical_cdf_on_grid(samples, theta_grid): s = np.sort(samples) idx = np.searchsorted(s, theta_grid, side="right") return idx / len(samples) def w1_from_cdfs(cdf1, cdf2, dtheta): return float(np.sum(np.abs(cdf1 - cdf2)) * dtheta) def w2_from_samples_and_ref(samples, ref_inv_cdf, q_levels): emp_inv_cdf = np.quantile(samples, q_levels) return float(math.sqrt(np.trapezoid((emp_inv_cdf - ref_inv_cdf) ** 2, q_levels))) # --------------------------------------------------------------------------- fSGLD engine (P_dw) def run_fsgld_chain(beta, sigma, lam, n_steps, burn_in, seed, theta0=0.0): """theta_{k+1} = theta_k - lam*u'(theta_k+eps_k) + sqrt(2*lam/beta)*xi_k. Returns the full post-init trajectory (length n_steps) so callers can slice burn-in or cumulative-from-0 windows as needed. """ rng = np.random.default_rng(seed) eps_all = rng.normal(0.0, sigma, size=n_steps) xi_all = rng.normal(0.0, 1.0, size=n_steps) noise_scale = math.sqrt(2.0 * lam / beta) theta = float(theta0) traj = np.empty(n_steps, dtype=float) for k in range(n_steps): grad = _dw_up_scalar(theta + eps_all[k]) theta = theta - lam * grad + noise_scale * xi_all[k] traj[k] = theta return traj # --------------------------------------------------------------------------- Part A def compute_part_a(): theta_grid_check = np.array([0.3, 0.7, 1.0]) sigma_grid = np.logspace(-3, -1, 9) residual_per_theta = np.abs( quartic_g_sigma(theta_grid_check[None, :], sigma_grid[:, None]) - quartic_v(theta_grid_check[None, :], sigma_grid[:, None]) ) # residual is theta-independent (=3*sigma^4 exactly); verify internally spread = residual_per_theta.std(axis=1) / np.maximum(residual_per_theta.mean(axis=1), 1e-300) if np.max(spread) > 1e-6: log(f"WARNING: D1a residual not theta-independent, max relative spread={np.max(spread):.2e}") residual_D1a = residual_per_theta.mean(axis=1) slope_D1a = float(np.polyfit(np.log(sigma_grid), np.log(residual_D1a), 1)[0]) beta_grid = np.logspace(1, 6, 11) theta_fixed = 0.7 sigma_b = beta_grid ** (-(1 + ETA) / 4) residual_b = np.abs(quartic_g_sigma(theta_fixed, sigma_b) - quartic_v(theta_fixed, sigma_b)) beta_residual_D1b = beta_grid * residual_b slope_D1b = float(np.polyfit(np.log(beta_grid), np.log(beta_residual_D1b), 1)[0]) return { "slope_D1a": slope_D1a, "slope_D1b": slope_D1b, "sigma_grid": sigma_grid.tolist(), "residual_D1a": residual_D1a.tolist(), "beta_grid": beta_grid.tolist(), "beta_residual_D1b": beta_residual_D1b.tolist(), } # --------------------------------------------------------------------------- Part B def compute_part_b(toy, theta_grid, dtheta, q_levels): beta_grid = np.logspace(0, 3, 10) KL_list, W2_list = [], [] for beta in beta_grid: sigma = beta ** (-(1 + ETA) / 4) v_vals = dw_v(theta_grid, sigma) g_vals = dw_g_sigma(theta_grid, sigma) p_fs = density_from_negpotential(-beta * g_vals, dtheta) p_star = density_from_negpotential(-beta * v_vals, dtheta) KL_list.append(kl_divergence(p_fs, p_star, dtheta)) W2_list.append(wasserstein2_grid(theta_grid, p_fs, p_star, dtheta, q_levels)) KL = np.array(KL_list) W2 = np.array(W2_list) slope_logKL_logbeta = float(np.polyfit(np.log(beta_grid), np.log(np.maximum(KL, 1e-300)), 1)[0]) KL_monotone_decreasing = bool(np.all(np.diff(KL) <= 1e-9 * max(KL.max(), 1.0))) # D2a: sampled surrogate check at beta=50 beta50 = 50.0 sigma50 = beta50 ** (-(1 + ETA) / 4) n_steps_d2a = 2000 if toy else int(2e6) burn_in_d2a = int(0.1 * n_steps_d2a) lam_d2a = 5e-4 t0 = time.time() traj = run_fsgld_chain(beta50, sigma50, lam_d2a, n_steps_d2a, burn_in_d2a, seed=0) samples = traj[burn_in_d2a:] log(f"[partB D2a] n_steps={n_steps_d2a} wall={time.time()-t0:.2f}s") edges = np.linspace(-3, 3, 81) centers = 0.5 * (edges[:-1] + edges[1:]) binwidth = edges[1] - edges[0] hist_density, _ = np.histogram(samples, bins=edges, density=True) g_centers = dw_g_sigma(centers, sigma50) p_target_bins = density_from_negpotential(-beta50 * g_centers, binwidth) mask = hist_density > 0 KL_emp = float(np.sum(hist_density[mask] * np.log(hist_density[mask] / np.maximum(p_target_bins[mask], 1e-300)) * binwidth)) # D2c: flatness bias at beta=50 v_vals50 = dw_v(theta_grid, sigma50) u_vals = dw_u(theta_grid) p_star50 = density_from_negpotential(-beta50 * v_vals50, dtheta) p_u50 = density_from_negpotential(-beta50 * u_vals, dtheta) mass_flat_pistar = float(np.sum(p_star50[theta_grid < 0]) * dtheta) mass_flat_expu = float(np.sum(p_u50[theta_grid < 0]) * dtheta) flatness_bias_real = bool(mass_flat_pistar > mass_flat_expu) return { "beta_grid": beta_grid.tolist(), "KL": KL.tolist(), "W2": W2.tolist(), "slope_logKL_logbeta": slope_logKL_logbeta, "KL_monotone_decreasing": KL_monotone_decreasing, "KL_emp_surrogate": KL_emp, "mass_flat_pistar": mass_flat_pistar, "mass_flat_expu": mass_flat_expu, "flatness_bias_real": flatness_bias_real, } # --------------------------------------------------------------------------- Part C def compute_lambda_max_est(theta_grid, beta_C): u_vals = dw_u(theta_grid) min_u = u_vals.min() cutoff = 20.0 / beta_C # mass-relevant region: exp(-beta*cutoff) ~ 2e-9, negligible tail mask = (u_vals - min_u) <= cutoff L = float(np.max(np.abs(dw_upp(theta_grid[mask])))) return 1.0 / L def run_one_partC_chain(lam, seed, beta_C, sigma_C, n_steps, burn_in, theta_grid, dtheta, cdf_ref, inv_cdf_ref, q_levels, min_v_C, ckpt_path): t0 = time.time() traj = run_fsgld_chain(beta_C, sigma_C, lam, n_steps, burn_in, seed=seed) samples = traj[burn_in:] cdf_emp = empirical_cdf_on_grid(samples, theta_grid) W1 = w1_from_cdfs(cdf_emp, cdf_ref, dtheta) W2 = w2_from_samples_and_ref(samples, inv_cdf_ref, q_levels) excess = float(np.mean(dw_v(samples, sigma_C)) - min_v_C) row = {"part": "C", "lambda": lam, "seed": seed, "W1": W1, "W2": W2, "excess": excess, "n_steps": n_steps} with open(ckpt_path, "w") as f: json.dump(row, f) log(f"[partC] lambda={lam:.6f} seed={seed} n_steps={n_steps} wall={time.time()-t0:.2f}s " f"W1={W1:.4f} W2={W2:.4f} excess={excess:.4f}") return row def power_fit(x, y): x = np.asarray(x, dtype=float) y = np.asarray(y, dtype=float) def model(x, D, B, p): return D + B * np.power(x, p) p0 = [max(y.min() * 0.5, 0.0), max(y.max() - y.min(), 1e-6), 0.3] try: popt, _ = curve_fit(model, x, y, p0=p0, bounds=([0, 0, 0], [np.inf, np.inf, np.inf]), maxfev=20000) D, B, p = (float(v) for v in popt) except Exception as e: log(f"WARNING: power_fit curve_fit failed ({e}); falling back to log-log slope, floor=0") D = 0.0 slope, _ = np.polyfit(np.log(x), np.log(np.maximum(y, 1e-300)), 1) p = float(slope) B = float(np.exp(np.polyfit(np.log(x), np.log(np.maximum(y, 1e-300)), 1)[1])) return D, B, p def compute_part_c(toy, job_cores): theta_grid = np.linspace(-3, 3, 4000) dtheta = theta_grid[1] - theta_grid[0] q_levels = np.linspace(0.0005, 0.9995, 1024) beta_C = 30.0 sigma_C = beta_C ** (-(1 + ETA) / 4) lambda_max_est = compute_lambda_max_est(theta_grid, beta_C) log(f"[partC] lambda_max_est={lambda_max_est:.5f}") lambda_grid = [0.001, 0.002, 0.004, 0.008, 0.016, 0.032] seeds = [0, 1] if toy else [0, 1, 2] g_vals_C = dw_g_sigma(theta_grid, sigma_C) p_ref = density_from_negpotential(-beta_C * g_vals_C, dtheta) cdf_ref = cdf_from_pdf(p_ref, dtheta) inv_cdf_ref = inv_cdf_from_grid(theta_grid, cdf_ref, q_levels) v_vals_C = dw_v(theta_grid, sigma_C) min_v_C = float(v_vals_C.min()) prefix = "exp01_toy" if toy else "exp01" n_steps_c = 3000 if toy else 500000 # full: max(500000, ceil(400/lam)) == 500000 for this grid burn_in_c = max(int(0.1 * n_steps_c), 1) pending = [] ckpt_paths = {} for lam in lambda_grid: for seed in seeds: path = os.path.join(WORK_DIR, f"{prefix}_partC_{lam:.6f}_{seed}.json") ckpt_paths[(lam, seed)] = path if not os.path.exists(path): pending.append((lam, seed)) else: log(f"[partC] skip existing checkpoint lambda={lam:.6f} seed={seed}") if pending: Parallel(n_jobs=job_cores)( delayed(run_one_partC_chain)( lam, seed, beta_C, sigma_C, n_steps_c, burn_in_c, theta_grid, dtheta, cdf_ref, inv_cdf_ref, q_levels, min_v_C, ckpt_paths[(lam, seed)] ) for lam, seed in pending ) rows = [] for lam in lambda_grid: for seed in seeds: with open(ckpt_paths[(lam, seed)]) as f: rows.append(json.load(f)) W1_mean, W2_mean, excess_mean = [], [], [] for lam in lambda_grid: lam_rows = [r for r in rows if abs(r["lambda"] - lam) < 1e-12] W1_mean.append(float(np.mean([r["W1"] for r in lam_rows]))) W2_mean.append(float(np.mean([r["W2"] for r in lam_rows]))) excess_mean.append(float(np.mean([r["excess"] for r in lam_rows]))) floor_W1, _, fit_p_W1 = power_fit(lambda_grid, W1_mean) floor_W2, _, fit_q_W2 = power_fit(lambda_grid, W2_mean) floor_excess, _, fit_r_excess = power_fit(lambda_grid, excess_mean) # k-sweep: single chain (theta0=0, no burn-in) at lambda=0.008, cumulative W1 vs k ksweep_path = os.path.join(WORK_DIR, f"{prefix}_partC_ksweep.json") if os.path.exists(ksweep_path): with open(ksweep_path) as f: k_sweep = json.load(f) log("[partC] skip existing checkpoint ksweep") else: t0 = time.time() lam_k = 0.008 k_full = [20000, 50000, 100000, 200000, 500000] n_steps_k = 3000 if toy else max(k_full) k_list = [50, 150, 400, 1200, 3000] if toy else k_full traj = run_fsgld_chain(beta_C, sigma_C, lam_k, n_steps_k, 0, seed=0) W1_k = [] for k in k_list: cdf_k = empirical_cdf_on_grid(traj[:k], theta_grid) W1_k.append(w1_from_cdfs(cdf_k, cdf_ref, dtheta)) k_sweep = {"k": k_list, "W1": W1_k} with open(ksweep_path, "w") as f: json.dump(k_sweep, f) log(f"[partC] ksweep n_steps={n_steps_k} wall={time.time()-t0:.2f}s") return { "beta": beta_C, "lambda_grid": lambda_grid, "W1_mean": W1_mean, "W2_mean": W2_mean, "excess_mean": excess_mean, "fit_p_W1": fit_p_W1, "fit_q_W2": fit_q_W2, "fit_r_excess": fit_r_excess, "floor_W1": floor_W1, "floor_W2": floor_W2, "floor_excess": floor_excess, "k_sweep": k_sweep, }, lambda_max_est, len(seeds) def main(): parser = argparse.ArgumentParser() parser.add_argument("--toy", action="store_true") args = parser.parse_args() toy = args.toy os.makedirs(WORK_DIR, exist_ok=True) os.makedirs(RESULTS_DIR, exist_ok=True) job_cores = int(os.environ.get("JOB_CORES", 4)) prefix = "exp01_toy" if toy else "exp01" t_start = time.time() partA_path = os.path.join(WORK_DIR, f"{prefix}_partA.json") if os.path.exists(partA_path): with open(partA_path) as f: partA = json.load(f) log("[partA] skip existing checkpoint") else: t0 = time.time() partA = compute_part_a() with open(partA_path, "w") as f: json.dump(partA, f) log(f"[partA] done wall={time.time()-t0:.2f}s") theta_grid = np.linspace(-3, 3, 4000) dtheta = theta_grid[1] - theta_grid[0] q_levels = np.linspace(0.0005, 0.9995, 1024) partB_path = os.path.join(WORK_DIR, f"{prefix}_partB.json") if os.path.exists(partB_path): with open(partB_path) as f: partB = json.load(f) log("[partB] skip existing checkpoint") else: t0 = time.time() partB = compute_part_b(toy, theta_grid, dtheta, q_levels) with open(partB_path, "w") as f: json.dump(partB, f) log(f"[partB] done wall={time.time()-t0:.2f}s") partC, lambda_max_est, n_seeds = compute_part_c(toy, job_cores) results = { "partA": partA, "partB": partB, "partC": partC, "meta": { "eta": ETA, "n_seeds": n_seeds, "lambda_max_est": lambda_max_est, "scale": "toy (low-dim toy)" if toy else "full (in-scale, low-dim toy)", }, } out_path = os.path.join(RESULTS_DIR, "exp01.json") with open(out_path, "w") as f: json.dump(results, f, indent=2) print(f"exp01_theory: {'TOY' if toy else 'FULL'} run complete in {time.time()-t_start:.2f}s") print(f" slope_D1a={partA['slope_D1a']:.4f} slope_D1b={partA['slope_D1b']:.4f}") print(f" slope_logKL_logbeta={partB['slope_logKL_logbeta']:.4f} KL_emp={partB['KL_emp_surrogate']:.4f} " f"flatness_bias_real={partB['flatness_bias_real']}") print(f" fit_p_W1={partC['fit_p_W1']:.4f} fit_q_W2={partC['fit_q_W2']:.4f} " f"fit_r_excess={partC['fit_r_excess']:.4f} lambda_max_est={lambda_max_est:.4f}") print(f" wrote {out_path}") if __name__ == "__main__": main()