#!/usr/bin/env python3 """Exact full-output TV benchmarks for frozen fair-pair exchangeable oracles. Only Python's standard library is required. All probabilities and reported distance comparisons use Fraction; floats are for presentation and timing. See schedule_math.md for the symmetry and full-output-TV justification. """ from __future__ import annotations import argparse from collections import defaultdict from fractions import Fraction from functools import lru_cache import hashlib from itertools import permutations, product import json import math from pathlib import Path import sys import time def shown(value): value = Fraction(value) return {"rational": str(value), "float": float(value)} def exact(value): if isinstance(value, dict): return Fraction(value["rational"]) return Fraction(value) def sha256(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def compositions(n, parts): """All ordered weak compositions, in lexicographic order.""" if parts == 1: yield (n,) return for first in range(n + 1): for rest in compositions(n - first, parts - 1): yield (first,) + rest def floor_root_power(n, exponent, root): """floor(n**(exponent/root)), by exact integer inequalities.""" if not 0 <= exponent <= root or root < 1 or n < 1: raise ValueError("Invalid integer-root arguments") target = n**exponent lo, hi = 0, n + 1 while hi - lo > 1: middle = (lo + hi) // 2 if middle**root <= target: lo = middle else: hi = middle if not lo**root <= target < (lo + 1)**root: raise AssertionError("Integer root invariant failed") return lo def geometric_batches(n, r): cumulative = [0] + [floor_root_power(n, j, r) for j in range(1, r)] + [n] return tuple(b - a for a, b in zip(cumulative, cumulative[1:])) def equal_batches(n, r): cumulative = [j * n // r for j in range(r + 1)] return tuple(b - a for a, b in zip(cumulative, cumulative[1:])) class ExactFairOracle: def __init__(self, witness): self.n = int(witness["n"]) self.tau = exact(witness["tau"]) self.weights = tuple(map(exact, witness["weights"])) self.probabilities = tuple(map(exact, witness["probabilities"])) if self.n < 1 or not 0 < self.tau < 1: raise ValueError("Need positive n and a positive teacher") if len(self.weights) != len(self.probabilities) or not self.weights: raise ValueError("Mismatching or empty mixture arrays") if sum(self.weights) != 1 or any(w < 0 for w in self.weights): raise ValueError("Weights must be nonnegative and sum exactly to one") if any(not 0 < p < 1 for p in self.probabilities): raise ValueError("Every component must be strictly positive") self.predictive = lru_cache(None)(self._predictive) self.binomial = lru_cache(None)(self._binomial) self.teacher_binomial = lru_cache(None)(lambda size: self.binomial(size, self.tau)) self.evaluate = lru_cache(None)(self._evaluate) def _predictive(self, completed, mismatches): likelihood = tuple(w * p**mismatches * (1 - p)**(completed - mismatches) for w, p in zip(self.weights, self.probabilities)) return sum(q * p for q, p in zip(likelihood, self.probabilities)) / sum(likelihood) @staticmethod def _binomial(size, rate): return tuple(Fraction(math.comb(size, m)) * rate**m * (1 - rate)**(size - m) for m in range(size + 1)) def _evaluate(self, batches): """TV on the joint vector of mismatch counts, not just its sum.""" if sum(batches) != self.n or any(b < 0 for b in batches): raise ValueError("Batch sizes must be nonnegative and sum to n") positive_difference = Fraction(0) q_total_count = defaultdict(Fraction) joint_count_cells = 0 def descend(j, completed, mismatches, q_prefix, p_prefix): nonlocal positive_difference, joint_count_cells if j == len(batches): joint_count_cells += 1 positive_difference += max(Fraction(0), q_prefix - p_prefix) q_total_count[mismatches] += q_prefix return size = batches[j] q_batch = self.binomial(size, self.predictive(completed, mismatches)) p_batch = self.teacher_binomial(size) for new_m, (q, p) in enumerate(zip(q_batch, p_batch)): descend(j + 1, completed + size, mismatches + new_m, q_prefix * q, p_prefix * p) descend(0, 0, 0, Fraction(1), Fraction(1)) if sum(q_total_count.values()) != 1: raise AssertionError("The exact schedule output does not sum to one") teacher_total_count = self.teacher_binomial(self.n) symmetrized_tv = sum(abs(q_total_count[m] - teacher_total_count[m]) for m in range(self.n + 1)) / 2 if symmetrized_tv > positive_difference: raise AssertionError("Total-count data processing inequality failed") if len([b for b in batches if b]) == 1: one_batch_tv = sum(abs(p - q) for p, q in zip( teacher_total_count, self.binomial(self.n, self.predictive(0, 0)))) / 2 if symmetrized_tv != positive_difference or positive_difference != one_batch_tv: raise AssertionError("One nonempty batch must equal its direct binomial TV") return positive_difference, symmetrized_tv, joint_count_cells def row(self, batches): tv, sym_tv, cells = self.evaluate(tuple(batches)) return {"batch_sizes": list(batches), "tv_exact": shown(tv), "symmetrized_tv_exact": shown(sym_tv), "joint_count_cells": cells} def literal_laws(oracle): """Full labeled 2n-coordinate P and R; no count transition kernels.""" teacher, model = {}, {} for x in product((0, 1), repeat=2 * oracle.n): m = sum(x[i] != x[oracle.n + i] for i in range(oracle.n)) teacher[x] = Fraction(1, 2**oracle.n) * oracle.tau**m * (1 - oracle.tau)**(oracle.n - m) model[x] = Fraction(1, 2**oracle.n) * sum( w * p**m * (1 - p)**(oracle.n - m) for w, p in zip(oracle.weights, oracle.probabilities)) if sum(teacher.values()) != 1 or sum(model.values()) != 1: raise AssertionError("Literal input laws do not normalize") return teacher, model def literal_policy_law(oracle, batches, pair_order, model): """Products of literal heads frozen before each coordinate batch.""" coordinate_batches = [tuple(range(oracle.n))] offset = 0 for size in batches: coordinate_batches.append(tuple(oracle.n + pair_order[j] for j in range(offset, offset + size))) offset += size @lru_cache(None) def head(revealed, values, coordinate, bit): denominator = sum(p for x, p in model.items() if all(x[i] == v for i, v in zip(revealed, values))) numerator = sum(p for x, p in model.items() if x[coordinate] == bit and all(x[i] == v for i, v in zip(revealed, values))) return numerator / denominator law = {} for x in model: probability = Fraction(1) revealed = () for batch in coordinate_batches: values = tuple(x[i] for i in revealed) for coordinate in batch: probability *= head(revealed, values, coordinate, x[coordinate]) revealed += batch law[x] = probability if sum(law.values()) != 1: raise AssertionError("Literal policy law does not normalize") return law def self_tests(): started = time.perf_counter() checks = [] literal_cases = 0 for n, batches in ((2, (1, 1)), (2, (0, 2, 0)), (3, (1, 2)), (3, (2, 1)), (3, (1, 0, 2)), (3, (1, 1, 1))): oracle = ExactFairOracle({"n": n, "tau": "1/4", "weights": ["2/3", "1/3"], "probabilities": ["1/4", "1/2"]}) teacher, model = literal_laws(oracle) fixed = literal_policy_law(oracle, batches, tuple(range(n)), model) fixed_tv = sum(abs(teacher[x] - fixed[x]) for x in teacher) / 2 sym_law = dict.fromkeys(teacher, Fraction(0)) for ordering in permutations(range(n)): law = literal_policy_law(oracle, batches, ordering, model) for x in sym_law: sym_law[x] += law[x] / math.factorial(n) sym_tv = sum(abs(teacher[x] - sym_law[x]) for x in teacher) / 2 calculated_tv, calculated_sym, _ = oracle.evaluate(batches) if fixed_tv != calculated_tv or sym_tv != calculated_sym: raise AssertionError("Independent full 2n-coordinate cross-check failed") literal_cases += 1 checks.append(f"{literal_cases} literal full-output fixed/random-permutation TV identities, n=2,3") target_cases = 0 for n in (2, 3, 8, 16): oracle = ExactFairOracle({"n": n, "tau": "1/4", "weights": ["1"], "probabilities": ["1/4"]}) for r in (1, 2, 3): for batches in {geometric_batches(n, r), equal_batches(n, r), (n,) + (0,) * (r - 1)}: tv, sym_tv, _ = oracle.evaluate(batches) if tv != 0 or sym_tv != 0: raise AssertionError("R=P must be sampled exactly in at least two rounds") target_cases += 1 checks.append(f"{target_cases} exact-target schedule zero-TV controls, n=2,3,8,16") for n in range(1, 33): for r in range(1, 5): for j in range(1, r + 1): root = floor_root_power(n, j, r) if not root**r <= n**j < (root + 1)**r: raise AssertionError("Exact geometric schedule root failure") checks.append("exact integer geometric-root inequalities n=1,...,32, r=1,...,4") return {"passed": True, "checks": checks, "elapsed_seconds": time.perf_counter() - started} def benchmark(witness, certificate, rounds): started = time.perf_counter() oracle = ExactFairOracle(witness) for key in ("n", "tau", "weights", "probabilities"): if witness[key] != certificate[key]: raise ValueError(f"Frozen witness/certificate mismatch in {key}") if not (certificate["model"]["kl_budget_certified"] and certificate["model"]["head_bound_certified"]): raise ValueError("An input model lacks certified KL/head constraints") if exact(certificate["model"]["kl_budget"]) != exact(witness["budget"]): raise ValueError("Witness and certificate KL budgets differ") if exact(certificate["model"]["head_bound"]) != exact(witness["head_bound"]): raise ValueError("Witness and certificate head bounds differ") case = next(c for c in certificate["cases"] if int(c["K"]) == rounds) lower, upper = exact(case["tv_lower_certified"]), exact(case["tv_upper_certified"]) if not 0 <= lower <= upper <= 1: raise ValueError("Invalid all-policy certificate interval") r = rounds - 1 geometric, equal = geometric_batches(oracle.n, r), equal_batches(oracle.n, r) all_rows = [] for batches in compositions(oracle.n, r): row = oracle.row(batches) if exact(row["tv_exact"]) < lower or exact(row["symmetrized_tv_exact"]) < lower: raise AssertionError("A legal exact schedule violates the all-policy lower certificate") all_rows.append(row) if len(all_rows) != math.comb(oracle.n + r - 1, r - 1): raise AssertionError("Weak-composition enumeration is incomplete") minimum = min(exact(x["tv_exact"]) for x in all_rows) minimum_sym = min(exact(x["symmetrized_tv_exact"]) for x in all_rows) fixed_ties = [x for x in all_rows if exact(x["tv_exact"]) == minimum] sym_ties = [x for x in all_rows if exact(x["symmetrized_tv_exact"]) == minimum_sym] best_fixed, best_sym = fixed_ties[0], sym_ties[0] row = { "id": witness["id"], "n": oracle.n, "budget": witness["budget"], "K": rounds, "weights": witness["weights"], "probabilities": witness["probabilities"], "model_tv": certificate["model"]["model_tv_exact"], "actual_kl_lower": certificate["model"]["kl_lower"], "actual_kl_upper": certificate["model"]["kl_upper"], "all_policy": {"lower": shown(lower), "upper": shown(upper)}, "geometric": oracle.row(geometric), "equal": oracle.row(equal), "best_fixed": best_fixed, "best_symmetrized": best_sym, "enumeration": {"schedule_count": len(all_rows), "best_fixed_tie_batch_sizes": [x["batch_sizes"] for x in fixed_ties], "best_symmetrized_tie_batch_sizes": [x["batch_sizes"] for x in sym_ties], "all_schedules": all_rows}, "geometric_excess_over_optimum_lower": shown(max(Fraction(0), exact(oracle.row(geometric)["tv_exact"]) - upper)), "geometric_excess_over_optimum_upper": shown(exact(oracle.row(geometric)["tv_exact"]) - lower), "best_fixed_excess_over_optimum_lower": shown(max(Fraction(0), minimum - upper)), "best_fixed_excess_over_optimum_upper": shown(minimum - lower), "head_cache_entries": oracle.predictive.cache_info().currsize, "elapsed_seconds": time.perf_counter() - started, } return row def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--witnesses", type=Path, required=True) parser.add_argument("--certificates", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--self-test", action="store_true") args = parser.parse_args() # Large exact denominators are research outputs, not untrusted integer text. if hasattr(sys, "set_int_max_str_digits"): sys.set_int_max_str_digits(0) started = time.perf_counter() witnesses = json.loads(args.witnesses.read_text()) certificates = json.loads(args.certificates.read_text()) if witnesses.get("status") != "complete": raise ValueError("Input witness selection must be complete") by_id = {w["id"]: w for w in certificates["witnesses"]} if len(by_id) != len(certificates["witnesses"]): raise ValueError("Duplicate certificate ids") witness_ids = [w["id"] for w in witnesses["witnesses"]] if len(set(witness_ids)) != len(witness_ids) or set(witness_ids) != set(by_id): raise ValueError("Witness and certificate id sets must match without duplicates") output = { "schema_version": 1, "status": "running", "metadata": { "witnesses_sha256": sha256(args.witnesses), "certificates_sha256": sha256(args.certificates), "source_sha256": sha256(__file__), "arithmetic": "exact fractions; floats are display only", "rounds": [3, 4], "policy": "Round 1 samples all fair A coordinates; fixed labeled B batches follow, with frozen pre-batch heads.", "fixed_tv": "Full-output TV equals TV of the JOINT vector of batch mismatch counts.", "symmetrized_tv": "Different policy: draw a uniform random permutation of pair labels before generation; marginalize that private randomness. Full-output TV then equals total mismatch count TV.", "optimization": "All ordered nonnegative compositions n into K-1 batches; oracle-specific optimum only within this schedule family, not an all-policy optimum or a uniformly chosen minimax schedule.", "tie_rule": "Record all exact ties; selected best is first in lexicographic batch-size order.", "geometric": "Cumulative sizes c_j=floor(n^(j/r)), c_0=0,c_r=n, computed by integer inequalities.", "equal": "Cumulative sizes c_j=floor(j*n/r), r=K-1.", }, "self_test": self_tests() if args.self_test else {"passed": None, "checks": []}, "rows": [], } args.output.parent.mkdir(parents=True, exist_ok=True) if args.output.exists(): raise FileExistsError("Refusing to overwrite an existing result") with args.output.open("x") as stream: json.dump(output, stream, indent=2) stream.write("\n") for witness in witnesses["witnesses"]: for rounds in (3, 4): row = benchmark(witness, by_id[witness["id"]], rounds) output["rows"].append(row) args.output.write_text(json.dumps(output, indent=2) + "\n") print(f"SCHEDULE {row['id']} K={rounds}: geometric={row['geometric']['tv_exact']['float']:.10g}, " f"equal={row['equal']['tv_exact']['float']:.10g}, best-fixed={row['best_fixed']['tv_exact']['float']:.10g}, " f"best-sym={row['best_symmetrized']['symmetrized_tv_exact']['float']:.10g}, " f"compositions={row['enumeration']['schedule_count']}, elapsed={row['elapsed_seconds']:.3f}s", flush=True) output["status"] = "complete" output["summary"] = { "witness_count": len(witnesses["witnesses"]), "row_count": len(output["rows"]), "schedule_evaluations": sum(r["enumeration"]["schedule_count"] for r in output["rows"]), "all_schedules_above_certified_lower": True, "all_data_processing_checks_passed": True, "elapsed_seconds": time.perf_counter() - started, } args.output.write_text(json.dumps(output, indent=2) + "\n") if __name__ == "__main__": main()