#!/usr/bin/env python3 """exp00_core -- build + self-test the shared core/ library (specs/exp00_core.md). This experiment has no results file of its own (it is a shared library used by exp01-exp06). Running this script imports every core/ module and exercises it with correctness checks; it exits non-zero if anything is wrong. """ import argparse import itertools import math import os import sys import time sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import numpy as np from core.cs import U_MAX, U_MIN, update_low, update_up, width from core.instance import gini_w, make_instance from core.oracles import oracle from core.parallel import get_n_jobs, run_grid from core.rounding import dependent_round from core.swf import lipschitz_const, swf from core.swfucb import run as swfucb_run NEG_INF = float("-inf") def log(msg): print(f"[exp00] {msg}", file=sys.stderr, flush=True) def check(name, cond, detail=""): if not cond: raise AssertionError(f"FAILED: {name} {detail}") log(f"ok: {name} {detail}") # --------------------------------------------------------------------- swf def test_swf_formulas(): v = np.array([0.4, 0.6, 1.0]) w = np.array([0.2, 0.3, 0.5]) check("wpm q=-inf == min", math.isclose(swf(v, "wpm", w, NEG_INF), 0.4)) check("wpm q=1 == weighted mean", math.isclose(swf(v, "wpm", w, 1.0), float(np.sum(w * v)))) geo = math.exp(float(np.sum(w * np.log(v)))) check("wpm q=0 == weighted geomean", math.isclose(swf(v, "wpm", w, 0.0), geo)) v0 = np.array([0.0, 0.6, 1.0]) check("wpm q=0 with a zero -> 0", swf(v0, "wpm", w, 0.0) == 0.0) check("wpm q=-1 with a zero -> 0", swf(v0, "wpm", w, -1.0) == 0.0) check("kolm q=-inf == min", math.isclose(swf(v, "kolm", w, NEG_INF), 0.4)) check("kolm q=0 == weighted mean", math.isclose(swf(v, "kolm", w, 0.0), float(np.sum(w * v)))) q = -2.0 expected = (1.0 / q) * math.log(float(np.sum(w * np.exp(q * v)))) check("kolm q=-2 matches direct logsumexp", math.isclose(swf(v, "kolm", w, q), expected, rel_tol=1e-9)) w_gini = np.array([0.5, 0.3, 0.2]) # non-increasing, paired with ascending v order = np.argsort(v) expected_gini = float(np.sum(w_gini * v[order])) check("gini == sum over ascending order", math.isclose(swf(v, "gini", w_gini), expected_gini)) check("lipschitz wpm", math.isclose(lipschitz_const("wpm", w, 0.1, 1.0), 10.0)) check("lipschitz kolm", lipschitz_const("kolm", w, 0.1, 1.0) == 1.0) check("lipschitz gini", math.isclose(lipschitz_const("gini", w, 0.1, 1.0), float(np.sum(w)))) # ----------------------------------------------------------------- oracles def _brute_force_best(u, family, w, q, k, grid_n=60000, rng=None): """Cross-check via random feasible search on small n (n<=6).""" n = len(u) rng = rng or np.random.default_rng(0) best = -math.inf for _ in range(grid_n): raw = rng.random(n) # random feasible p: pick k "mass units" via Dirichlet-ish random split # then rescale to sum k, clipped to [0,1] via a few water-filling passes p = np.zeros(n) rem = float(k) order = rng.permutation(n) weights = raw / raw.sum() p = np.clip(weights * k, 0.0, 1.0) # fix sum via simple rescale/clip iterations for _ in range(20): s = p.sum() if abs(s - k) < 1e-9: break free = (p > 1e-9) & (p < 1 - 1e-9) if not np.any(free): break adj = (k - s) / max(np.sum(free), 1) p[free] = np.clip(p[free] + adj, 0.0, 1.0) if abs(p.sum() - k) > 1e-6: continue val = swf(u * p, family, w, q) if val > best: best = val return best def test_oracles_feasibility_and_optimality(): n, k = 6, 3 configs = [] for family, qs in [ ("wpm", [NEG_INF, -2.0, -0.5, 0.0, 0.5, 1.0]), ("kolm", [NEG_INF, -2.0, -0.5, 0.0]), ("gini", [None]), ]: for q in qs: configs.append((family, q, len(configs))) def _one(cfg): family, q, seed_idx = cfg local_rng = np.random.default_rng(1000 + seed_idx) u = local_rng.uniform(0.1, 1.0, n) if family == "gini": w = np.sort(local_rng.uniform(0.5, 2.0, n))[::-1] w = w / w.sum() else: w = local_rng.uniform(0.5, 2.0, n) w = w / w.sum() p = oracle(u, family, w, q, k) feas_ok = bool(np.all(p >= -1e-9) and np.all(p <= 1 + 1e-9) and abs(p.sum() - k) < 1e-8) val = swf(u * p, family, w, q) return dict(family=family, q=q, feas_ok=feas_ok, val=val, u=u, w=w) results = run_grid(_one, configs) for r in results: check(f"oracle feasible ({r['family']}, q={r['q']})", r["feas_ok"]) check(f"oracle objective finite ({r['family']}, q={r['q']})", math.isfinite(r["val"])) # optimality cross-check against random search: one config per family (not just # the first 3, which were all wpm and never exercised the gini oracle -- gini's # exact Algorithm 4 pseudocode is a single shrinking block, which a literal # reading implements straightforwardly; empirically that literal reading is # badly suboptimal (loses >0.5 SWF units to random search on adversarial cases) # because it lets the induced v=u*p reorder relative to the u-rank the w vector # is pinned to. core/oracles.py fixes this via PAVA block-pooling, verified here # and cross-checked against brute-force random search to confirm it, not just # beat, the naive reading. check_configs = [results[0], results[6], results[10]] assert {r["family"] for r in check_configs} == {"wpm", "kolm", "gini"} for r in check_configs: rs_best = _brute_force_best(r["u"], r["family"], r["w"], r["q"], k, grid_n=4000, rng=np.random.default_rng(7)) check( f"oracle >= random-search best ({r['family']}, q={r['q']})", r["val"] >= rs_best - 1e-6, f"(oracle={r['val']:.6f}, random={rs_best:.6f})", ) # ---------------------------------------------------------------- rounding def test_dependent_round(): rng = np.random.default_rng(1) p = np.array([0.3, 0.7, 0.5, 0.5, 1.0, 0.0]) k = int(round(p.sum())) trials = 4000 counts = np.zeros(len(p)) for _ in range(trials): S = dependent_round(p, rng) check("dependent_round size == k", int(S.sum()) == k) counts += S marginals = counts / trials check( "dependent_round marginals ~ p", bool(np.all(np.abs(marginals - p) < 0.05)), f"(marginals={marginals}, p={p})", ) # --------------------------------------------------------------------- cs def test_cs(): n, delta = 50, 0.1 w0 = width(0, n, delta) check("width(N=0) finite and positive", math.isfinite(w0) and w0 > 0, f"={w0}") w1 = width(1, n, delta) w10 = width(10, n, delta) check("width decreasing in N", w0 > w1 > w10, f"({w0},{w1},{w10})") mu_hat_new = 0.5 up = update_up(mu_hat_new, 5, n, delta) low = update_low(mu_hat_new, 5, n, delta) check("update_up clipped to U_MAX", up <= U_MAX + 1e-12) check("update_low clipped to U_MIN", low >= U_MIN - 1e-12) check("update_up >= update_low", up >= low) # ---------------------------------------------------------------- instance def test_instance(): n = 50 inst_e = make_instance(n, "exp") inst_l = make_instance(n, "linear") check("mu in (0.1,1.0) exp", bool(np.all(inst_e["mu"] > 0.1) and np.all(inst_e["mu"] < 1.0))) check("weights sum to 1 (exp)", math.isclose(inst_e["w"].sum(), 1.0, abs_tol=1e-9)) check("weights sum to 1 (linear)", math.isclose(inst_l["w"].sum(), 1.0, abs_tol=1e-9)) check("exp weights non-increasing", bool(np.all(np.diff(inst_e["w"]) <= 1e-15))) check("linear weights increasing", bool(np.all(np.diff(inst_l["w"]) >= -1e-15))) inst_e2 = make_instance(n, "exp") check("instance draws deterministic (seed=0 fixed)", bool(np.allclose(inst_e["alpha"], inst_e2["alpha"]))) gw_e = gini_w(inst_e["w"], "exp") gw_l = gini_w(inst_l["w"], "linear") check("gini_w exp == as-is", bool(np.array_equal(gw_e, inst_e["w"]))) check("gini_w linear == reversed", bool(np.array_equal(gw_l, inst_l["w"][::-1]))) check("gini_w linear now non-increasing", bool(np.all(np.diff(gw_l) <= 1e-15))) # ---------------------------------------------------------------- swfucb def test_swfucb(n, T, k): checkpoints = sorted({max(1, T // 4), max(1, T // 2), T}) def _one(cfg): family, weight_decay, q = cfg inst = make_instance(n, weight_decay) out = swfucb_run(inst, family, q, k, T, delta=0.1, seed=0, checkpoints=checkpoints) return dict(family=family, weight_decay=weight_decay, q=q, out=out) configs = [ ("wpm", "exp", 0.0), ("kolm", "exp", NEG_INF), ("gini", "linear", None), ] results = run_grid(_one, configs) for r in results: out = r["out"] tag = f"({r['family']}, {r['weight_decay']}, q={r['q']})" vals = list(out["regret_at_checkpoints"].values()) check(f"swfucb checkpoints recorded {tag}", len(vals) == len(checkpoints), out["regret_at_checkpoints"]) check(f"swfucb regret finite {tag}", all(math.isfinite(x) for x in vals)) check(f"swfucb regret non-decreasing {tag}", all(b >= a - 1e-6 for a, b in zip(vals, vals[1:]))) check(f"swfucb regret >= -1e-6 {tag}", all(x >= -1e-6 for x in vals)) check(f"swfucb sum_p_total == k*T {tag}", math.isclose(out["sum_p_total"], k * T, rel_tol=1e-6)) check(f"swfucb W_star finite {tag}", math.isfinite(out["W_star"])) def main(): ap = argparse.ArgumentParser() ap.add_argument("--toy", action="store_true") args = ap.parse_args() t0 = time.time() log(f"JOB_CORES={get_n_jobs()} numpy={np.__version__} toy={args.toy}") log("running swf formula checks...") test_swf_formulas() log("running oracle feasibility/optimality checks...") test_oracles_feasibility_and_optimality() log("running dependent_round checks...") test_dependent_round() log("running cs.py checks (incl. N=0 guard)...") test_cs() log("running instance.py checks...") test_instance() n, T, k = (10, 40, 3) if args.toy else (50, 200, 5) log(f"running swfucb end-to-end checks (n={n}, T={T}, k={k})...") test_swfucb(n, T, k) elapsed = time.time() - t0 print(f"exp00_core self-test PASSED in {elapsed:.1f}s (toy={args.toy}, n_jobs={get_n_jobs()})") print("modules ok: swf, oracles, rounding, cs, instance, swfucb, parallel") return 0 if __name__ == "__main__": sys.exit(main())