File size: 6,370 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
"""converge-then-prune: phase-1 sparse-PGD shrink to a sparse support at margin>=climb, then
phase-2 repeatedly (fully converge signs -> prune lowest converged-contribution, hold margin>=10)."""
from __future__ import annotations
import sys, time, json, base64, io
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.scoring import quick_score
from perturbnet.imagenet100_bootstrap import load_imagenet100
from perturbnet.image_io import decode_image_b64
def pil_b64(img):
    b=io.BytesIO(); img.convert("RGB").save(b, format="PNG"); return base64.b64encode(b.getvalue()).decode()
def mgrad(victim,x0f,delta,ti,tg):
    d=delta.detach().requires_grad_(True); row=victim((x0f+d).unsqueeze(0))[0]
    g=torch.autograd.grad(row[tg]-row[ti], d)[0]; return g,row.detach()
def screen_best_target(victim,x0f,ti,K=10,steps=8):
    _,_,cl=victim.evaluate(x0f,ti); m0=cl.clone(); m0[ti]=-1e12
    rivals=[int(i) for i in torch.topk(m0,K).indices.tolist()]; eps=1.0/255.0; best=(-1e9,rivals[0])
    for t in rivals:
        delta=torch.zeros_like(x0f); gmom=torch.zeros_like(x0f); bm=-1e9
        for it in range(steps):
            g,_=mgrad(victim,x0f,delta,ti,t)
            with torch.no_grad():
                gmom=0.9*gmom+g; delta=(delta+eps*0.4*torch.sign(gmom)).clamp(-eps,eps)
                xi=((x0f+delta).clamp(0,1)*255).round().long()
            _,mm,_=victim.evaluate(xi.float()/255,ti); bm=max(bm,float(mm))
        if bm>best[0]: best=(bm,t)
    return best[1]
def sign_converge(victim,x0f,delta,maskf,ti,tg,steps):
    eps=1.0/255.0; gmom=torch.zeros_like(x0f)
    for it in range(steps):
        g,_=mgrad(victim,x0f,delta,ti,tg)
        with torch.no_grad():
            gmom=0.9*gmom+g; delta=(delta+eps*0.25*torch.sign(gmom)).clamp(-eps,eps)*maskf
    g,_=mgrad(victim,x0f,delta,ti,tg)
    return delta,g
def attack(victim,x0f,x0,ti,tg,budget,climb_target=11.0,p1_frac=0.62):
    eps=1.0/255.0; N=int(x0.numel()); t0=time.time(); p1_dl=t0+p1_frac*budget; dl=t0+budget
    delta=torch.zeros_like(x0f); mask=torch.ones_like(x0f,dtype=torch.bool); gmom=torch.zeros_like(x0f); k=N
    best=(-1.0,-1e9,1.0,1.0)
    def maybe(delta,mask):
        nonlocal best
        xi=((x0f+delta).clamp(0,1)*255).round().long(); xf=xi.float()/255
        pred,margin,logits=victim.evaluate(xf,ti)
        if pred!=ti:
            score,det=quick_score(x0f,xf,logits,ti)
            if det.get("reason")=="success" and score>best[0]:
                best=(float(score),float(margin),float(det.get("rmse",0)),float((xi!=x0).float().mean().item()))
        return float(margin)
    # phase-0: climb at FULL support until margin>=climb_target (bank margin for hard tasks)
    p0_dl=t0+0.28*budget
    for it in range(120):
        if time.time()>p0_dl: break
        g,_=mgrad(victim,x0f,delta,ti,tg)
        with torch.no_grad():
            gmom=0.9*gmom+g; delta=(delta+eps*0.25*torch.sign(gmom)).clamp(-eps,eps)
            mm=maybe(delta,mask)
            if mm>=climb_target: break
    # phase-1: shrink with best-by-score tracking (captures m10 at whatever density hard tasks need)
    k=N; k_floor=max(8,int(0.02*N))
    for it in range(300):
        if time.time()>p1_dl: break
        g,_=mgrad(victim,x0f,delta,ti,tg)
        with torch.no_grad():
            gmom=0.9*gmom+g; delta=(delta+eps*0.25*torch.sign(gmom)).clamp(-eps,eps)*mask
            k=max(k_floor,int(k*0.95))
            if int(mask.sum().item())>k:
                imp=(delta.abs()*g.abs()*mask.float()).flatten()
                kth=torch.topk(imp,k).values[-1]; mask=(imp>=kth).view_as(delta)&mask; delta=delta*mask
            m=maybe(delta,mask)
            if int(mask.sum().item())<=k_floor: break
    # phase-2: converge-then-prune
    while time.time()<dl:
        delta,g=sign_converge(victim,x0f,delta,mask.float(),ti,tg,steps=20)
        m=maybe(delta,mask)
        act=mask.flatten().nonzero().flatten()
        if m<10.3 or act.numel()<max(8,int(0.002*N)): break
        with torch.no_grad():
            contrib=(delta*g).flatten(); ca=contrib[act]; b=max(1,int(0.06*act.numel()))
            drop=act[torch.argsort(ca)[:b]]
            newmask=mask.clone().flatten(); newmask[drop]=False; newmask=newmask.view_as(mask)
        nd=delta*newmask.float(); nd,_=sign_converge(victim,x0f,nd,newmask.float(),ti,tg,18)
        xi=((x0f+nd).clamp(0,1)*255).round().long(); _,nm,_=victim.evaluate(xi.float()/255,ti)
        if nm>=10.0: mask=newmask; delta=nd; maybe(delta,mask)
        else:
            with torch.no_grad():
                b2=max(1,b//3); drop2=act[torch.argsort(ca)[:b2]]
                nm2=mask.clone().flatten(); nm2[drop2]=False; nm2=nm2.view_as(mask)
            nd2=delta*nm2.float(); nd2,_=sign_converge(victim,x0f,nd2,nm2.float(),ti,tg,18)
            xi2=((x0f+nd2).clamp(0,1)*255).round().long(); _,nm2m,_=victim.evaluate(xi2.float()/255,ti)
            if nm2m>=10.0: mask=nm2; delta=nd2; maybe(delta,mask)
            else: break
    return best
def main():
    budget=float(sys.argv[1]) if len(sys.argv)>1 else 32.0
    recs=[json.loads(l) for l in open("/root/lb_snapshot.jsonl") if l.strip()]
    ds=load_imagenet100(split="train")
    victim=VictimModel(device="cuda" if torch.cuda.is_available() else "cpu")
    import statistics
    print(f"{'row':<9}{'cp':<9}{'u126':<9}{'delta':<9}{'cp_m':<7}{'cp_dens':<9}{'u126_dens'}")
    cs=[]; us=[]
    for r in recs:
        row=r["row"]; u=r.get("uid126")
        if not u or row>=ds.num_rows: continue
        x=decode_image_b64(pil_b64(ds[row]["image"])).to(victim.device)
        x0=(x.clamp(0,1)*255).round().long(); x0f=x0.float()/255
        _,_,cl=victim.evaluate(x0f,0); ti=int(cl.argmax().item())
        tg=screen_best_target(victim,x0f,ti)
        b=attack(victim,x0f,x0,ti,tg,budget)
        cs.append(b[0]); us.append(u["score"])
        print(f"{row:<9}{b[0]:<9.4f}{u['score']:<9.4f}{b[0]-u['score']:<+9.4f}{b[1]:<7.2f}{b[3]*100:<9.1f}{u['dens']*100:.1f}%")
    print(f"\nCP mean={statistics.mean(cs):.4f} UID126={statistics.mean(us):.4f} delta={statistics.mean(cs)-statistics.mean(us):+.4f}")
    print(f"CP beats UID126 on {sum(1 for a,b in zip(cs,us) if a>b)}/{len(cs)} | current=0.9526 v2=0.9541")
if __name__=="__main__": main()