File size: 17,709 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
#!/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()