"""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()=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()=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()