File size: 7,786 Bytes
d656622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""ILS head-to-head vs UID64's ACTUAL submissions on harvested ground-truth rows.

Chain per row (offline, generous time -- this is a capability probe, not production):
  cp (20s) -> BB refine from cp (8s) -> ILS from best-of (rest of budget)
Compare chain-best score/density/margin against uid64's leaderboard score for the
same row AND their actual submitted PNG re-scored on our faithful model.
Idle-gated to the miner's cycle; single-proc guarded; replay writes off.

Usage: python3 scripts/ils_h2h.py <n_rows> [total_budget_per_row=70]
"""
import os, sys, io, json, time, base64, urllib.request

os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
sys.path.insert(0, "/root/Perturb")

import numpy as np
import torch
from PIL import Image

from miner_lib.victim import VictimModel
from miner_lib.config import AttackConfig
from miner_lib.scoring import quick_score
from miner_lib.converge_prune_attack import run_converge_prune_attack
from miner_lib.bb_l0_attack import run_bb_l0_attack
from miner_lib.ils_attack import run_ils_attack

EDGE = "/root/edge_cases"
LOG = "/root/ils_h2h.log"
API = "https://api.perturbai.io/api/v1"


def log(msg):
    line = f"{time.strftime('%H:%M:%S')} {msg}"
    print(line, flush=True)
    with open(LOG, "a") as f:
        f.write(line + "\n")


def last_submit_age():
    try:
        mt = os.path.getmtime("/root/miner_live.log")
        with open("/root/miner_live.log", "rb") as f:
            try:
                f.seek(-200000, 2)
            except OSError:
                pass
                tail = f.read().decode(errors="ignore")
    except Exception:
        return 999.0
    import re
    ts = None
    for m in re.finditer(r"(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d).*Submitted task", tail):
        ts = m.group(1)
    if ts is None:
        return 999.0
    t = time.mktime(time.strptime(ts, "%Y-%m-%d %H:%M:%S"))
    return time.time() - t


def gate(min_idle=42.0):
    while True:
        age = last_submit_age()
        if age >= min_idle:
            return
        time.sleep(5)


def img_from_url(u):
    req = urllib.request.Request(u, headers={"User-Agent": "probe"})
    return np.asarray(Image.open(io.BytesIO(urllib.request.urlopen(req, timeout=25).read())).convert("RGB"))


def load_gt_rows(n_rows):
    """rows where uid64 submitted AND we have the clean input locally."""
    by_row = {}
    with open(f"{EDGE}/manifest.jsonl") as f:
        for line in f:
            try:
                d = json.loads(line)
            except Exception:
                continue
            if str(d.get("uid")) == "64":
                by_row[d["row"]] = d
    rows = []
    for row, d in by_row.items():
        p = f"{EDGE}/inputs/{row}.png"
        u = f"{EDGE}/64/{row}.png"
        if os.path.exists(p) and os.path.exists(u):
            rows.append((row, d))
    rows.sort(key=lambda rd: rd[1].get("score", 0))
    # stratify: hardest third, middle third, easiest third
    k = max(1, len(rows) // 3)
    picked = rows[:k][: n_rows // 3 + 1] + rows[k:2*k][:(n_rows - n_rows//3)//2 + 1] + rows[2*k:][-((n_rows+2)//3):]
    seen, out = set(), []
    for r in picked:
        if r[0] not in seen:
            seen.add(r[0]); out.append(r)
    return out[:n_rows]


def dens_of(xa_u8, x0_u8):
    d = xa_u8.astype(np.int16) - x0_u8.astype(np.int16)
    return float((d != 0).sum()) / d.size


def main():
    n_rows = int(sys.argv[1]) if len(sys.argv) > 1 else 12
    total_b = float(sys.argv[2]) if len(sys.argv) > 2 else 70.0
    me = os.getpid()
    os.system(f"echo {me} > /tmp/ils_h2h.pid")

    dev = "cuda:0"
    v = VictimModel(device=dev)
    rows = load_gt_rows(n_rows)
    log(f"=== ILS h2h start: {len(rows)} GT rows, {total_b:.0f}s/row ===")
    torch.backends.cudnn.benchmark = True

    tot_us = tot_u64 = 0.0; w = l = t = 0; n = 0
    for row, meta in rows:
        gate()
        clean = np.asarray(Image.open(f"{EDGE}/inputs/{row}.png").convert("RGB"))
        x0f = torch.tensor(clean.astype(np.float32) / 255.0).permute(2, 0, 1).to(dev)
        x0 = (x0f * 255).round().long()
        with torch.no_grad():
            _, _, cl = v.evaluate(x0f, 0)
            ti = int(cl.argmax().item())

        cfg = AttackConfig(time_budget_seconds=33)
        cfg.replay_enabled = False; cfg.replay_save = False

        t0 = time.time()
        a = run_converge_prune_attack(v, x0f, ti, cfg, deadline=time.time() + 20)
        warm = None
        cp_best_s = -1.0
        if a.flipped and a.x_adv is not None:
            xf = a.x_adv.float() / 255.0
            _, m, lg = v.evaluate(xf, ti)
            s, _ = quick_score(x0f, xf, lg, ti)
            cp_best_s = s
            warm = xf - x0f
        bb_s = -1.0
        if warm is not None and time.time() - t0 < total_b - 15:
            b = run_bb_l0_attack(v, x0f, ti, cfg, deadline=min(time.time() + 8, t0 + total_b - 10),
                                 warm_delta=warm)
            if b.flipped and b.x_adv is not None and b.score > cp_best_s:
                warm = b.x_adv.float() / 255.0 - x0f
                bb_s = b.score
        # fallback seed for rows where cp/bb find nothing: dense sign-climb (offline validation only)
        if warm is None:
            du = torch.zeros_like(x0f); gm = torch.zeros_like(x0f)
            for s_ in range(160):
                if time.time() - t0 > total_b - 12:
                    break
                d = (du / 255.).unsqueeze(0).requires_grad_(True)
                r = v.net(v._differentiable_preprocess(x0f.unsqueeze(0) + d))[0]
                g = torch.autograd.grad(r.masked_fill(torch.arange(1000, device=dev) == ti, -1e12).max() - r[ti], d)[0][0]
                with torch.no_grad():
                    gm = 0.9 * gm + g
                    du = (du + torch.sign(gm)).clamp(-1, 1)
                if s_ % 20 == 19:
                    with torch.no_grad():
                        _, m_, _ = v.evaluate((x0f + du / 255.).clamp(0, 1).unsqueeze(0), ti)
                    if m_ >= 11:
                        break
            with torch.no_grad():
                _, mm, ll = v.evaluate((x0f + du / 255.).clamp(0, 1).unsqueeze(0), ti)
            if int(ll.argmax().item()) != ti and mm > 0:
                warm = du / 255.
        ils = run_ils_attack(v, x0f, ti, cfg,
                             deadline=t0 + total_b, warm_delta=warm)
        el = time.time() - t0

        # uid64 ground truth on our model
        u_img = np.asarray(Image.open(f"{EDGE}/64/{row}.png").convert("RGB"))
        if u_img.shape != clean.shape:
            log(f"row {row}: shape mismatch, skip"); continue
        xa = torch.tensor(u_img.astype(np.float32) / 255.0).permute(2, 0, 1).to(dev)
        _, u_m, ulg = v.evaluate(xa, ti)
        u_s, _ = quick_score(x0f, xa, ulg, ti)
        u_d = dens_of(u_img, clean)

        ours = max(ils.score if ils.flipped else -1, cp_best_s, bb_s)
        strat = "ils" if ils.flipped and ils.score >= max(cp_best_s, bb_s) else ("bb" if bb_s >= cp_best_s else "cp")
        od = ((ils.rmse * 255) ** 2 * 100) if (strat == "ils") else -1
        delta = ours - u_s
        n += 1; tot_us += ours; tot_u64 += u_s
        tag = "WIN " if delta > 1e-4 else ("LOSS" if delta < -1e-4 else "tie ")
        w += tag == "WIN "; l += tag == "LOSS"; t += tag == "tie "
        log(f"[{n:2d}/{len(rows)}] row {row:6d} ti={ti} | us({strat}) {ours:.4f} "
            f"(cp {cp_best_s:.4f}, bb {bb_s:.4f}, ils {ils.score:.4f} d={od:.1f}% r={ils.rounds}) "
            f"| U64 {u_s:.4f} m={u_m:5.2f} d={u_d*100:5.1f}% | {tag} {delta:+.4f} ({el:.0f}s)")
        del xa
        torch.cuda.empty_cache()

    if n:
        log(f"=== DONE n={n}: US {tot_us/n:.4f}  U64 {tot_u64/n:.4f}  Δ{(tot_us-tot_u64)/n:+.4f}  W/L/T={w}/{l}/{t} ===")


if __name__ == "__main__":
    main()