"""Hybrid: batched multi-restart finds the best support BASIN (diversity), then single-restart converge-then-prune deeply SPARSIFIES that basin. Diversity + depth. vs UID126.""" 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 miner_lib.converge_prune_attack import _sign_converge, _mgrad 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 batched_phase(victim,x0f,x0,ti,B,budget,rivals,at): eps=1.0/255.0; dev=x0f.device; N=int(x0f.numel()); t0=time.time(); C,H,W=x0f.shape 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() 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,"delta":None,"mask":None,"tg":int(tg[0]),"margin":0.,"rmse":1.,"dens":1.} 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.3: 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(),"delta":delta[bi].clone(), "mask":mask[bi].clone(),"tg":int(tg[bi]),"margin":float(mg[bi]), "rmse":float(rmse[bi]),"dens":float((xi[bi]!=x0).float().mean())} step+=1 return best def attack(victim,x0f,x0,ti,B,budget): eps=1.0/255.0; t0=time.time() _,_,cl=victim.evaluate(x0f,ti); m0=cl.clone(); m0[ti]=-1e12 rivals=[int(i) for i in torch.topk(m0,10).indices.tolist()] 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) # batched basin search (55% budget) b=batched_phase(victim,x0f,x0,ti,B,0.55*budget,rivals,at) best={"score":b["score"],"xi":b["xi"],"margin":b["margin"],"rmse":b["rmse"],"dens":b["dens"]} if b["delta"] is None: return best # deep converge-then-prune refinement on the best basin (rest of budget) delta=b["delta"]; mask=b["mask"]; tg=b["tg"]; N=int(x0f.numel()) def maybe(delta): xi=((x0f+delta).clamp(0,1)*255).round().long(); xf=xi.float()/255 pred,margin,logits=victim.evaluate(xf,ti) if pred!=ti: sc,det=quick_score(x0f,xf,logits,ti) if det.get("reason")=="success" and sc>best["score"]: best.update(score=float(sc),xi=xi.clone(),margin=float(margin),rmse=float(det.get("rmse",0)),dens=float((xi!=x0).float().mean())) return float(margin) while time.time()-t0=9.0: mask=nm; delta=nd; maybe(delta) else: break 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 32.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}{'dens':<8}{'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:<8.1f}{u['dens']*100:.1f}%",flush=True) print(f"\nHYBRID 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 0.9571 multi 0.9580") if __name__=="__main__": main()