File size: 5,659 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
"""Homotopy attack (VITA-Group nmAPG) adapted to OUR victim at amp-1 (eps=1/255), on the 5 gold rows.
Pipeline per row: homotopy(bare-flip, min-L0) -> ultra-sparse support -> sign-climb to m10 (fix-support
sigma-zero, validated to reproduce teacher margin from a good support) -> real Perturb score.
Answers: is homotopy's support sparser than UID64 AND m10-capable? Emits HOMO_DONE."""
import os, sys, json, time, argparse
sys.path.insert(0, "/root/Perturb"); sys.path.insert(0, "/root/Perturb/scripts")
sys.path.insert(0, "/root/SparseADV_Homotopy")
import numpy as np, torch
from torch.autograd import Variable
from PIL import Image
from miner_lib.victim import VictimModel
from miner_lib.scoring import quick_score
import demo_attack as H  # homotopy(), CWLoss(), nmAPG() ...

dev = "cuda:0"; eps = 1.0 / 255.0
v = VictimModel(device=dev)

# BYPASS the slow, eps-0.05-tuned search_lambda: the homotopy loop already anneals lambda
# (dec_factor) from the start value down to the flip point, so a fixed high start works and is fast.
_FL = {"v": 1e-3}
def _fast_search_lambda(*a, **k):
    print("attack lambda (fixed) =", _FL["v"], flush=True)
    return _FL["v"]
H.search_lambda = _fast_search_lambda

ap = argparse.ArgumentParser()
ap.add_argument("--rows", type=int, default=2)
ap.add_argument("--val_c", type=float, default=1.0)
ap.add_argument("--max_update", type=int, default=400)
ap.add_argument("--maxiter", type=int, default=60)
ap.add_argument("--dec_factor", type=float, default=0.95)
ap.add_argument("--climb", type=int, default=80)
ap.add_argument("--fixed_lambda", type=str, default="1e-3", help="comma list of lambdas to sweep")
args = ap.parse_args()
LAMS = [float(x) for x in args.fixed_lambda.split(",")]


class NetWrap(torch.nn.Module):
    def forward(self, x):
        return v.net(v._differentiable_preprocess(x.clamp(0, 1)))
net = NetWrap().to(dev).eval()


def wait_mem(gb):
    need = gb * (1024 ** 3)
    while torch.cuda.mem_get_info()[0] < need:
        time.sleep(3)


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


def sign_climb(x, ti, tg, u0, steps, hold=9.0, kappa=10.0):
    """fix-support sigma-zero: freeze support of u0, optimize signs to drive margin to kappa. best score."""
    C, H, W = x.shape
    umin = torch.clamp(-x / eps, min=-1.0); umax = torch.clamp((1.0 - x) / eps, max=1.0)
    mask = (u0 != 0).float()
    u = u0.clone().clamp(umin, umax).detach().requires_grad_(True)
    opt = torch.optim.Adam([u], lr=1.0)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=steps, eta_min=0.01)
    best = (-1e9, 0.0, 0.0, None)
    for i in range(steps):
        opt.zero_grad(set_to_none=True)
        row = v.net(v._differentiable_preprocess((x + u * eps).clamp(0, 1).unsqueeze(0)))[0]
        other = row.clone(); other[tg] = -1e30
        (other.max() - row[tg] + kappa).clamp(min=0.0).backward()
        with torch.no_grad():
            g = u.grad * mask
            u.grad.copy_(g / g.abs().max().clamp_min(1e-12))
        opt.step(); sched.step()
        with torch.no_grad():
            u.clamp_(umin, umax); u.mul_(mask)
            if (i + 1) % 5 == 0 or i == steps - 1:
                xi = ((x + u * eps).clamp(0, 1) * 255).round().long()
                s, m, dn = score_uint8(x, xi, ti)
                if s > best[0]:
                    best = (s, m, dn, xi.clone())
    return best


def load(p):
    return torch.from_numpy(np.asarray(Image.open(p).convert("RGB")).astype(np.float32) / 255.0).permute(2, 0, 1).to(dev)


recs = [json.loads(l) for l in open("/root/sz_teacher/teacher.jsonl")][:args.rows]
print(f"val_c={args.val_c} max_update={args.max_update} maxiter={args.maxiter} dec={args.dec_factor} climb={args.climb}", flush=True)
print("row | homotopy(bareflip: m,d%) | +signclimb(s,m,d%) | UID64(s,d%) | vs_uid64", flush=True)
for r in recs:
    row = r["row"]; ti = int(r["ti"]); tg = int(r["tg"])
    x = load(r["clean"]); x0i = (x * 255).round().long()
    # UID64 reference (load returns [0,1] -> scale to uint8 0-255)
    u64 = (load(f"/root/edge_cases/64/{row}.png") * 255).round().long()
    us, um, ud = score_uint8(x, u64, ti)
    ori = x.unsqueeze(0).detach()
    for lam in LAMS:
        _FL["v"] = lam
        wait_mem(4)
        t0 = time.time()
        try:
            adv_noise = H.homotopy(loss_type="cw", net=net, original_img=Variable(ori, requires_grad=False),
                                   target_class=tg, original_class=ti, tar=1, max_epsilon=eps,
                                   dec_factor=args.dec_factor, val_c=args.val_c, val_w1=1e-2, val_w2=1e-4,
                                   max_update=args.max_update, maxiter=args.maxiter, val_gamma=0.8)
        except Exception as e:
            print(f"{row} lam={lam} | HOMOTOPY_ERR {type(e).__name__}: {e}", flush=True); continue
        adv = (adv_noise.data + ori).clamp(0, 1)
        xi_h = (adv * 255).round().long().squeeze(0)
        hs, hm, hd = score_uint8(x, xi_h, ti)
        # sign-climb homotopy's support to m10
        u0 = (xi_h - x0i).float()  # delta/eps in {-1,0,1}
        cs, cm, cd, cxi = sign_climb(x, ti, tg, u0, args.climb)
        print(f"{row} lam={lam:.0e} | homo m{hm:.1f} {hd:.1f}% [{time.time()-t0:.0f}s] | "
              f"climb {cs:.4f} m{cm:.1f} {cd:.1f}% | UID64 {us:.4f} {ud:.1f}% | {cs-us:+.4f}", flush=True)
print("HOMO_DONE", flush=True)