File size: 5,540 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
"""Forward greedy growth (clean grad handling): grow support by |g| until margin>=10.5,
then backward-eliminate holding margin>=9.5. gradient recomputed fresh each iteration."""
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,true_index,target):
    d=delta.detach().requires_grad_(True)
    row=victim((x0f+d).unsqueeze(0))[0]
    g=torch.autograd.grad(row[target]-row[true_index], d)[0]
    return g, row.detach()

def screen_best_target(victim,x0f,true_index,K=10,steps=8):
    _,_,cl=victim.evaluate(x0f,true_index); m0=cl.clone(); m0[true_index]=-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,true_index,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()
            _,m,_=victim.evaluate(xi.float()/255,true_index); bm=max(bm,float(m))
        if bm>best[0]: best=(bm,t)
    return best[1]

def evalx(victim,x0f,x0,delta,true_index):
    xi=((x0f+delta).clamp(0,1)*255).round().long(); xf=xi.float()/255
    pred,margin,logits=victim.evaluate(xf,true_index)
    return xi,xf,pred,float(margin),logits

def fwd_greedy(victim,x0f,x0,true_index,target,deadline,climb_target=10.5,batch_frac=0.003,resign=3):
    eps=1.0/255.0; N=int(x0.numel())
    delta=torch.zeros_like(x0f); active=torch.zeros_like(x0f,dtype=torch.bool)
    best=(-1.0,-1e9,1.0,1.0)
    def maybe_best(delta):
        xi,xf,pred,margin,logits=evalx(victim,x0f,x0,delta,true_index)
        nonlocal best
        if pred!=true_index:
            score,det=quick_score(x0f,xf,logits,true_index)
            if det.get("reason")=="success" and score>best[0]:
                best=(float(score),margin,float(det.get("rmse",0)),float((xi!=x0).float().mean().item()))
        return margin
    # GROW
    while time.time()<deadline:
        g,_=mgrad(victim,x0f,delta,true_index,target)
        margin=maybe_best(delta)
        if margin>=climb_target: break
        with torch.no_grad():
            b=max(1,int(batch_frac*N))
            gi=g.abs().flatten().clone(); gi[active.flatten()]=-1e30
            add=torch.topk(gi,b).indices
            fa=active.flatten(); fd=delta.flatten(); gf=g.flatten()
            fa[add]=True; fd[add]=eps*torch.sign(gf[add])
            active=fa.view_as(active); delta=fd.view_as(delta)
        # re-sign active pixels (grad fresh each step, outside no_grad for grad)
        for _ in range(resign):
            g2,_=mgrad(victim,x0f,delta,true_index,target)
            with torch.no_grad():
                delta=(eps*torch.sign(g2))*active.float()
    # BACKWARD ELIM
    while time.time()<deadline:
        g,_=mgrad(victim,x0f,delta,true_index,target)
        with torch.no_grad():
            contrib=(delta*g).flatten(); act=active.flatten().nonzero().flatten()
            if act.numel()<10: break
            ca=contrib[act]; b=max(1,int(0.05*act.numel()))
            drop=act[torch.argsort(ca)[:b]]
            fa=active.flatten().clone(); fd=delta.flatten().clone(); fa[drop]=False; fd[drop]=0
            nactive=fa.view_as(active); ndelta=fd.view_as(delta)
        for _ in range(resign):
            g2,_=mgrad(victim,x0f,ndelta,true_index,target)
            with torch.no_grad(): ndelta=(eps*torch.sign(g2))*nactive.float()
        xi,xf,pred,margin,logits=evalx(victim,x0f,x0,ndelta,true_index)
        if margin>=9.5 and pred!=true_index:
            active=nactive; delta=ndelta; maybe_best(delta)
        else: break
    return best

def main():
    budget=float(sys.argv[1]) if len(sys.argv)>1 else 30.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}{'fwd':<9}{'u126':<9}{'delta':<9}{'fwd_m':<7}{'fwd_dens':<9}{'u126_dens'}")
    fs=[]; 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())
        t0=time.time(); tgt=screen_best_target(victim,x0f,ti)
        b=fwd_greedy(victim,x0f,x0,ti,tgt,deadline=t0+budget)
        fs.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"\nFWD mean={statistics.mean(fs):.4f} UID126={statistics.mean(us):.4f} delta={statistics.mean(fs)-statistics.mean(us):+.4f}")
    print(f"fwd beats UID126 on {sum(1 for a,b in zip(fs,us) if a>b)}/{len(fs)} | current=0.9526 v2=0.9541")
if __name__=="__main__": main()