File size: 5,508 Bytes
152228b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Contention-safe A/B bench for cp variants (baseline / L1 / L3) vs UID126.

Runs alongside the LIVE miner without starving it: before each row it waits for a
safe slice of the 2-minute task cycle (the miner attacks in the first ~35s after
each even-minute boundary; we only run in the idle remainder). Loads the victim
once and reuses it. Compares each variant's cp-only score to UID126's actual
operating point on the same ImageNet-100 row.

Usage:
  python scripts/cp_bench.py --variant l1 --budget 20 --jsonl /root/lb_val.jsonl --n 12
  python scripts/cp_bench.py --variant baseline --rows 13943,48859 --budget 20
"""
from __future__ import annotations

import argparse
import io
import json
import statistics
import sys
import time
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

import torch

from miner_lib.victim import VictimModel
from miner_lib.config import AttackConfig
from miner_lib.converge_prune_attack import run_converge_prune_attack
from miner_lib.cp_l1_fast import run_cp_l1
from miner_lib.cp_l3_mc import run_cp_l3
from miner_lib.cp_frontier import run_cp_frontier
from perturbnet.imagenet100_bootstrap import load_imagenet100
from perturbnet.image_io import decode_image_b64
from PIL import Image  # noqa: F401

RUNNERS = {"baseline": run_converge_prune_attack, "l1": run_cp_l1, "l3": run_cp_l3,
           "frontier": run_cp_frontier}


def pil_to_tensor(img, device):
    import base64
    b = io.BytesIO(); img.convert("RGB").save(b, format="PNG")
    return decode_image_b64(base64.b64encode(b.getvalue()).decode()).to(device)


def wait_safe_window(budget, gate, guard_start=38.0, guard_end=116.0, pad=6.0):
    """Block until we're inside the idle slice of the 2-min cycle with room to finish.
    The miner attacks pos in [0, ~35]; we run only when pos in [guard_start, guard_end-budget-pad]."""
    if not gate:
        return
    latest_start = guard_end - budget - pad
    while True:
        pos = time.time() % 120.0
        if guard_start <= pos <= latest_start:
            return
        # sleep to the next window opening
        if pos < guard_start:
            time.sleep(min(guard_start - pos, 5.0))
        else:
            time.sleep(min(120.0 - pos + guard_start, 5.0))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--variant", choices=list(RUNNERS), default="baseline")
    ap.add_argument("--compare", default="", help="comma variants to A/B per row, e.g. baseline,l3")
    ap.add_argument("--budget", type=float, default=20.0)
    ap.add_argument("--jsonl", default="/root/lb_val.jsonl")
    ap.add_argument("--n", type=int, default=0, help="limit rows (0=all)")
    ap.add_argument("--rows", default="", help="comma list of specific row indices")
    ap.add_argument("--no-gate", action="store_true", help="disable miner-window gating")
    args = ap.parse_args()

    recs = []
    want = set(int(x) for x in args.rows.split(",")) if args.rows else None
    for line in open(args.jsonl):
        line = line.strip()
        if not line:
            continue
        r = json.loads(line)
        if want is not None and r["row"] not in want:
            continue
        recs.append(r)
    if args.n:
        recs = recs[: args.n]

    ds = load_imagenet100(split="train")
    victim = VictimModel(device="cuda" if torch.cuda.is_available() else "cpu")
    cfg = AttackConfig(time_budget_seconds=args.budget)
    gate = not args.no_gate
    variants = [v.strip() for v in args.compare.split(",") if v.strip()] if args.compare else [args.variant]
    # each variant needs its own safe slot; budget the window for all variants back-to-back
    window_budget = args.budget * len(variants)

    print(f"variants={variants} budget={args.budget}s n_rows={len(recs)} gate={gate}")
    hdr = f"{'row':<9}{'variant':<10}{'ours':<8}{'u126':<8}{'delta':<9}{'m':<7}{'dens%':<8}{'u126_d%':<9}{'ngrad':<7}{'sec'}"
    print(hdr)
    agg = {v: {"ours": [], "dens": []} for v in variants}
    u126 = []; udens = []
    for r in recs:
        row = r["row"]
        if row >= ds.num_rows:
            continue
        u = r.get("uid126")
        if not u:
            continue
        x = pil_to_tensor(ds[row]["image"], victim.device)
        with torch.no_grad():
            ti = int(victim.forward(x).argmax(dim=1).item())
        wait_safe_window(window_budget, gate)
        u126.append(u["score"]); udens.append(u["dens"])
        for v in variants:
            t0 = time.time()
            res = RUNNERS[v](victim, x, ti, cfg, deadline=t0 + args.budget)
            dt = time.time() - t0
            os_ = res.score if res.flipped else 0.0
            agg[v]["ours"].append(os_); agg[v]["dens"].append(res.density)
            print(f"{row:<9}{v:<10}{os_:<8.4f}{u['score']:<8.4f}{os_-u['score']:<+9.4f}{res.margin:<7.2f}"
                  f"{res.density*100:<8.1f}{u['dens']*100:<9.1f}{getattr(res,'n_grad',0):<7}{dt:.1f}")
            sys.stdout.flush()

    print()
    um = statistics.mean(u126) if u126 else 0.0
    for v in variants:
        o = agg[v]["ours"]; d = agg[v]["dens"]
        if not o:
            continue
        print(f"{v:<10}: mean={statistics.mean(o):.4f} u126={um:.4f} delta={statistics.mean(o)-um:+.4f} "
              f"| dens={statistics.mean(d)*100:.1f}% (u126={statistics.mean(udens)*100:.1f}%) "
              f"| beat {sum(1 for a,b in zip(o,u126) if a>b)}/{len(o)}")


if __name__ == "__main__":
    main()