File size: 14,623 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#!/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()