File size: 2,298 Bytes
ff6090a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Forensic: why do floods cross continuously but never bank a valid snap?"""
import os, sys, time, json
import numpy as np, torch
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
sys.path.insert(0, "/root/Perturb")
from PIL import Image
from miner_lib.victim import VictimModel
from miner_lib.scoring import quick_score

dev = "cuda:0"; BAD = "/root/badrows"
v = VictimModel(device=dev); torch.backends.cudnn.benchmark = True


def lg(p):
    a = np.asarray(Image.open(p).convert("RGB"))
    return (torch.tensor(a.astype(np.float32)/255.).permute(2,0,1).to(dev)*255).round()/255.


x0 = lg(f"{BAD}/102948/clean.png")
ti = int(v.evaluate(x0.unsqueeze(0), 0)[2].argmax())
print("true idx:", ti, flush=True)

# what class do the winners' submissions land on?
for uid in ["64", "126", "140", "141"]:
    adv = lg(f"{BAD}/102948/uid{uid}.png")
    p, m, lgt = v.evaluate(adv.unsqueeze(0), ti)
    _, _, det_ok = None, None, None
    s, det = quick_score(x0, adv, lgt, ti)
    print(f"uid{uid}: pred={int(p)} (ti={ti}) score={s:.4f} reason={det.get('reason')} "
          f"m={det.get('margin')}", flush=True)

# forensic flood with full logging
eps = 1/255.
delta = torch.zeros_like(x0); gmom = torch.zeros_like(x0)
pos_cont = 0
for st in range(200):
    d = delta.detach().requires_grad_(True)
    row = v((x0+d).unsqueeze(0))[0]
    with torch.no_grad():
        mm = row.detach().clone(); mm[ti] = -1e12
        ctg = int(mm.argmax())
        m_now = float(mm.max().item() - row[ti].item())
    g = torch.autograd.grad(row[ctg]-row[ti], d)[0]
    with torch.no_grad():
        gmom = 0.9*gmom+g
        delta = (delta + eps*0.4*torch.sign(gmom)).clamp(-eps, eps)
    if m_now > 0: pos_cont += 1
    if st % 10 == 9:
        xi = ((x0+delta).clamp(0,1)*255).round().long()
        xf = xi.float()/255.
        p, m, lgt = v.evaluate(xf.unsqueeze(0), ti)
        flipped = int(p) != ti
        line = f"st={st} cont_m={m_now:+.2f} ctg={ctg} snap_flip={flipped}"
        if flipped:
            s, det = quick_score(x0, xf, lgt, ti)
            line += f" s={s:.4f} reason={det.get('reason')} m={det.get('margin')}"
            if det.get("reason") == "success":
                break
        print(line, flush=True)
print("continuous-positive steps:", pos_cont, "/200", flush=True)