File size: 14,371 Bytes
4780f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""exp02_cs_coverage -- empirical anytime-valid coverage of the lifted welfare
confidence sequence (Claim 1 / Theorem 4.1) and the fixed-policy corollary
(specs/exp02_cs_coverage.md). No dataset (paper is fully simulated).
"""

import argparse
import json
import math
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import numpy as np

from core import cs
from core.instance import gini_w, make_instance
from core.oracles import oracle
from core.parallel import run_grid
from core.rounding import dependent_round
from core.swf import swf

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
RESULTS_PATH = os.path.join(ROOT, "results", "exp02.json")

SEED_BASE = 10_000
N = 20  # instance size (spec: reduced from paper's 50; theorem is n-agnostic)
TOL = 1e-9

# Must match gates.py EXP02_GRID / EXP02_KS / EXP02_DELTAS exactly.
FULL_GRID = [("wpm", "-inf"), ("wpm", -2.0), ("wpm", 0.0), ("wpm", 1.0),
             ("kolm", "-inf"), ("kolm", -2.0), ("kolm", 0.0), ("gini", None)]
FULL_KS = [1, 5, 10]
FULL_DELTAS = [0.1, 0.25]

R_CANDIDATES_FULL = [2000, 1000, 500]
WALL_BUDGET_SEC = 3 * 3600


def log(msg):
    print(f"[exp02] {msg}", file=sys.stderr, flush=True)


def qlabel(q):
    if q is None:
        return None
    if isinstance(q, str):
        return q
    return float(q)


def make_t_grid(T, n_points):
    pts = np.unique(np.round(np.geomspace(1, T, n_points)).astype(int))
    pts = pts[(pts >= 1) & (pts <= T)]
    if pts[0] != 1:
        pts = np.concatenate(([1], pts))
    if pts[-1] != T:
        pts = np.concatenate((pts, [T]))
    return sorted(int(t) for t in np.unique(pts))


# ------------------------------------------------------------- simulation

def simulate_replicate(mu, alpha, beta, w, family, q, k, p_star, W_star, T, delta, seed, t_grid):
    n = len(mu)
    rng = np.random.default_rng(seed)
    init_rounds = math.ceil(n / k)
    p_fix = np.full(n, k / n)
    W_fix_true = swf(mu * p_fix, family, w, q)

    mu_up = np.full(n, cs.U_MAX)
    mu_low = np.full(n, cs.U_MIN)
    N_i = np.zeros(n)
    mu_hat = np.zeros(n)

    L = len(t_grid)
    pointwise_miss = np.zeros(L, dtype=bool)
    running_missed = np.zeros(L, dtype=bool)
    width_at_grid = np.zeros(L, dtype=float)
    gi = 0

    missed_so_far = False
    link_ever_bad = {"i": False, "ii": False, "iii": False, "iv": False}
    fixed_ever_bad = False

    for t in range(1, T + 1):
        p_up_t = oracle(mu_up, family, w, q, k)
        p_low_t = oracle(mu_low, family, w, q, k)
        W_up_t = swf(mu_up * p_up_t, family, w, q)
        W_low_t = swf(mu_low * p_low_t, family, w, q)
        covered_t = (W_low_t <= W_star + TOL) and (W_up_t >= W_star - TOL)
        if not covered_t:
            missed_so_far = True

        swf_mu_p_low = swf(mu * p_low_t, family, w, q)
        swf_muup_p_star = swf(mu_up * p_star, family, w, q)
        if not (W_star >= swf_mu_p_low - TOL):
            link_ever_bad["i"] = True
        if not (swf_mu_p_low >= W_low_t - TOL):
            link_ever_bad["ii"] = True
        if not (swf_muup_p_star >= W_star - TOL):
            link_ever_bad["iii"] = True
        if not (W_up_t >= swf_muup_p_star - TOL):
            link_ever_bad["iv"] = True

        W_fix_low = swf(mu_low * p_fix, family, w, q)
        W_fix_up = swf(mu_up * p_fix, family, w, q)
        if not (W_fix_low <= W_fix_true + TOL and W_fix_up >= W_fix_true - TOL):
            fixed_ever_bad = True

        if gi < L and t == t_grid[gi]:
            pointwise_miss[gi] = not covered_t
            running_missed[gi] = missed_so_far
            width_at_grid[gi] = W_up_t - W_low_t
            gi += 1

        if t <= init_rounds:
            idx = [((t - 1) * k + j) % n for j in range(k)]
            S_t = np.array(idx, dtype=int)
        else:
            S_t = np.nonzero(dependent_round(p_up_t, rng))[0]

        for i in S_t:
            N_old = N_i[i]
            u_ti = 0.1 + 0.9 * rng.beta(alpha[i], beta[i])
            mu_hat[i] = (N_old * mu_hat[i] + u_ti) / (N_old + 1.0)
            N_i[i] = N_old + 1.0
            mu_up[i] = float(np.clip(cs.update_up(mu_hat[i], N_old, n, delta), cs.U_MIN, cs.U_MAX))
            mu_low[i] = float(np.clip(cs.update_low(mu_hat[i], N_old, n, delta), cs.U_MIN, cs.U_MAX))

    return dict(
        any_miss=missed_so_far,
        pointwise_miss=pointwise_miss,
        running_missed=running_missed,
        width_at_grid=width_at_grid,
        link_ever_bad=link_ever_bad,
        fixed_ever_bad=fixed_ever_bad,
    )


def simulate_chunk(mu, alpha, beta, w, family, q, k, p_star, W_star, T, delta, seeds, t_grid):
    L = len(t_grid)
    sum_any_miss = 0
    sum_pointwise = np.zeros(L)
    sum_running = np.zeros(L)
    sum_width = np.zeros(L)
    sum_link = {"i": 0, "ii": 0, "iii": 0, "iv": 0}
    sum_fixed = 0
    for seed in seeds:
        res = simulate_replicate(mu, alpha, beta, w, family, q, k, p_star, W_star, T, delta, seed, t_grid)
        sum_any_miss += int(res["any_miss"])
        sum_pointwise += res["pointwise_miss"]
        sum_running += res["running_missed"]
        sum_width += res["width_at_grid"]
        for key in sum_link:
            sum_link[key] += int(res["link_ever_bad"][key])
        sum_fixed += int(res["fixed_ever_bad"])
    return dict(n=len(seeds), sum_any_miss=sum_any_miss, sum_pointwise=sum_pointwise.tolist(),
                sum_running=sum_running.tolist(), sum_width=sum_width.tolist(),
                sum_link=sum_link, sum_fixed=sum_fixed)


def combine_chunks(chunk_results, t_grid, family, q, k, delta, W_star):
    R = sum(c["n"] for c in chunk_results)
    sum_any_miss = sum(c["sum_any_miss"] for c in chunk_results)
    sum_pointwise = np.sum([c["sum_pointwise"] for c in chunk_results], axis=0)
    sum_running = np.sum([c["sum_running"] for c in chunk_results], axis=0)
    sum_width = np.sum([c["sum_width"] for c in chunk_results], axis=0)
    sum_link = {key: sum(c["sum_link"][key] for c in chunk_results) for key in ("i", "ii", "iii", "iv")}
    sum_fixed = sum(c["sum_fixed"] for c in chunk_results)

    anytime_miss_rate = sum_any_miss / R
    anytime_miss_se = math.sqrt(anytime_miss_rate * (1.0 - anytime_miss_rate) / R)
    pointwise_miss_rate = (sum_pointwise / R).tolist()
    running_miss_rate = (sum_running / R).tolist()
    mean_width = (sum_width / R).tolist()
    link_miss_rates = {key: sum_link[key] / R for key in sum_link}
    fixed_policy_anytime_miss_rate = sum_fixed / R

    t_arr = np.array(t_grid, dtype=float)
    mw_arr = np.array(mean_width, dtype=float)
    last_decade = t_arr >= (t_arr[-1] / 10.0)
    if last_decade.sum() < 2:
        last_decade = np.ones_like(t_arr, dtype=bool)
    slope, _ = np.polyfit(np.log(t_arr[last_decade]), np.log(np.maximum(mw_arr[last_decade], 1e-300)), 1)

    return {
        "family": family, "q": qlabel(q), "k": k, "delta": delta, "R": R,
        "anytime_miss_rate": anytime_miss_rate, "anytime_miss_se": anytime_miss_se,
        "running_miss_rate": running_miss_rate,
        "pointwise_miss_rate": pointwise_miss_rate,
        "link_miss_rates": link_miss_rates,
        "fixed_policy_anytime_miss_rate": fixed_policy_anytime_miss_rate,
        "mean_width": mean_width,
        "width_decay_alpha": float(slope),
        "W_star": float(W_star),
    }


# --------------------------------------------------------------- grid setup

def build_cells(toy):
    if toy:
        combos = [("wpm", "-inf"), ("wpm", 0.0), ("kolm", -2.0), ("gini", None)]
        ks, deltas = [1, 5], [0.1]
        T, R, n_grid_points, chunk_size = 60, 25, 8, 10
    else:
        combos = FULL_GRID
        ks, deltas = FULL_KS, FULL_DELTAS
        T, R, n_grid_points, chunk_size = 2000, 2000, 40, 50
    cells = [(f, q, k, d) for f, q in combos for k in ks for d in deltas]
    return cells, T, R, n_grid_points, chunk_size


def calibrate_and_pick_R(mu, alpha, beta, pstar_cache, cells_spec, T, n_jobs, candidates):
    T_probe = 100
    probe_grid = make_t_grid(T_probe, 5)
    combos = sorted(set((f, qlabel(q), k) for f, q, k, d in cells_spec),
                     key=lambda c: (c[0], str(c[1]), c[2]))
    step_time = {}
    for family, qk, k in combos:
        q_actual = next(q for f, q, kk, d in cells_spec if f == family and qlabel(q) == qk and kk == k)
        p_star, W_star, w_eff = pstar_cache[(family, qk, k)]
        t0 = time.time()
        simulate_replicate(mu, alpha, beta, w_eff, family, q_actual, k, p_star, W_star,
                            T_probe, 0.1, 999_999, probe_grid)
        dt = (time.time() - t0) / T_probe
        step_time[(family, qk, k)] = dt
        log(f"calibration family={family} q={qk} k={k}: {dt * 1e6:.2f} us/step")

    total_step_time = sum(step_time[(f, qlabel(q), k)] for f, q, k, d in cells_spec)
    note = None
    chosen = candidates[-1]
    for R_cand in candidates:
        projected = total_step_time * T * R_cand / n_jobs
        log(f"projected wall time for R={R_cand}: {projected / 3600:.2f} h")
        if projected <= WALL_BUDGET_SEC:
            chosen = R_cand
            if R_cand < candidates[0]:
                note = (f"R reduced from {candidates[0]} to {R_cand}: projected wall time at "
                        f"R={candidates[0]} exceeded the {WALL_BUDGET_SEC / 3600:.0f}h budget")
            break
    else:
        chosen = candidates[-1]
        projected = total_step_time * T * chosen / n_jobs
        note = (f"R reduced to floor {chosen}; projected wall time still "
                f"{projected / 3600:.2f}h, exceeds {WALL_BUDGET_SEC / 3600:.0f}h budget")
    return chosen, note


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--toy", action="store_true")
    args = ap.parse_args()
    t0 = time.time()

    n_jobs = max(1, min(int(os.environ.get("JOB_CORES", "4")), 12))
    log(f"JOB_CORES(n_jobs)={n_jobs} numpy={np.__version__} toy={args.toy}")

    instance = make_instance(n=N, weight_decay="exp", seed=0)
    mu, alpha, beta, w = instance["mu"], instance["alpha"], instance["beta"], instance["w"]
    log(f"instance built: n={N}, mu[:5]={np.round(mu[:5], 4).tolist()}")

    cells_spec, T, R, n_grid_points, chunk_size = build_cells(args.toy)
    t_grid = make_t_grid(T, n_grid_points)
    log(f"cells={len(cells_spec)} T={T} R={R} t_grid: {len(t_grid)} points "
        f"[{t_grid[0]}..{t_grid[-1]}]")

    pstar_cache = {}
    for family, q, k, delta in cells_spec:
        key = (family, qlabel(q), k)
        if key in pstar_cache:
            continue
        w_eff = gini_w(w, instance["weight_decay"]) if family == "gini" else w
        p_star = oracle(mu, family, w_eff, q, k)
        W_star = swf(mu * p_star, family, w_eff, q)
        pstar_cache[key] = (p_star, W_star, w_eff)
    log(f"precomputed p_star/W_star for {len(pstar_cache)} (family,q,k) combos")

    R_used, R_note = R, None
    if not args.toy:
        R_used, R_note = calibrate_and_pick_R(mu, alpha, beta, pstar_cache, cells_spec, T, n_jobs,
                                               R_CANDIDATES_FULL)
    log(f"replicates per cell: R={R_used}" + (f" ({R_note})" if R_note else ""))

    tasks = []
    for cell_idx, (family, q, k, delta) in enumerate(cells_spec):
        key = (family, qlabel(q), k)
        p_star, W_star, w_eff = pstar_cache[key]
        seeds_all = [SEED_BASE + r for r in range(R_used)]
        for start in range(0, R_used, chunk_size):
            chunk_seeds = seeds_all[start:start + chunk_size]
            tasks.append((cell_idx, family, q, k, delta, p_star, W_star, w_eff, T, chunk_seeds))
    log(f"built {len(tasks)} chunk tasks across {len(cells_spec)} cells (chunk_size={chunk_size})")

    def _run_chunk_task(task):
        cell_idx, family, q, k, delta, p_star, W_star, w_eff, T_, seeds = task
        res = simulate_chunk(mu, alpha, beta, w_eff, family, q, k, p_star, W_star, T_, delta, seeds, t_grid)
        return cell_idx, res

    t_sim0 = time.time()
    raw_results = run_grid(_run_chunk_task, tasks, n_jobs=n_jobs)
    log(f"all {len(raw_results)} chunk tasks completed in {time.time() - t_sim0:.1f}s")

    by_cell = {i: [] for i in range(len(cells_spec))}
    for cell_idx, chunk_res in raw_results:
        by_cell[cell_idx].append(chunk_res)

    cells_out = []
    for cell_idx, (family, q, k, delta) in enumerate(cells_spec):
        _, W_star, _ = pstar_cache[(family, qlabel(q), k)]
        cell_out = combine_chunks(by_cell[cell_idx], t_grid, family, q, k, delta, W_star)
        cells_out.append(cell_out)
        log(f"cell family={family} q={q} k={k} delta={delta}: "
            f"anytime_miss={cell_out['anytime_miss_rate']:.4f} se={cell_out['anytime_miss_se']:.4f} "
            f"alpha={cell_out['width_decay_alpha']:.3f}")

    max_anytime = max((c["anytime_miss_rate"] for c in cells_out), default=0.0)
    n_exceed_delta = sum(1 for c in cells_out if c["anytime_miss_rate"] > c["delta"])
    n_exceed_delta_3se = sum(1 for c in cells_out
                              if c["anytime_miss_rate"] > c["delta"] + 3 * c["anytime_miss_se"])

    meta = dict(
        exp="exp02", n_cores_used=n_jobs, wall_time_sec=time.time() - t0,
        seed_base=SEED_BASE, numpy_version=np.__version__, n=N, T=T, R=R_used,
        ambiguities={"beta_prior": "U[1,5] seed 0", "mu_up_init": 1.0, "mu_low_init": 0.1,
                     "clip_range": [0.1, 1.0], "init_rule": "round_robin"},
    )
    if R_note:
        meta["R_reduction_note"] = R_note

    out = dict(
        meta=meta,
        status="ok",
        t_grid=t_grid,
        cells=cells_out,
        summary=dict(n_cells=len(cells_out), max_anytime_miss_rate=max_anytime,
                     n_cells_exceeding_delta=n_exceed_delta,
                     n_cells_exceeding_delta_plus_3se=n_exceed_delta_3se),
    )

    os.makedirs(os.path.dirname(RESULTS_PATH), exist_ok=True)
    with open(RESULTS_PATH, "w") as fh:
        json.dump(out, fh, indent=2)

    elapsed = time.time() - t0
    print(f"exp02 done in {elapsed:.1f}s (toy={args.toy}, n_jobs={n_jobs}, R={R_used})")
    print(f"cells: {len(cells_out)}, max_anytime_miss_rate={max_anytime:.4f}")
    print(f"n_cells_exceeding_delta={n_exceed_delta}, n_cells_exceeding_delta_plus_3se={n_exceed_delta_3se}")
    print(f"results written to {RESULTS_PATH}")
    return 0


if __name__ == "__main__":
    sys.exit(main())