File size: 5,081 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 | """GreedyFool-style: climb to high margin at full support, then backward-eliminate pixels
with re-optimization between removals, holding margin>=thresh. Target min density."""
from __future__ import annotations
import sys, time
from pathlib import Path
import base64, io
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 climb(victim,x0f,true_index,target,steps,alpha_frac=0.25,mom=0.9):
eps=1.0/255.0; alpha=eps*alpha_frac
delta=torch.zeros_like(x0f); gmom=torch.zeros_like(x0f)
for it in range(steps):
d=delta.detach().requires_grad_(True)
row=victim((x0f+d).unsqueeze(0))[0]
g=torch.autograd.grad(row[target]-row[true_index], d)[0]
with torch.no_grad():
gmom=mom*gmom+g
delta=(delta+alpha*torch.sign(gmom)).clamp(-eps,eps)
return delta
def refine(victim,x0f,delta,mask,true_index,target,steps,alpha_frac=0.25,mom=0.9):
eps=1.0/255.0; alpha=eps*alpha_frac; gmom=torch.zeros_like(x0f)
for it in range(steps):
d=delta.detach().requires_grad_(True)
row=victim((x0f+d).unsqueeze(0))[0]
g=torch.autograd.grad(row[target]-row[true_index], d)[0]
with torch.no_grad():
gmom=mom*gmom+g
delta=(delta+alpha*torch.sign(gmom)).clamp(-eps,eps)*mask
return delta,g
def evalm(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 pred,margin,logits,xi
def main():
row_idx=int(sys.argv[1]) if len(sys.argv)>1 else 92064
target=int(sys.argv[2]) if len(sys.argv)>2 else 287
thresh=9.5
ds=load_imagenet100(split="train")
victim=VictimModel(device="cuda" if torch.cuda.is_available() else "cpu")
x=decode_image_b64(pil_b64(ds[row_idx]["image"])).to(victim.device)
x0=(x.clamp(0,1)*255).round().long(); x0f=x0.float()/255; N=int(x0.numel())
_,_,cl=victim.evaluate(x0f,0); true_index=int(cl.argmax().item())
print(f"row={row_idx} target={target} true_index={true_index}")
t0=time.time()
# climb dense
delta=climb(victim,x0f,true_index,target,45)
# snap to grid support
mask=(delta.abs()>1e-9)
pred,margin,logits,xi=evalm(victim,x0f,x0,delta,true_index)
dens=float((xi!=x0).float().mean().item())
print(f"after climb: margin={margin:.2f} density={dens*100:.1f}%")
best=(-1.0,-1e9,1.0,1.0)
# backward elimination
it_round=0
while time.time()-t0<26:
it_round+=1
d=delta.detach().requires_grad_(True)
row=victim((x0f+d).unsqueeze(0))[0]
g=torch.autograd.grad(row[target]-row[true_index], d)[0]
contrib=(delta*g) # positive = helping margin
active=mask.flatten().nonzero().flatten()
n_active=active.numel()
if n_active<int(0.03*N): break
# remove the least-contributing batch (could be negative = hurting)
c_active=contrib.flatten()[active]
batch=max(1,int(0.06*n_active))
order=torch.argsort(c_active) # ascending: worst first
drop=active[order[:batch]]
newmask=mask.clone().flatten(); newmask[drop]=False; newmask=newmask.view_as(mask)
newdelta=delta*newmask
# refine survivors
newdelta,_=refine(victim,x0f,newdelta,newmask,true_index,target,4)
pred,margin,logits,xi=evalm(victim,x0f,x0,newdelta,true_index)
if margin>=thresh and pred!=true_index:
delta=newdelta; mask=newmask
score,det=quick_score(x0f,xi.float()/255,logits,true_index)
dens=float((xi!=x0).float().mean().item())
if det.get("reason")=="success" and score>best[0]:
best=(float(score),float(margin),float(det.get("rmse",0)),dens)
else:
# too aggressive: try smaller batch by restoring and reducing
batch=max(1,batch//2)
if batch<=1:
# try single-pixel removals of the worst; if fails, stop
newmask=mask.clone().flatten(); newmask[drop[:1]]=False; newmask=newmask.view_as(mask)
newdelta=delta*newmask
newdelta,_=refine(victim,x0f,newdelta,newmask,true_index,target,4)
pred,margin,logits,xi=evalm(victim,x0f,x0,newdelta,true_index)
if margin>=thresh and pred!=true_index:
delta=newdelta; mask=newmask
else:
break
print(f"final best: score={best[0]:.4f} margin={best[1]:.2f} rmse={best[2]:.6f} density={best[3]*100:.1f}% rounds={it_round}")
print("UID126 ref: margin 9.98 @ 8.0% density score 0.9712 | our sparse-PGD floor: ~10.5%")
if __name__=="__main__":
main()
|