File size: 5,511 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
"""THE live-relevant test: run gen's ACTUAL pipeline to get its real support+target, then re-optimize
the signs on that SAME support+target with budget-APGD, and compare SCORE. Also compares to cp's
support (converge-prune) + APGD. This is the wireable change; no oracle data.
gen_current vs gen+APGD vs cp+APGD vs competitor, by score."""
import os, sys, json, time
sys.path.insert(0, "/root/Perturb"); sys.path.insert(0, "/root/Perturb/scripts")
import numpy as np, 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 gen_attack import run_gen_attack
from miner_lib.converge_prune_attack import run_converge_prune_attack

dev = "cuda:0"; COND = "/root/supgen4/cond"
v = VictimModel(device=dev); eps = 1 / 255.

def gate():
    while int(time.time()) % 120 < 48:
        time.sleep(2)

def score_of(x0f, xi, ti):
    xf = xi.float() / 255.
    pred, m, lg = v.evaluate(xf, ti)
    if pred == ti:
        return -1.0, float(m), 100.0 * float((xi != (x0f * 255).round().long()).float().mean())
    s, det = quick_score(x0f, xf, lg, ti)
    dn = 100.0 * float((xi != (x0f * 255).round().long()).float().mean())
    return (float(s) if det.get("reason") == "success" else -1.0), float(m), dn

def loss_grad(x0f, delta, ti, tg):
    d = delta.detach().requires_grad_(True)
    row = v.net(v._differentiable_preprocess((x0f + d).clamp(0, 1).unsqueeze(0)))[0]
    L = row[tg] - row[ti]
    return torch.autograd.grad(L, d)[0], float(L.detach())

def apgd_delta(x0f, ti, tg, mask, seed, n_iter=50, n_restarts=2):
    m = mask.float(); best = -1e9; bestd = None
    ck = set(int(p * n_iter) for p in (0.22, 0.44, 0.66, 0.85))
    for rst in range(n_restarts):
        delta = (eps * (torch.sign(seed) if rst == 0 else torch.sign(torch.randn_like(seed))) * m).clamp(-eps, eps)
        step = 2.0 * eps; g, L = loss_grad(x0f, delta, ti, tg); Lb = L; prev = delta.clone(); Lc = Lb
        delta = (delta + step * torch.sign(g) * m).clamp(-eps, eps)
        for i in range(n_iter):
            g, L = loss_grad(x0f, delta, ti, tg)
            with torch.no_grad():
                z = (delta + step * torch.sign(g) * m).clamp(-eps, eps)
                delta2 = (delta + 0.75 * (z - delta) + 0.25 * (delta - prev)).clamp(-eps, eps) * m
                prev = delta.clone(); delta = delta2; Lb = max(Lb, L)
                if (i + 3) % 6 == 0:
                    xi = ((x0f + delta).clamp(0, 1) * 255).round().long()
                    _, mm, _ = v.evaluate(xi.float() / 255., ti)
                    if mm > best:
                        best = float(mm); bestd = delta.clone()
                if i in ck:
                    if Lb <= Lc + 1e-3:
                        step = max(step * 0.5, 0.05 * eps)
                    Lc = Lb
    return bestd

cfg = AttackConfig(); cfg.gen_head_path = "/root/supgen3/head_ep5.pt"; cfg.gen_ladder = (0.08,)
cfg.gen_enabled = False; cfg.gen_pilot_enabled = False; cfg.gen_pilot_unstarved_enabled = False

va = [json.loads(l) for l in open("/root/supgen3/val.jsonl")]
va = [it for it in va if os.path.exists(f"{COND}/{it['row']}.npz")][:10]
rows = []
print("row | gen_cur | gen+APGD | cp+APGD | comp | best_delta_vs_comp", flush=True)
for it in va:
    gate()
    clean = np.asarray(Image.open(it["clean"]).convert("RGB")).astype(np.float32)
    adv = np.asarray(Image.open(it["adv"]).convert("RGB")).astype(np.float32)
    if adv.shape != clean.shape:
        continue
    x = torch.from_numpy(clean / 255.).permute(2, 0, 1).to(dev)
    x0i = (x * 255).round().long()
    ti = int(v.evaluate(x, 0)[2].argmax())
    cs, cm, cd = score_of(x, torch.from_numpy(adv).round().long().permute(2, 0, 1).to(dev), ti)
    # --- gen current ---
    gr = run_gen_attack(v, x, ti, cfg, deadline=time.time() + 26)
    if gr.x_adv is None or not gr.flipped:
        print(f"{it['row']} | genFAIL | - | - | {cs:.4f}", flush=True); continue
    gs, gm, gd = score_of(x, gr.x_adv, ti)
    gtg = gr.tg_used if gr.tg_used is not None else int(v.evaluate((gr.x_adv.float()/255.), ti)[2].argmax())
    # --- gen support + APGD ---
    gmask = (gr.x_adv != x0i)
    seed = (gr.x_adv.float() - x0i.float())
    gad = apgd_delta(x, ti, gtg, gmask, torch.sign(seed))
    if gad is not None:
        gaxi = ((x + gad).clamp(0, 1) * 255).round().long()
        gas, gam, gad2 = score_of(x, gaxi, ti)
    else:
        gas = -1
    # --- cp support + APGD ---
    gate()
    cp = run_converge_prune_attack(v, x, ti, cfg, deadline=time.time() + 20)
    if cp.x_adv is not None:
        cmask = (cp.x_adv != x0i); cseed = (cp.x_adv.float() - x0i.float())
        ctg = int(v.evaluate((cp.x_adv.float()/255.), ti)[2].argmax())
        cad = apgd_delta(x, ti, ctg, cmask, torch.sign(cseed))
        if cad is not None:
            caxi = ((x + cad).clamp(0, 1) * 255).round().long()
            cas, cam, cad2 = score_of(x, caxi, ti)
        else:
            cas = -1
    else:
        cas = -1
    rows.append((gs, gas, cas, cs))
    print(f"{it['row']} | {gs:.4f}(m{gm:.1f},{gd:.0f}%) | {gas:.4f} | {cas:.4f} | {cs:.4f}", flush=True)
import numpy as np
R = np.array(rows)
if len(R):
    print(f"--- MEANS gen_cur={R[:,0].mean():.4f} gen+APGD={R[:,1].mean():.4f} cp+APGD={R[:,2].mean():.4f} comp={R[:,3].mean():.4f} ---", flush=True)
    print(f"--- gen+APGD vs gen_cur: {(R[:,1]>R[:,0]).sum()}/{len(R)} wins, mean delta {R[:,1].mean()-R[:,0].mean():+.4f} ---", flush=True)
print("GENAPGD_DONE", flush=True)