#!/usr/bin/env python3 """Deterministic three-round self-generated-pilot experiment. First reveal all fair representative bits. Next reveal a uniformly random, unrecorded pilot subset of c partner bits, then reveal all remaining partners. Every head is frozen at the beginning of its batch. A hidden uniform subset makes the output exchangeable, so mismatch-count TV equals full-output TV. All calculations below are floating-point finite sums, not proof certificates. """ from __future__ import annotations import argparse from fractions import Fraction from itertools import combinations, product import json import math from pathlib import Path import platform import time import numpy as np import scipy from scipy.special import logsumexp from scipy.stats import binom DEFAULTS = { "n_values": [64, 256, 1024, 4096], "tau": 0.25, "w": 0.125, "delta": 0.25, "lambda": 0.2, "logspace_count": 12, "block_size": 64, } def make_models(tau: float, w: float, delta: float, lam: float) -> dict: if not (0 < tau < 1 and 0 < w < 1 and 0 < delta < 1 - tau): raise ValueError("Require 0 < tau,w < 1 and 0 < delta < 1-tau") if not 0 < lam <= 1: raise ValueError("Require 0 < lambda <= 1") small_delta = delta * (w / 2) * lam specifications = { "single": ([1 - w, w], [tau, tau + delta]), "ladder": ([1 - w, w / 2, w / 2], [tau, tau + delta, tau + small_delta]), "drift_matched_single": ([1 - w, w], [tau, tau + (delta + small_delta) / 2]), } return { name: {"weights": weights, "probs": probs, "initial_drift": float(np.dot(weights, probs) - tau)} for name, (weights, probs) in specifications.items() } def posterior_table(c: int, weights, probs): """Mixture posterior given c completed pairs with m mismatches.""" m = np.arange(c + 1, dtype=float) probs = np.asarray(probs, dtype=float) log_post = ( np.log(np.asarray(weights, dtype=float))[None, :] + m[:, None] * np.log(probs)[None, :] + (c - m[:, None]) * np.log1p(-probs)[None, :] ) log_post -= logsumexp(log_post, axis=1, keepdims=True) posterior = np.exp(log_post) return posterior, posterior @ probs def pilot_output(n: int, c: int, weights, probs, block_size: int = 64): """Full deterministic count law; no deliberate probability-tail pruning.""" if not 0 <= c <= n: raise ValueError("Pilot size must be between zero and n") p0 = float(np.dot(weights, probs)) pilot_pmf = binom.pmf(np.arange(c + 1), c, p0) posterior, heads = posterior_table(c, weights, probs) if c == n: return pilot_pmf.copy(), pilot_pmf, posterior, heads tail_n = n - c tail_counts = np.arange(tail_n + 1) q = np.zeros(n + 1) for start in range(0, c + 1, block_size): stop = min(c + 1, start + block_size) conditional = binom.pmf(tail_counts[None, :], tail_n, heads[start:stop, None]) conditional *= pilot_pmf[start:stop, None] for row, m in enumerate(range(start, stop)): q[m:m + tail_n + 1] += conditional[row] return q, pilot_pmf, posterior, heads def model_metrics(n: int, tau: float, weights, probs) -> dict: counts = np.arange(n + 1, dtype=float) teacher = binom.pmf(counts, n, tau) probabilities = np.asarray(probs, dtype=float) weights = np.asarray(weights, dtype=float) log_ratios = ( counts[:, None] * np.log(probabilities / tau)[None, :] + (n - counts[:, None]) * np.log((1 - probabilities) / (1 - tau))[None, :] ) kl_terms = -logsumexp(np.log(weights)[None, :] + log_ratios, axis=1) actual_kl = float(np.dot(teacher, kl_terms)) model_pmf = sum(float(weight) * binom.pmf(counts, n, float(prob)) for weight, prob in zip(weights, probabilities)) return { "actual_kl": actual_kl, "kl_upper_bound": float(-np.log(weights[0])), "model_tv": float(np.abs(model_pmf - teacher).sum() / 2), "teacher_mass_residual": float(abs(teacher.sum() - 1)), "model_mass_residual": float(abs(model_pmf.sum() - 1)), } def weighted_quantiles(values, weights, quantiles=(0.1, 0.5, 0.9)) -> list: order = np.argsort(values, kind="stable") values = np.asarray(values)[order] cumulative = np.cumsum(np.asarray(weights)[order]) cumulative /= cumulative[-1] return [float(values[min(len(values) - 1, np.searchsorted(cumulative, q, side="left"))]) for q in quantiles] def pilot_sizes(n: int, logspace_count: int) -> list[int]: if n < 1: raise ValueError("n must be a positive integer") sizes = {0, n} if n > 1: sizes.update(round(x) for x in np.geomspace(1, n - 1, logspace_count)) sizes.update(round(x) for x in (n ** 0.25, np.sqrt(n), n ** 0.75, n / 2)) return sorted(c for c in sizes if 0 <= c <= n) def summarize_case(n, c, tau, weights, probs, block_size=64): q, pilot_pmf, posterior, heads = pilot_output(n, c, weights, probs, block_size) teacher = binom.pmf(np.arange(n + 1), n, tau) drift = heads - tau initial_drift = float(np.dot(weights, probs) - tau) quantiles = weighted_quantiles(drift, pilot_pmf) statistics = { "n": n, "c": c, "tv": float(np.abs(q - teacher).sum() / 2), "normalization_residual": float(abs(q.sum() - 1)), "pilot_mass_residual": float(abs(pilot_pmf.sum() - 1)), "posterior_row_mass_residual": float(np.max(abs(posterior.sum(axis=1) - 1))), "posterior_mean_weights": (pilot_pmf @ posterior).tolist(), "drift_quantiles": dict(zip(("q10", "q50", "q90"), quantiles)), "mean_drift": float(np.dot(pilot_pmf, drift)), "prob_drift_gt_half_initial": float(pilot_pmf[drift > initial_drift / 2].sum()), "initial_drift": initial_drift, "pilot_p0": float(np.dot(weights, probs)), } diagnostic = { "n": n, "c": c, "pilot_m": list(range(c + 1)), "pilot_pmf": pilot_pmf.tolist(), "posterior": posterior.tolist(), "heads": heads.tolist(), "drift": drift.tolist(), "output_count_pmf": q.tolist(), "teacher_count_pmf": teacher.tolist(), } return statistics, diagnostic def validate() -> dict: """Independent rational full-label check, averaged over every pilot subset. Each literal output (A,B) is summed over uniformly random subsets J. Conditional heads here use direct rational likelihood products, whereas the production count calculation uses floating-point log posterior updates. """ models = make_models(0.25, 0.125, 0.25, 0.2) tau = Fraction(1, 4) max_atom_residual = 0.0 max_tv_residual = 0.0 max_mass_residual = 0.0 literal_atom_checks = 0 case_count = 0 for model in models.values(): weights = [Fraction(str(x)) for x in model["weights"]] probs = [Fraction(str(x)) for x in model["probs"]] p0 = sum(w * p for w, p in zip(weights, probs)) for n in range(1, 5): for c in range(n + 1): q, _, _, _ = pilot_output(n, c, model["weights"], model["probs"]) subsets = tuple(combinations(range(n), c)) full_tv = Fraction(0) full_mass = Fraction(0) for a in product((0, 1), repeat=n): for b in product((0, 1), repeat=n): e = tuple(x ^ y for x, y in zip(a, b)) s = sum(e) output_probability = Fraction(0) for subset in subsets: m = sum(e[i] for i in subset) likelihoods = [w * p ** m * (1 - p) ** (c - m) for w, p in zip(weights, probs)] p_head = sum(l * p for l, p in zip(likelihoods, probs)) / sum(likelihoods) output_probability += ( p0 ** m * (1 - p0) ** (c - m) * p_head ** (s - m) * (1 - p_head) ** (n - c - s + m) ) / len(subsets) output_probability /= 2 ** n teacher_probability = tau ** s * (1 - tau) ** (n - s) / 2 ** n full_mass += output_probability full_tv += abs(output_probability - teacher_probability) / 2 count_atom_probability = float(q[s]) / math.comb(n, s) / 2 ** n max_atom_residual = max(max_atom_residual, abs(float(output_probability) - count_atom_probability)) literal_atom_checks += 1 count_tv = np.abs(q - binom.pmf(np.arange(n + 1), n, float(tau))).sum() / 2 max_tv_residual = max(max_tv_residual, abs(float(full_tv) - count_tv)) max_mass_residual = max(max_mass_residual, abs(float(full_mass) - 1)) assert full_mass == 1 case_count += 1 # Endpoint schedules both reduce to independent draws at the initial head. endpoint_residual = 0.0 for model in models.values(): for n in (1, 7, 32): reference = binom.pmf(np.arange(n + 1), n, np.dot(model["weights"], model["probs"])) for c in (0, n): q, _, _, _ = pilot_output(n, c, model["weights"], model["probs"]) endpoint_residual = max(endpoint_residual, float(np.max(abs(q - reference)))) tolerance = 2e-12 assert max_atom_residual < tolerance, max_atom_residual assert max_tv_residual < tolerance, max_tv_residual assert endpoint_residual < tolerance, endpoint_residual independent_reference_tvs = { "single": 0.05413154766773641, "ladder": 0.027308808315495564, "drift_matched_single": 0.027628599041908977, } reference_cases = {} for name, model in models.items(): stats, _ = summarize_case(4, 2, 0.25, model["weights"], model["probs"]) assert abs(stats["tv"] - independent_reference_tvs[name]) < tolerance reference_cases[name] = stats return { "status": "passed", "cases": case_count, "literal_atom_checks": literal_atom_checks, "max_atom_residual": max_atom_residual, "max_tv_residual": max_tv_residual, "max_exact_full_mass_residual": max_mass_residual, "max_endpoint_residual": endpoint_residual, "independent_n4_c2_references": reference_cases, "tolerance": tolerance, "scope": "n=1..4 full labelled laws with rational pilot-subset averaging; not a theorem proof", } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", type=Path) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--validate-only", action="store_true") args = parser.parse_args() config = dict(DEFAULTS) if args.config: document = json.loads(args.config.read_text()) config.update(document.get("e2", {})) if int(config["block_size"]) < 1: raise ValueError("block_size must be positive") start = time.perf_counter() validation = validate() result = { "experiment": "E2_three_round_self_generated_pilot", "metadata": { "config": config, "python": platform.python_version(), "numpy": np.__version__, "scipy": scipy.__version__, "computation": "deterministic full finite sums in float64; no deliberate tail pruning", "pilot_sampling_law": "Binomial(c, sum_j weights_j * probs_j), not teacher sampling", "symmetry": "hidden uniform pilot subset; pair permutations and fair representative bits imply full TV equals count TV", "scope": "specified three-round schedule family, not optimal all-policy error", "numerical_caveat": "normalization residuals are diagnostics, not certified floating-point error bounds; binomial underflow may occur", }, "validation": validation, "models": {}, "model_statistics": [], "records": [], "diagnostics": [], } print(json.dumps({"phase": "validation", **validation}), flush=True) if not args.validate_only: models = make_models(float(config["tau"]), float(config["w"]), float(config["delta"]), float(config["lambda"])) result["models"] = models for n in config["n_values"]: n = int(n) for name, model in models.items(): metrics = model_metrics(n, config["tau"], model["weights"], model["probs"]) result["model_statistics"].append({"model": name, "n": n, **metrics}) for c in pilot_sizes(n, int(config["logspace_count"])): case_start = time.perf_counter() record, diagnostic = summarize_case( n, c, config["tau"], model["weights"], model["probs"], int(config["block_size"])) record.update({"model": name, "runtime_seconds": time.perf_counter() - case_start}) if record["normalization_residual"] > 1e-9: raise ArithmeticError(f"Count normalization failed: {name=}, {n=}, {c=}") result["records"].append(record) if n == 1024 and c == 32: result["diagnostics"].append({"model": name, **diagnostic}) records = [r for r in result["records"] if r["model"] == name and r["n"] == n] best = min(records, key=lambda r: r["tv"]) print(json.dumps({"phase": "grid_progress", "n": n, "model": name, "cases": len(records), "best_grid_c": best["c"], "best_grid_tv": best["tv"], **metrics}), flush=True) result["metadata"]["runtime_seconds"] = time.perf_counter() - start args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") print(json.dumps({"phase": "complete", "output": str(args.output), "records": len(result["records"]), "runtime_seconds": result["metadata"]["runtime_seconds"]}), flush=True) if __name__ == "__main__": main()