File size: 5,449 Bytes
7956103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deterministic model-vs-execution diagnostic; no sampled TV estimators."""
from __future__ import annotations

import argparse
import json
import math
import time
from fractions import Fraction
from pathlib import Path

import numpy as np
from scipy.stats import binom


def binomial_tv(n: int, p: float, q: float) -> float:
    """Exact finite distribution identity evaluated by double-precision CDFs.

    The likelihood ratio is monotone; CDF difference at its crossing gives TV.
    Neighbor candidates protect against floating-point rounding at a tie.
    This is not an interval-arithmetic certificate.
    """
    if p == q or n == 0:
        return 0.0
    p, q = sorted((p, q))
    difference = q - p
    log_yes = math.log1p(difference / p)
    log_no = math.log1p(-difference / (1 - p))
    slope = log_yes - log_no
    crossing = -n * log_no / slope
    k = math.floor(crossing)
    candidates = np.array([max(-1, min(n, k + d)) for d in (-1, 0, 1)])
    return float(np.max(binom.cdf(candidates, n, p) - binom.cdf(candidates, n, q)))


def kl_teacher_to_mixture(n, tau, w, delta, block_size=65536):
    """Sum all n+1 teacher count atoms; no intentional tail truncation."""
    total = 0.0
    mass = 0.0
    terms_abs = 0.0
    log_yes = math.log1p(delta / tau)
    log_no = math.log1p(-delta / (1 - tau))
    for start in range(0, n + 1, block_size):
        k = np.arange(start, min(start + block_size, n + 1))
        prob = binom.pmf(k, n, tau)
        log_lr = k * log_yes + (n - k) * log_no
        log_mix_lr = np.logaddexp(math.log1p(-w), math.log(w) + log_lr)
        terms = -prob * log_mix_lr
        total += float(np.sum(terms, dtype=np.float64))
        terms_abs += float(np.sum(abs(terms), dtype=np.float64))
        mass += float(np.sum(prob, dtype=np.float64))
    residual = abs(mass - 1)
    if residual > 2e-8 or total < -1e-10 or total > -math.log1p(-w) + 1e-8:
        raise ArithmeticError((n, total, residual))
    return {"kl": total, "teacher_mass_residual": residual,
            "absolute_summands": terms_abs, "evaluated_atoms": n + 1}


def validate():
    worst_cdf = 0.0
    cases = 0
    for n in (1, 2, 4, 16, 64, 257):
        for p, q in ((.25,.5),(.25,.28125),(.25,.250001),(.1,.8)):
            k = np.arange(n + 1)
            brute = .5 * np.sum(abs(binom.pmf(k,n,p) - binom.pmf(k,n,q)))
            error = abs(binomial_tv(n,p,q) - brute)
            worst_cdf = max(worst_cdf, error)
            assert error < 2e-12, (n,p,q,error)
            cases += 1
    # Independent exact-rational small-count KL computation.
    worst_kl = 0.0
    for n in range(1, 9):
        tau, w, delta = Fraction(1,4), Fraction(1,8), Fraction(1,4)
        expected = 0.0
        for k in range(n + 1):
            p = Fraction(math.comb(n,k)) * tau**k * (1-tau)**(n-k)
            r = (1-w)*p + w*math.comb(n,k)*(tau+delta)**k*(1-tau-delta)**(n-k)
            expected += float(p) * math.log(float(p/r))
        observed = kl_teacher_to_mixture(n,float(tau),float(w),float(delta))["kl"]
        worst_kl = max(worst_kl, abs(expected-observed))
    assert worst_kl < 2e-12
    return {"status":"PASS", "cdf_vs_pmf_cases":cases,
            "cdf_vs_pmf_max_error":worst_cdf,
            "rational_mass_kl_cases":8, "rational_mass_kl_max_error":worst_kl}


def run(config):
    started = time.monotonic()
    validation = validate()
    records = []
    for exponent in config["exponents"]:
        n = 2**exponent
        scale = (n/config["reference_n"])**(-config["decay_exponent"])
        tau = config["tau"]
        w, delta = config["w0"]*scale, config["delta0"]*scale
        stats = kl_teacher_to_mixture(n,tau,w,delta,config["block_size"])
        records.append({"n":n,"tau":tau,"w":w,"delta":delta,
            "kl":stats["kl"],"kl_upper_bound":-math.log1p(-w),
            "model_tv":w*binomial_tv(n,tau,tau+delta),
            "execution_tv":binomial_tv(n,tau,tau+w*delta),
            "head_tv_upper_bound":delta,
            "execution_hoeffding_lower_bound":max(0.0,1-2*math.exp(-n*(w*delta)**2/2)),
            "teacher_mass_residual":stats["teacher_mass_residual"],
            "evaluated_atoms":stats["evaluated_atoms"]})
        print(f"E1 n={n} KL={stats['kl']:.6g} outputTV={records[-1]['execution_tv']:.6g}",flush=True)
    return {"experiment":"e1_model_execution","validation":validation,
        "records":records,"runtime_seconds":time.monotonic()-started,
        "metadata":{"method":"Full finite sums for KL; monotone-likelihood-ratio binomial CDF identity for TV",
                    "error_accounting":"No intentional truncation. Double precision, not rigorous interval bounds; full teacher mass residual recorded.",
                    "policy":"all A, then all B; fixed schedule, not all-policy optimum",
                    "full_tv_justification":"Both laws have independent fair A and iid mismatches; count is sufficient for their likelihood ratio.",
                    "head_error":"delta is a uniform upper bound, not measured worst-case equality"}}


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    result = run(json.loads(args.config.read_text())["e1"])
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(result, indent=2, allow_nan=False)+"\n")