File size: 7,843 Bytes
868c741
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Exact audits for the information-limit constructions in Chapter 8.

Only Python's standard library is required. These finite audits check
algebraic implementations and stated examples. The universal claims and
analytic Gaussian envelope are proved in the manuscript; finite checks
are not a replacement for those proofs.
"""
from __future__ import annotations

import argparse
import json
from fractions import Fraction as F
from math import factorial
from pathlib import Path


def trim(p):
    p = list(p)
    while len(p) > 1 and p[-1] == 0:
        p.pop()
    return p


def add(p, q):
    out = [F(0)] * max(len(p), len(q))
    for i, c in enumerate(p):
        out[i] += c
    for i, c in enumerate(q):
        out[i] += c
    return trim(out)


def scale(p, c):
    return trim([c * x for x in p])


def shift(p, n):
    return [F(0)] * n + list(p)


def mul(p, q):
    out = [F(0)] * (len(p) + len(q) - 1)
    for i, a in enumerate(p):
        for j, b in enumerate(q):
            out[i + j] += a * b
    return trim(out)


def derivative(p):
    return trim([F(i) * p[i] for i in range(1, len(p))] or [F(0)])


def evaluate(p, x):
    value = F(0)
    for c in reversed(p):
        value = value * x + c
    return value


def gaussian_derivative_polynomial(p):
    """Return Q such that (exp(-x^2) P)' = exp(-x^2) Q."""
    return add(derivative(p), scale(shift(p, 1), -2))


def piecewise_value(x, a, mu, v, offset=F(0)):
    curvature = a if x <= 0 else mu
    return offset + v * x + curvature * x * x / 2


def piecewise_gradient(x, a, mu, v):
    return v + (a if x <= 0 else mu) * x


def audit_transcripts():
    cases = []
    total_queried_points = 0
    total_future_values = 0
    for mu, L, eta, v in [
        (F(1, 16), F(1), F(1), F(1, 4)),
        (F(1, 8), F(1), F(3, 2), F(2, 3)),
        (F(1, 5), F(3, 2), F(1), F(3, 7)),
    ]:
        assert 0 < eta * mu < 1 and 0 < eta * L < 2
        for t in [0, 1, 2, 5, 9, 17]:
            q = 1 - eta * mu
            points = [v / mu * (q ** (i - t) - 1) for i in range(t + 1)]
            assert points[-1] == 0 and all(x >= 0 for x in points)
            transcripts = []
            for a in [mu, (mu + L) / 2, L]:
                data = [(x, piecewise_value(x, a, mu, v),
                         piecewise_gradient(x, a, mu, v)) for x in points]
                transcripts.append(data)
                for i in range(t):
                    assert data[i][0] - eta * data[i][2] == data[i + 1][0]
                optimum = -v / a
                assert piecewise_gradient(optimum, a, mu, v) == 0
                remaining = piecewise_value(F(0), a, mu, v) - piecewise_value(
                    optimum, a, mu, v)
                assert remaining == v * v / (2 * a)
                x = F(0)
                for n in range(1, 15):
                    x -= eta * piecewise_gradient(x, a, mu, v)
                    closed = v / a * ((1 - eta * a) ** n - 1)
                    assert x == closed and x <= 0
                    gain = piecewise_value(F(0), a, mu, v) - piecewise_value(
                        x, a, mu, v)
                    assert gain == v * v / (2 * a) * (1 - (1 - eta * a) ** (2 * n))
                    total_future_values += 1
            assert transcripts[0] == transcripts[1] == transcripts[2]
            for n in range(1, 15):
                gains = [v * v / (2 * a) * (1 - (1 - eta * a) ** (2 * n))
                         for a in [mu, (mu + L) / 2, L]]
                assert gains[0] > gains[1] > gains[2]
            total_queried_points += t + 1
            cases.append({"mu": str(mu), "L": str(L), "eta": str(eta),
                          "v": str(v), "t": t, "all_exact_checks_passed": True})
    return {"cases": cases, "distinct_common_prefix_points": total_queried_points,
            "exact_future_values_checked": total_future_values}


def audit_analytic_jets():
    reports = []
    jet_equalities = 0
    mu, L, a, eta, x0 = F(1, 4), F(1), F(1, 2), F(1), F(1)
    q = 1 - eta * a
    for t in range(6):
        for r in range(1, 4):
            points = [q ** i * x0 for i in range(t + 1)]
            p = [F(1)]
            for x in points:
                for _ in range(2 * r + 2):
                    p = mul(p, [-x, F(1)])
            first = gaussian_derivative_polynomial(p)
            second = gaussian_derivative_polynomial(first)
            direct = add(add(derivative(derivative(p)),
                             scale(shift(derivative(p), 1), -4)),
                         add(scale(shift(p, 2), 4), scale(p, -2)))
            assert second == direct
            M = sum((abs(c) * factorial((j + 1) // 2)
                     for j, c in enumerate(second)), F(0))
            assert M > 0
            epsilon = min(a - mu, L - a) / (2 * M)
            assert mu < a - epsilon * M < a + epsilon * M < L
            d = p
            for order in range(2 * r + 2):
                for x in points:
                    assert evaluate(d, x) == 0
                    jet_equalities += 1
                d = gaussian_derivative_polynomial(d)
            next_x = q ** (t + 1) * x0
            assert next_x not in points
            assert evaluate(p, next_x) > 0
            # exp(-next_x**2)>0; the rational prefactor below is positive.
            separation_prefactor = 2 * epsilon * evaluate(p, next_x)
            assert separation_prefactor > 0
            reports.append({"t": t, "r": r, "polynomial_degree": len(p) - 1,
                            "M_numerator_bits": M.numerator.bit_length(),
                            "M_denominator_bits": M.denominator.bit_length(),
                            "epsilon_positive": epsilon > 0,
                            "next_loss_separation_positive": separation_prefactor > 0,
                            "all_exact_checks_passed": True})
    return {"cases": reports, "exact_zero_jet_equalities_checked": jet_equalities,
            "envelope": "M=sum_j abs(q_j)*ceil(j/2)!; global bound proved in text"}


def audit_curvature_budget():
    checked = 0
    for m in range(1, 65):
        D0 = F(1, m + 3)
        increments = [F(j + 1, (m + 3) ** 3) for j in range(m)]
        decrements = [D0]
        for increment in increments:
            decrements.append(decrements[-1] + increment)
        weighted = (m + 1) * D0 + sum(
            ((m - j) * value for j, value in enumerate(increments)), F(0))
        assert sum(decrements, F(0)) == weighted
        checked += 1
    return {"weighted_curvature_identities_checked": checked}


def run_audit():
    return {"arithmetic": "fractions.Fraction; exact integer polynomial operations",
            "all_checks_passed": True,
            "transcripts": audit_transcripts(),
            "analytic_finite_jets": audit_analytic_jets(),
            "curvature_budget": audit_curvature_budget(),
            "scope": "Finite implementation audits; universal claims rest on manuscript proofs."}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()
    report = run_audit()
    encoded = json.dumps(report, indent=2) + "\n"
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(encoded, encoding="utf-8")
    print(json.dumps({"all_checks_passed": report["all_checks_passed"],
                      "transcript_cases": len(report["transcripts"]["cases"]),
                      "analytic_cases": len(report["analytic_finite_jets"]["cases"]),
                      "exact_future_values": report["transcripts"]["exact_future_values_checked"],
                      "exact_zero_jets": report["analytic_finite_jets"]["exact_zero_jet_equalities_checked"]},
                     indent=2))


if __name__ == "__main__":
    main()