File size: 9,871 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 | """Claim 3 [ALGORITHMIC]: mechanism structure + complexity.
Two parts:
(A) Structural verification of the two-stage mechanism against the paper's own
pseudocode and the invariants its proofs rely on.
(B) Empirical complexity: the paper's "Complexity Analysis" states the cold start
lasts O(K L N) rounds with per-round cost "only the sorting of prior means",
and the exploitation stage is dominated by the offline oracle (O(d^3) inversion).
"""
import json, os, sys, time
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 RCB, ipgs, L_eps, m0_eps
from rcb.env import SyntheticEnv
RES, FAIL = {"checks": {}}, []
def check(name, cond, detail=""):
RES["checks"][name] = {"pass": bool(cond), "detail": detail}
print(f"[{'PASS' if cond else 'FAIL'}] {name} {detail}")
if not cond:
FAIL.append(name)
# ============================================================ (A) structure
def structural():
rng = np.random.default_rng(0)
# -- IPGS is a valid kernel and p(b_t) >= 1/K (asserted in proof Eq. C.14/C.15)
worst_pb, ok_simplex = 1.0, True
for _ in range(200000):
K = int(rng.integers(2, 15))
gamma = float(10 ** rng.uniform(-2, 5))
p, b = ipgs(rng.normal(size=K), gamma)
ok_simplex &= bool(np.all(p >= -1e-12) and abs(p.sum() - 1) < 1e-10)
worst_pb = min(worst_pb, p[b] * K)
check("IPGS is a probability kernel for all gamma>0, K>=2", ok_simplex,
"2e5 random draws: p >= 0 and sums to 1")
check("IPGS satisfies p_t(b_t) >= 1/K (used in Part I of Eq. C.15)",
worst_pb >= 1.0 - 1e-9, f"min over 2e5 draws of K*p(b_t) = {worst_pb:.6f} >= 1")
# -- Cold start: organic pulls must NOT increment N_i or S_i (Section 3.1)
K, d = 4, 3
beta0 = [np.zeros(d) for _ in range(K)]
beta0[0] = np.full(d, 0.3)
S0 = [0.2 * np.eye(d) for _ in range(K)]
env = SyntheticEnv(K, d, 0.05, beta0, S0, rng=np.random.default_rng(3))
a = RCB(K, d, 0.05, beta0, S0, N=15, L=8.0, offset=0.5, phi0=1 / d,
use_empirical_EF=True, rng=np.random.default_rng(4))
phases, organic_counted = {"MPASC": 0, "RASC-promote": 0, "RASC-organic": 0, "IPGS": 0}, 0
for t in range(20000):
x = env.context()
before = a.Ni.copy()
rec, info = a.recommend(x)
phases[info["phase"]] = phases.get(info["phase"], 0) + 1
a.update(x, rec, env.pull(x, rec), info)
if info["phase"] == "RASC-organic" and not np.array_equal(before, a.Ni):
organic_counted += 1
check("Organic recommendations do not increment N_i or S_i", organic_counted == 0,
f"{phases['RASC-organic']} organic rounds, {organic_counted} wrongly counted")
check("Both stages of the mechanism are exercised",
phases["MPASC"] > 0 and phases["RASC-promote"] > 0 and phases["IPGS"] > 0,
f"MPASC={phases['MPASC']} RASC-promote={phases['RASC-promote']} "
f"RASC-organic={phases['RASC-organic']} IPGS={phases['IPGS']}")
check("Every arm reaches the saturation threshold N before Stage 2",
bool(np.all(a.Ni >= 15)), f"N_i at transition = {a.Ni.tolist()}, N = 15")
RES["phases"] = phases
# -- RASC explores with frequency exactly 1/L (Algorithm 1, q_t ~ Ber(1/L))
prom = org = 0
for sd in range(40):
env2 = SyntheticEnv(K, d, 0.05, beta0, S0, rng=np.random.default_rng(1000 + sd))
a2 = RCB(K, d, 0.05, beta0, S0, N=60, L=8.0, offset=0.5, phi0=1 / d,
use_empirical_EF=True, rng=np.random.default_rng(2000 + sd))
while a2.stage == 1:
x = env2.context(); r, i = a2.recommend(x)
a2.update(x, r, env2.pull(x, r), i)
prom += i["phase"] == "RASC-promote"; org += i["phase"] == "RASC-organic"
n_r = prom + org
frac = prom / n_r
se = np.sqrt(0.125 * 0.875 / n_r)
check("RASC explores with frequency 1/L", abs(frac - 0.125) < 3 * se,
f"measured {frac:.4f} over {n_r} RASC rounds vs 1/L = 0.1250 (3 s.e. = {3*se:.4f})")
# -- epoch schedule m0 = ceil(2 + log2 N)
ok = all(m0_eps(N) == int(np.ceil(2 + np.log2(N))) for N in [1, 5, 10, 100, 1000, 175781])
check("Exploitation starts at epoch m0 = ceil(2 + log2 N)", ok, "checked N in {1..1.8e5}")
# -- Cold-start DBIC inequality Eq. (C.7): with L >= 1 + (Delta0-eps)/(tau*rho+eps),
# (1-1/L) E[G|G>0]Pr(G>0) + (1/L)(mu0_i - mu0_j) >= -eps
worst = np.inf
for _ in range(200000):
eps = float(rng.uniform(0, 0.3)); tau = float(rng.uniform(1e-3, 0.2))
rho = float(rng.uniform(0.5, 1.0)); D0 = float(rng.uniform(0, 1.0))
L = L_eps(eps, tau, rho, delta_max=D0)
lhs = (1 - 1 / L) * (tau * rho) + (1 / L) * (-D0)
worst = min(worst, lhs + eps)
check("Cold-start DBIC bound Eq. (C.7) holds at the prescribed L", worst >= -1e-9,
f"min over 2e5 random (eps,tau,rho,Delta0) of LHS+eps = {worst:.3e} >= 0")
# ============================================================ (B) complexity
def complexity():
def cold_len(K, L, N, seed=0, d=3):
beta0 = [np.zeros(d) for _ in range(K)]; beta0[0] = np.full(d, 0.3)
S0 = [0.2 * np.eye(d) for _ in range(K)]
env = SyntheticEnv(K, d, 0.05, beta0, S0, rng=np.random.default_rng(seed + 5))
a = RCB(K, d, 0.05, beta0, S0, N=N, L=L, offset=0.5, phi0=1 / d,
use_empirical_EF=True, rng=np.random.default_rng(seed))
t = 0
while a.stage == 1 and t < 5_000_000:
x = env.context(); rec, info = a.recommend(x)
a.update(x, rec, env.pull(x, rec), info); t += 1
return t
def sl(xs, ys):
return float(np.polyfit(np.log(xs), np.log(ys), 1)[0])
# fit away from the small-K boundary (at K=2 only one arm needs RASC at all)
Ks = [8, 16, 32, 64]
yK = [np.mean([cold_len(K, 10.0, 20, s) for s in range(3)]) for K in Ks]
Ls = [4.0, 8.0, 16.0, 32.0]
yL = [np.mean([cold_len(5, L, 20, s) for s in range(3)]) for L in Ls]
Ns = [10, 20, 40, 80]
yN = [np.mean([cold_len(5, 10.0, N, s) for s in range(3)]) for N in Ns]
sK, sL, sN = sl(Ks, yK), sl(Ls, yL), sl(Ns, yN)
check("Cold start is linear in K (paper: O(K L N))", abs(sK - 1.0) < 0.15,
f"fitted exponent in K = {sK:.3f}")
check("Cold start is linear in L", abs(sL - 1.0) < 0.15, f"fitted exponent in L = {sL:.3f}")
check("Cold start is linear in N", abs(sN - 1.0) < 0.15, f"fitted exponent in N = {sN:.3f}")
RES["cold_start_complexity"] = dict(K=dict(x=Ks, y=list(map(float, yK)), slope=sK),
L=dict(x=Ls, y=list(map(float, yL)), slope=sL),
N=dict(x=Ns, y=list(map(float, yN)), slope=sN))
# per-round wall-clock of Algorithm 2 vs d, and epoch-refit cost vs d
def timing(d, T=8000, K=5):
beta0 = [np.zeros(d) for _ in range(K)]; S0 = [0.2 * np.eye(d) for _ in range(K)]
env = SyntheticEnv(K, d, 0.05, beta0, S0, rng=np.random.default_rng(1))
a = RCB(K, d, 0.05, beta0, S0, N=5, L=4.0, offset=0.5, phi0=1 / d,
use_empirical_EF=True, rng=np.random.default_rng(2))
for _ in range(2000):
x = env.context(); r, i = a.recommend(x); a.update(x, r, env.pull(x, r), i)
t0 = time.perf_counter()
for _ in range(T):
x = env.context(); r, i = a.recommend(x); a.update(x, r, env.pull(x, r), i)
return (time.perf_counter() - t0) / T * 1e6 # microseconds per round
ds = [2, 4, 8, 16, 32, 64]
yt = [timing(d) for d in ds]
st = sl(ds, yt)
check("Algorithm 2 per-round cost grows sub-cubically in d (per-round work is O(Kd))",
st < 1.6, f"fitted exponent in d = {st:.3f}; per-round us = "
f"{[round(v,1) for v in yt]}")
RES["per_round_us"] = dict(d=ds, us=yt, slope=st)
# offline-oracle refit: separate the O(d^3) linear solve from the O(n d^2) Gram
def timeit(f, reps):
f(); t0 = time.perf_counter()
for _ in range(reps):
f()
return (time.perf_counter() - t0) / reps * 1e6
def solve_us(d, reps=50):
rng = np.random.default_rng(0)
A = rng.normal(size=(d, d)); A = A @ A.T + d * np.eye(d); b = rng.normal(size=d)
return timeit(lambda: np.linalg.solve(A, b), reps)
def gram_us(d, n=4000, reps=10):
rng = np.random.default_rng(0)
X = rng.normal(size=(n, d))
return timeit(lambda: X.T @ X, reps)
# fit in the asymptotic regime; below d~128 the measurement is dominated by
# constant LAPACK/Python call overhead rather than by arithmetic
ds2 = [128, 256, 512, 1024]
ysolve = [solve_us(d) for d in ds2]
ygram = [gram_us(d) for d in ds2]
s_solve, s_gram = sl(ds2, ysolve), sl(ds2, ygram)
check("Oracle linear solve scales close to the paper's stated O(d^3)",
2.2 < s_solve < 3.4, f"fitted exponent in d = {s_solve:.3f} (theory 3, wall-clock fit); "
f"us = {[round(v,1) for v in ysolve]}")
check("Oracle Gram formation scales close to O(n d^2), the true dominant cost",
1.6 < s_gram < 2.6, f"fitted exponent in d = {s_gram:.3f} (theory 2, wall-clock fit); "
f"us = {[round(v,1) for v in ygram]}")
RES["refit_us"] = dict(d=ds2, solve_us=ysolve, gram_us=ygram,
slope_solve=s_solve, slope_gram=s_gram)
if __name__ == "__main__":
structural(); complexity()
RES["n_fail"] = len(FAIL); RES["failed"] = FAIL
os.makedirs("outputs", exist_ok=True)
json.dump(RES, open("outputs/claim3_structure.json", "w"), indent=1)
print(f"\n{len(RES['checks'])} checks, {len(FAIL)} failed")
sys.exit(1 if FAIL else 0)
|