File size: 12,313 Bytes
b381c58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Executable re-derivation of the lemma chain behind Theorem 2 (Claim 1) and
Theorem 1 (Claim 2). Every step is an assertion; the script exits non-zero on failure.

Chain verified:
  Lemma 7    sum_pi Q_m(pi) Reg_hat_t(pi) < (K-1)/gamma_m      [IPGS kernel identity]
  Cor. 1     E[(x'beta_hat - x'beta)^2] = Theta(sigma^2 d / n) [ridge, random design]
  Lemma 11   R(T) <= tau_{m0-1} + 206 K sum_t 1/gamma_m(t) + Azuma
  Eq. E.30   206 K sum_t 1/gamma_m(t)  =  Theta(sigma sqrt(K d T))
  Thm 1      N(eps) ~ K^3 d / (phi0 (tau+eps)^2);  L(eps) = 1 + (1-eps)/(tau rho + eps)
"""
import json, sys, os
import numpy as np

os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from rcb.core import ipgs, EF_ridge, N_eps, L_eps, m0_eps

RES = {}
FAIL = []


def check(name, cond, detail=""):
    (RES.setdefault("checks", {}))[name] = {"pass": bool(cond), "detail": detail}
    print(f"[{'PASS' if cond else 'FAIL'}] {name}  {detail}")
    if not cond:
        FAIL.append(name)


def loglog_slope(xs, ys):
    return float(np.polyfit(np.log(xs), np.log(ys), 1)[0])


# ---------------------------------------------------------------- Lemma 7
def lemma7():
    """sum_{a != b} p_t(a) (mu_hat(b) - mu_hat(a)) < (K-1)/gamma, for the IPGS kernel.

    Proof step (E.12): each term is (1/gamma) * [gamma*Delta / (K + gamma*Delta)] < 1/gamma.
    """
    rng = np.random.default_rng(0)
    worst = -np.inf
    for _ in range(200000):
        K = int(rng.integers(2, 12))
        gamma = float(10 ** rng.uniform(-1, 4))
        mu = rng.normal(size=K)
        p, b = ipgs(mu, gamma)
        lhs = float(sum(p[a] * (mu[b] - mu[a]) for a in range(K) if a != b))
        worst = max(worst, lhs * gamma / (K - 1))
        if p[b] < 0:                       # kernel must stay a valid distribution
            check("lemma7-valid-kernel", False, f"p(b)={p[b]}")
            return
    check("Lemma 7: sum_a p(a)(mu_b - mu_a) < (K-1)/gamma", worst < 1.0,
          f"sup over 2e5 random (K,gamma,mu_hat) of LHS*gamma/(K-1) = {worst:.6f} < 1")
    RES["lemma7_sup_ratio"] = worst


# ---------------------------------------------------------------- Corollary 1
def corollary1():
    """Excess prediction risk of ridge with random design.

    The sharp identity is E_x[(x'beta_hat - x'beta)^2] = ||beta_hat - beta||^2_Sigma;
    Lemma 1 + Lemma 2 bound its expectation by ~ sigma^2 Tr[(Sigma+lam)^{-1}Sigma]/n
    + lam||beta||^2, i.e. Theta(sigma^2 d / n). We measure the exponents in d, n, sigma.
    """
    rng = np.random.default_rng(1)

    def risk(n, d, sigma, reps=200, lam=1e-6):
        out = []
        Sigma = np.eye(d)
        for _ in range(reps):
            beta = rng.normal(size=d) / np.sqrt(d)
            X = rng.normal(size=(n, d))
            y = X @ beta + sigma * rng.normal(size=n)
            bh = np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y)
            out.append(float((bh - beta) @ Sigma @ (bh - beta)))
        return float(np.mean(out))

    ns = np.array([200, 400, 800, 1600, 3200])
    s_n = loglog_slope(ns, [risk(n, 10, 0.1) for n in ns])
    check("Corollary 1: excess risk ~ n^-1", abs(s_n + 1.0) < 0.06,
          f"fitted exponent in n = {s_n:.3f} (theory -1)")

    ds = np.array([4, 8, 16, 32, 64])
    s_d = loglog_slope(ds, [risk(4000, d, 0.1) for d in ds])
    check("Corollary 1: excess risk ~ d^+1", abs(s_d - 1.0) < 0.06,
          f"fitted exponent in d = {s_d:.3f} (theory +1)")

    ss = np.array([0.02, 0.05, 0.1, 0.2, 0.4])
    s_s = loglog_slope(ss, [risk(2000, 10, s) for s in ss])
    check("Corollary 1: excess risk ~ sigma^+2", abs(s_s - 2.0) < 0.06,
          f"fitted exponent in sigma = {s_s:.3f} (theory +2)")
    RES["corollary1_exponents"] = dict(n=s_n, d=s_d, sigma=s_s)


# ---------------------------------------------------------------- Eq. E.29 / E.30
def regret_sum(T, K, d, sigma, phi0=1.0, N=1.0, c3=1.0, gamma_const=4.0, C0=206.0):
    """The learning-regret term of Lemma 11 evaluated exactly:

        C0 * K * sum_{t = tau_{m0-1}+1}^{T} 1/gamma_{m(t)},
        gamma_m = gamma_const * sqrt(K / E_F(2^{m-2})),  E_F = c3 sigma^2 d/(phi0 n).
    """
    m0 = m0_eps(N)
    tot = 0.0
    m = m0
    while 2 ** (m - 1) < T:
        lo, hi = max(2 ** (m - 1), 2 ** (m0 - 1)), min(2 ** m, T)
        if hi > lo:
            EF = EF_ridge(2 ** (m - 2), d, sigma, phi0, c3)
            gamma = gamma_const * np.sqrt(K / EF)
            tot += C0 * K * (hi - lo) / gamma
        m += 1
    return tot


def eq_e30():
    """Verify the closed form of Eq. (E.30): the learning term is Theta(sigma sqrt(KdT))
    and obeys the paper's stated constant 151 sigma sqrt(KdT)."""
    base = dict(K=5, d=5, sigma=0.05)

    Ts = np.array([2 ** k for k in range(12, 22)])
    sT = loglog_slope(Ts, [regret_sum(T=T, **base) for T in Ts])
    check("Eq. E.30: learning regret ~ T^1/2", abs(sT - 0.5) < 0.02,
          f"fitted exponent in T = {sT:.4f} (theory 1/2)")

    Ks = np.array([2, 3, 5, 10, 20, 40])
    sK = loglog_slope(Ks, [regret_sum(T=2 ** 20, K=K, d=5, sigma=0.05) for K in Ks])
    check("Eq. E.30: learning regret ~ K^1/2", abs(sK - 0.5) < 0.02,
          f"fitted exponent in K = {sK:.4f} (theory 1/2)")

    ds = np.array([2, 3, 5, 10, 20, 40])
    sd = loglog_slope(ds, [regret_sum(T=2 ** 20, K=5, d=d, sigma=0.05) for d in ds])
    check("Eq. E.30: learning regret ~ d^1/2", abs(sd - 0.5) < 0.02,
          f"fitted exponent in d = {sd:.4f} (theory 1/2)")

    ss = np.array([0.01, 0.02, 0.05, 0.1, 0.2])
    ss_ = loglog_slope(ss, [regret_sum(T=2 ** 20, K=5, d=5, sigma=s) for s in ss])
    check("Eq. E.30: learning regret ~ sigma^1", abs(ss_ - 1.0) < 0.02,
          f"fitted exponent in sigma = {ss_:.4f} (theory 1)")

    # ---- the paper's explicit constant -----------------------------------
    # E.30's last-but-one step replaces sum_{m=m0}^{log2 T} 2^{m/2} by
    # int_{m0}^{log2 T} 2^{x/2} dx. For an INCREASING integrand the sum EXCEEDS the
    # integral, so this direction is invalid: sum -> 2^{M/2}/(1 - 2^{-1/2}) = 3.414 sqrt(T)
    # while the integral gives (2/ln 2) sqrt(T) = 2.885 sqrt(T). The paper's stated
    # constant 151 is therefore understated by the factor 3.414/2.885 = 1.183.
    M = 24
    disc = sum(2 ** (m / 2) for m in range(6, M + 1))
    integ = (2 ** (M / 2) - 2 ** 3) * 2 / np.log(2)
    check("E.30: sum_m 2^{m/2} EXCEEDS int 2^{x/2} dx (paper bounds it the wrong way)",
          disc > integ, f"discrete sum/integral = {disc/integ:.4f} > 1 "
                        f"(asymptotically 3.4142/2.8854 = 1.1833)")

    ratios = []
    for T in [2 ** k for k in range(12, 22)]:
        for K in [3, 5, 10]:
            for d in [2, 5, 10]:
                r = regret_sum(T=T, K=K, d=d, sigma=0.05)
                ratios.append(r / (0.05 * np.sqrt(K * d * T)))
    mx = max(ratios)
    check("E.30: paper's constant 151 is VIOLATED; correct constant is ~176",
          mx > 151.0 and mx <= 177.0,
          f"max over 90 (T,K,d) grid points of term/(sigma sqrt(KdT)) = {mx:.1f}; "
          f"paper claims <=151, closed form 51.5/(1-2^-1/2) = {51.5/(1-2**-0.5):.1f}")
    RES["e30"] = dict(T=sT, K=sK, d=sd, sigma=ss_, max_ratio=float(mx),
                      correct_constant=float(51.5 / (1 - 2 ** -0.5)))

    # ---- E.29 line 2 typo --------------------------------------------------
    # As printed, E.29 line 2 reads 52 sum_m sqrt(K E_F(...) (tau_m - tau_{m-1})).
    # Lemma 11 actually yields (tau_m - tau_{m-1}) * sqrt(K E_F). The printed form is
    # O(sqrt(Kd) log T); only the latter gives O(sqrt(KdT)). Distinguish by the T exponent.
    def printed_sum(T, K=5, d=5, sigma=0.05):
        s = 0.0
        for m in range(6, int(np.log2(T)) + 1):
            EF = EF_ridge(2 ** (m - 2), d, sigma, 1.0, 1.0)
            s += 52 * np.sqrt(K * EF * 2 ** (m - 1))
        return s

    Ts = np.array([2 ** k for k in range(12, 25)])
    sp = loglog_slope(Ts, [printed_sum(T) for T in Ts])
    check("E.29 as printed is O(polylog T), not O(sqrt(T)) -- a typo, not the real bound",
          sp < 0.15, f"fitted exponent in T of the printed expression = {sp:.4f} "
                     f"(log-like); the corrected expression gives {sT:.4f}")


# ---------------------------------------------------------------- Theorem 1
def theorem1():
    """N(eps) exponents (Claim 2) evaluated on the closed form of Eq. (7)."""
    base = dict(sigma=0.05, eps=0.05, tau=0.01, phi0=1.0)

    Ks = np.array([2, 3, 5, 10, 20, 40])
    sK = loglog_slope(Ks, [N_eps(K=K, d=5, **base) for K in Ks])
    check("Theorem 1: N(eps) ~ K^3", abs(sK - 3.0) < 1e-6,
          f"fitted exponent in K = {sK:.6f} (paper: cubic in arms)")

    # The paper advertises N(eps) as "linear in context (d)". The formula's d-factor is
    # (sigma^2 d + 1), which is linear only once sigma^2 d >> 1. At the paper's own
    # noise levels that crossover sits far beyond any d it uses.
    ds = np.array([2, 5, 10, 20, 50, 100, 200])
    sd = loglog_slope(ds, [N_eps(K=5, d=d, **base) for d in ds])
    check("Theorem 1: N(eps) is NOT linear in d at the paper's own sigma=0.05",
          sd < 0.2, f"fitted exponent in d over d in [2,200] = {sd:.4f}, i.e. essentially "
                    f"CONSTANT, because sigma^2 d < 1 until d > 1/sigma^2 = {1/0.05**2:.0f}. "
                    f"Every d used in the paper (2,5,10,70) lies in this flat regime.")

    ds2 = np.array([1e5, 1e6, 1e7, 1e8])
    sd2 = loglog_slope(ds2, [N_eps(K=5, d=d, **base) for d in ds2])
    check("Theorem 1: N(eps) -> d^1 only asymptotically (sigma^2 d >> 1)",
          abs(sd2 - 1.0) < 0.02,
          f"fitted exponent in d over d in [1e5,1e8] = {sd2:.4f} (theory 1)")

    es = np.array([0.005, 0.01, 0.02, 0.05, 0.1])
    se = loglog_slope(es + 0.01, [N_eps(K=5, d=5, sigma=0.05, eps=e, tau=0.01, phi0=1.0)
                                  for e in es])
    check("Theorem 1: N(eps) ~ (tau+eps)^-2", abs(se + 2.0) < 1e-6,
          f"fitted exponent in (tau+eps) = {se:.6f} (theory -2)")

    ps = np.array([0.01, 0.1, 1.0, 10.0])
    sp = loglog_slope(ps, [N_eps(K=5, d=5, sigma=0.05, eps=0.05, tau=0.01, phi0=p)
                           for p in ps])
    check("Theorem 1: N(eps) ~ phi0^-1", abs(sp + 1.0) < 1e-6,
          f"fitted exponent in phi0 = {sp:.6f} (theory -1)")

    # L(eps) is decreasing in eps and >= 1
    es = np.linspace(0.0, 1.0, 101)
    Ls = np.array([L_eps(e, 0.01, 0.95) for e in es])
    check("Theorem 1: L(eps) decreasing in eps and >= 1",
          bool(np.all(np.diff(Ls) < 0) and np.all(Ls >= 1.0)),
          f"L(0)={Ls[0]:.1f} -> L(1)={Ls[-1]:.1f}")
    RES["theorem1"] = dict(K=sK, d_small=sd, d_large=sd2, eps=se, phi0=sp)


# ------------------------------- Theorem 2 statement vs its own proof
def theorem2_statement():
    """Theorem 2 states the price-of-incentives term as 'T_cold ~ m0(eps)'. But
    m0(eps) = ceil(2 + log2 N(eps)) is LOGARITHMIC in N, whereas (a) the proof E.29
    uses tau_{m0-1} = 2^{m0-1} ~ 2 N(eps), and (b) the body text says this cost
    'scales as O(1/eps^2)'. Only the proof's reading is self-consistent."""
    out = {}
    for eps in [0.01, 0.02, 0.05, 0.1]:
        N = N_eps(5, 5, 0.05, eps, 0.01, 1.0)
        m0 = m0_eps(N)
        out[eps] = dict(N=N, m0=m0, tau_m0_minus_1=2.0 ** (m0 - 1))
    es = np.array(list(out))
    s_m0 = loglog_slope(es + 0.01, [out[e]["m0"] for e in es])
    s_tau = loglog_slope(es + 0.01, [out[e]["tau_m0_minus_1"] for e in es])
    check("Theorem 2's stated T_cold ~ m0(eps) is NOT O(1/eps^2)", abs(s_m0) < 0.6,
          f"exponent of m0(eps) in (tau+eps) = {s_m0:.3f}, not -2")
    check("Theorem 2's proof term tau_{m0-1} IS O(1/eps^2)", abs(s_tau + 2.0) < 0.15,
          f"exponent of tau_(m0-1) in (tau+eps) = {s_tau:.3f} (theory -2)")
    RES["theorem2_statement"] = dict(m0_exponent=s_m0, tau_exponent=s_tau,
                                     table={str(k): v for k, v in out.items()})


if __name__ == "__main__":
    lemma7(); corollary1(); eq_e30(); theorem1(); theorem2_statement()
    RES["n_fail"] = len(FAIL); RES["failed"] = FAIL
    os.makedirs("outputs", exist_ok=True)
    json.dump(RES, open("outputs/theory_checks.json", "w"), indent=1)
    print(f"\n{len(RES['checks'])} checks, {len(FAIL)} failed")
    sys.exit(1 if FAIL else 0)