Srishti280992's picture
Add incentivized exploration reproduction bundle
b381c58 verified
Raw
History Blame Contribute Delete
7.13 kB
"""Claim 1, empirical half: does RCB's regret actually scale as O(sqrt(K d T))?
Theorem 2 bounds the TOTAL regret by
R(T) <= T_cold(eps) + O~( sqrt( K d (T - T_cold) ) ) ,
so the sqrt(KdT) rate is a statement about the EXPLOITATION-stage regret only; the
cold-start term is separately linear in K (its length is O(K L N), the paper's own
Complexity Analysis). Fitting exponents on total regret therefore conflates the two
terms. This script measures both and fits log-log exponents separately:
R_total(T) = R(T)
R_exploit(T) = R(T) - R(T_cold)
Sweeps (Appendix F Setting 1 parameters: sigma = 0.05, eps = 0.05, tau_P0 = 0.01,
rho_P0 = 0.95, Sigma_{i,0} = (1/5) I_d, beta_{i,0} = 0_d, cold start N = 20):
T sweep : T in {2^13 .. 2^17}, (K,d) in {(3,5),(5,5),(10,5),(5,10)} -> exponent 1/2
K sweep : K in {2,3,5,10,20}, d = 5, T = 2^17 -> exponent 1/2
d sweep : d in {2,3,5,10,20}, K = 5, T = 2^17 -> exponent 1/2
"""
import argparse, json, os, sys, time
from concurrent.futures import ProcessPoolExecutor
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 scripts.run_synthetic import simulate, slope
TMAX = 1 << 17 # 131 072
def _one(job):
T, K, d, seed, N = job
r = simulate(T, K, d, N=N, seed=seed, gain_every=10 ** 9)
return dict(T=T, K=K, d=d, seed=seed,
total=r["regret_total"], exploit=r["regret_exploit"],
Tcold=int(r["Tcold"]))
def aggregate(rows, key):
"""Mean over seeds, grouped by the sweep variable `key`."""
xs = sorted({r[key] for r in rows})
tot = [float(np.mean([r["total"] for r in rows if r[key] == x])) for x in xs]
exp = [float(np.mean([r["exploit"] for r in rows if r[key] == x])) for x in xs]
tc = [float(np.mean([r["Tcold"] for r in rows if r[key] == x])) for x in xs]
return dict(x=xs, total=tot, exploit=exp, Tcold=tc,
slope_total=slope(xs, tot), slope_exploit=slope(xs, exp),
slope_Tcold=slope(xs, tc))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="outputs/claim1_rate.json")
ap.add_argument("--seeds", type=int, default=5)
ap.add_argument("--N", type=int, default=20)
ap.add_argument("--workers", type=int, default=12)
args = ap.parse_args()
S = list(range(args.seeds))
jobs, tags = [], []
def add(T, K, d, tag):
for s in S:
jobs.append((T, K, d, s, args.N)); tags.append(tag)
Ts = [1 << k for k in range(13, 18)]
for (K, d) in [(3, 5), (5, 5), (10, 5), (5, 10)]:
for T in Ts:
add(T, K, d, f"T:K{K}_d{d}")
for K in [2, 3, 5, 10, 20]:
add(TMAX, K, 5, "K")
for d in [2, 3, 5, 10, 20]:
add(TMAX, 5, d, "d")
print(f"{len(jobs)} simulations on {args.workers} workers "
f"(T up to {TMAX}, {args.seeds} seeds)")
t0 = time.time()
with ProcessPoolExecutor(max_workers=args.workers) as ex:
rows = list(ex.map(_one, jobs, chunksize=1))
for r, tg in zip(rows, tags):
r["tag"] = tg
print(f"simulations done in {time.time() - t0:.0f}s")
res = {"meta": dict(seeds=args.seeds, N=args.N, Tmax=TMAX,
setting="Appendix F Setting 1 parameters"), "fits": {}}
for (K, d) in [(3, 5), (5, 5), (10, 5), (5, 10)]:
tg = f"T:K{K}_d{d}"
res["fits"][tg] = aggregate([r for r in rows if r["tag"] == tg], "T")
f = res["fits"][tg]
print(f" {tg:<12} exponent in T: total={f['slope_total']:+.3f} "
f"exploit={f['slope_exploit']:+.3f} (theory +0.500)")
for key in ("K", "d"):
res["fits"][key] = aggregate([r for r in rows if r["tag"] == key], key)
f = res["fits"][key]
print(f" {key} sweep exponent in {key}: total={f['slope_total']:+.3f} "
f"exploit={f['slope_exploit']:+.3f} (theory +0.500); "
f"T_cold exponent {f['slope_Tcold']:+.3f}")
# ---- Control for the environment's own K-dependence ---------------------
# In Setting 1 the arm means are mu_i = 0.5 + x'beta_i with beta_i ~ N(0, (1/5)I_d)
# and ||x|| = 1, so mu_1..mu_K are iid and E[max_i mu_i - mu_j] grows like
# sqrt(2 var log K) purely from taking a max over more arms. A policy of FIXED
# quality therefore already accrues more regret at larger K. We measure that
# baseline gap by Monte Carlo and refit the K exponent on regret normalised by it,
# so what remains is the algorithmic K-dependence that Theorem 2 claims is sqrt(K).
rng = np.random.default_rng(12345)
Ks = res["fits"]["K"]["x"]
gap = []
for K in Ks:
mu = 0.5 + rng.normal(scale=np.sqrt(1 / 5), size=(200_000, K))
gap.append(float(np.mean(mu.max(1) - mu.mean(1))))
norm = [r / g for r, g in zip(res["fits"]["K"]["exploit"], gap)]
res["fits"]["K"]["env_gap"] = gap
res["fits"]["K"]["slope_env_gap"] = slope(Ks, gap)
res["fits"]["K"]["exploit_normalised"] = norm
res["fits"]["K"]["slope_exploit_normalised"] = slope(Ks, norm)
print(f" K sweep environment mean gap exponent {slope(Ks, gap):+.3f}; "
f"regret normalised by it has K exponent "
f"{slope(Ks, norm):+.3f} (theory +0.500)")
# ---- Is the paper's *explicit* bound satisfied, point by point? ---------
# Eq. (E.30) final line, which is what Theorem 2's O~(sqrt(Kd(T-T_cold))) abbreviates:
# R(T) <= tau_{m0-1} + 151 sigma sqrt(K d T) + sqrt( 8 (T - tau_{m0-1}) log(2/delta) )
# with sigma = 0.05 (Setting 1), delta = 0.05, m0 = ceil(2 + log2 N).
sigma, delta = 0.05, 0.05
m0 = int(np.ceil(2 + np.log2(args.N)))
tau0 = 2.0 ** (m0 - 1)
bound_rows = []
for r in rows:
T, K, d = r["T"], r["K"], r["d"]
rhs = (tau0 + 151 * sigma * np.sqrt(K * d * T)
+ np.sqrt(8 * max(T - tau0, 0) * np.log(2 / delta)))
bound_rows.append(dict(T=T, K=K, d=d, seed=r["seed"], measured=r["total"],
bound=float(rhs), slack=float(rhs / r["total"])))
n_viol = sum(1 for b in bound_rows if b["measured"] > b["bound"])
slacks = [b["slack"] for b in bound_rows]
res["bound_check"] = dict(
formula="tau_{m0-1} + 151 sigma sqrt(KdT) + sqrt(8(T-tau)log(2/delta))",
sigma=sigma, delta=delta, m0=m0, tau_m0_minus_1=tau0,
n_points=len(bound_rows), n_violations=n_viol,
min_slack=float(min(slacks)), max_slack=float(max(slacks)),
median_slack=float(np.median(slacks)), rows=bound_rows)
print(f" Eq. E.30 bound: {len(bound_rows) - n_viol}/{len(bound_rows)} points satisfied; "
f"slack (bound/measured) min={min(slacks):.1f}x median={np.median(slacks):.1f}x "
f"max={max(slacks):.1f}x")
res["rows"] = rows
res["wall_clock_s"] = time.time() - t0
os.makedirs("outputs", exist_ok=True)
json.dump(res, open(args.out, "w"))
print(f"wrote {args.out} [{res['wall_clock_s']:.0f}s]")
if __name__ == "__main__":
main()