"""Head-to-head: batched multi-restart attack vs UID126 on the leaderboard rows.""" from __future__ import annotations import sys, time, json, base64, io, os 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, statistics 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 bmargins(logits,tg,ti): return logits.gather(1,tg.view(-1,1)).squeeze(1)-logits[:,ti] def attack(victim,x0f,x0,ti,B,budget): eps=1.0/255.0; dev=x0f.device; N=int(x0f.numel()); t0=time.time(); C,H,W=x0f.shape _,_,cl=victim.evaluate(x0f,ti); m0=cl.clone(); m0[ti]=-1e12 rivals=[int(i) for i in torch.topk(m0,10).indices.tolist()] # adaptive target d=torch.zeros_like(x0f); gm=torch.zeros_like(x0f); at=rivals[0] for _ in range(30): dd=d.detach().requires_grad_(True); row_=victim((x0f+dd).unsqueeze(0))[0] mm=row_.detach().clone(); mm[ti]=-1e12; at=int(mm.argmax().item()) gg=torch.autograd.grad(row_[at]-row_[ti],dd)[0] with torch.no_grad(): gm=0.9*gm+gg; d=(d+eps*0.25*torch.sign(gm)).clamp(-eps,eps) tg=torch.tensor([rivals[b%len(rivals)] for b in range(B)],device=dev); tg[-2:]=at delta=torch.zeros((B,C,H,W),device=dev) for b in range(B//2,B): m=(torch.rand(C,H,W,device=dev)<0.03).float(); delta[b]=eps*torch.sign(torch.randn(C,H,W,device=dev))*m mask=torch.ones((B,C,H,W),dtype=torch.bool,device=dev); gmom=torch.zeros((B,C,H,W),device=dev) noise=1.0+0.5*torch.rand((B,1,1,1),device=dev)*torch.randn((B,C,H,W),device=dev).abs() # per-restart DIVERSITY: shrink rate (fast=easy tasks, slow=hard tasks) + floor shrink_rates=torch.linspace(0.89,0.985,B,device=dev) kf=(torch.linspace(0.004,0.10,B,device=dev)*N).clamp(min=8) kb=torch.full((B,),float(N),device=dev) best={"score":-1.0,"xi":None,"margin":0.0,"rmse":1.0,"dens":1.0} k=N; k_floor=max(8,int(0.004*N)); step=0 while time.time()-t0=12: kb=torch.maximum(kf,kb*shrink_rates) imp=(delta.abs()*g.abs()*mask.float()*noise).flatten(1) kmax=int(kb.max().item()) vals=torch.topk(imp,kmax,dim=1).values ranks=(kb.long()-1).clamp(0,kmax-1) kth=vals.gather(1,ranks.view(-1,1)) mask=(imp>=kth).view_as(delta)&mask; delta=delta*mask if (float(kb.min())<0.25*N) or step%3==0 or time.time()-t0>=budget-0.5: xi=((x0f.unsqueeze(0)+delta).clamp(0,1)*255).round().long() gl=victim(xi.float()/255.0); mg=bmargins(gl,tg,ti); pred=gl.argmax(1) diff=xi.float()/255.0-x0f.unsqueeze(0); rmse=torch.sqrt((diff**2).flatten(1).mean(1)) rsc=(1-(rmse/0.03).clamp(max=1))**2; msc=(mg.clamp(0,10))/10.0 chpx=((xi!=x0.unsqueeze(0)).any(1)).flatten(1).sum(1); nov=(chpx.float()/8.).clamp(max=1.) sc=0.653+0.3*rsc+0.03*msc+0.01*nov; sc=torch.where(pred!=ti,sc,torch.full_like(sc,-1.)) bi=int(sc.argmax().item()) if float(sc[bi])>best["score"]: best={"score":float(sc[bi]),"xi":xi[bi].clone(),"margin":float(mg[bi]),"rmse":float(rmse[bi]),"dens":float((xi[bi]!=x0).float().mean())} step+=1 # exact-verify the best via quick_score if best["xi"] is not None: xf=best["xi"].float()/255.0; _,_,lg=victim.evaluate(xf,ti) sc,det=quick_score(x0f,xf,lg,ti) if det.get("reason")=="success": best["score"]=float(sc) return best def main(): jpath=sys.argv[1] if len(sys.argv)>1 else "/root/lb_snapshot.jsonl" budget=float(sys.argv[2]) if len(sys.argv)>2 else 30.0 B=int(os.environ.get("B","14")) recs=[json.loads(l) for l in open(jpath) if l.strip()] ds=load_imagenet100(split="train"); victim=VictimModel(device="cuda") print(f"B={B} budget={budget}",flush=True) print(f"{'row':<9}{'our':<9}{'u126':<9}{'delta':<9}{'our_m':<7}{'our_dens':<9}{'u126_dens'}",flush=True) ours=[]; 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("cuda") x0=(x.clamp(0,1)*255).round().long(); x0f=x0.float()/255 _,_,cl=victim.evaluate(x0f,0); ti=int(cl.argmax().item()) b=attack(victim,x0f,x0,ti,B,budget) sc=b["score"] if b["xi"] is not None else 0.0 ours.append(sc); us.append(u["score"]) print(f"{row:<9}{sc:<9.4f}{u['score']:<9.4f}{sc-u['score']:<+9.4f}{b['margin']:<7.2f}{b['dens']*100:<9.1f}{u['dens']*100:.1f}%",flush=True) print(f"\nMULTI mean={statistics.mean(ours):.4f} UID126={statistics.mean(us):.4f} delta={statistics.mean(ours)-statistics.mean(us):+.4f}") print(f"beats UID126 on {sum(1 for a,b in zip(ours,us) if a>b)}/{len(ours)} | single-cp was 0.9571(-0.0077)") if __name__=="__main__": main()