Download code/scripts/batched_restart.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 5.27 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/batched_restart.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/batched_restart.py
-
curl -L -o batched_restart.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/batched_restart.py
5.27 kB
| """Massively-parallel multi-restart: B diverse restarts (random targets/init/prune-noise) explore | |
| different support basins in parallel (batched on GPU). Keep sparsest margin-10. Best-of-N escapes | |
| the single-basin plateau. Test density@margin10 vs single converge-prune & UID126.""" | |
| from __future__ import annotations | |
| import sys, time, 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 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 batched_margins(logits, tg, ti): | |
| return logits.gather(1, tg.view(-1,1)).squeeze(1) - logits[:, ti] | |
| def fast_score(x0f, xi, x0, margins_grid): | |
| # batched score approx (skip SSIM/PSNR which always pass at 1/255) | |
| diff = xi.float()/255.0 - x0f.unsqueeze(0) | |
| rmse = torch.sqrt((diff**2).flatten(1).mean(1)) | |
| rmse_score = (1 - (rmse/0.03).clamp(max=1))**2 | |
| mscore = (margins_grid.clamp(0,10))/10.0 | |
| changed_px = ((xi != x0.unsqueeze(0)).any(dim=1)).flatten(1).sum(1) # per-restart changed pixels | |
| nov = (changed_px.float()/8.0).clamp(max=1.0) | |
| return 0.653 + 0.3*rmse_score + 0.03*mscore + 0.01*nov, rmse | |
| def run(victim, x0f, x0, ti, B, budget, top_rivals, adapt_tg): | |
| eps=1.0/255.0; dev=x0f.device; N=int(x0f.numel()); t0=time.time() | |
| C,H,W = x0f.shape | |
| # assign diverse targets: round-robin over rivals + adaptive on a few | |
| tg=torch.tensor([top_rivals[b % len(top_rivals)] for b in range(B)], device=dev) | |
| tg[-2:]=adapt_tg | |
| # random init: half zero, half small random support | |
| 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) | |
| # per-restart importance noise scale (fixed per restart for consistent basin) | |
| noise=1.0+0.5*torch.rand((B,1,1,1),device=dev)*torch.randn((B,C,H,W),device=dev).abs() | |
| 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 < budget: | |
| d=delta.detach().requires_grad_(True) | |
| logits=victim((x0f.unsqueeze(0)+d).clamp(0,1)) | |
| margins=batched_margins(logits, tg, ti) | |
| g=torch.autograd.grad(margins.sum(), d)[0] | |
| with torch.no_grad(): | |
| gmom=0.9*gmom+g | |
| delta=(delta+eps*0.25*torch.sign(gmom)).clamp(-eps,eps)*mask | |
| # shrink after warmup | |
| if step>=12: | |
| k=max(k_floor,int(k*0.92)) | |
| imp=(delta.abs()*g.abs()*mask.float()*noise).flatten(1) # (B,N) | |
| kth=torch.topk(imp,k,dim=1).values[:,-1:] | |
| mask=(imp>=kth).view_as(delta) & mask | |
| delta=delta*mask | |
| # score on grid every 2 steps | |
| if (k < int(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=batched_margins(gl, tg, ti) | |
| pred=gl.argmax(1) | |
| sc,rmse=fast_score(x0f,xi,x0,mg) | |
| sc=torch.where(pred!=ti, sc, torch.full_like(sc,-1.0)) | |
| 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 | |
| return best, step | |
| def main(): | |
| rows=[int(a) for a in sys.argv[1:]] or [96196,18414,18726] | |
| B=int(__import__("os").environ.get("B","14")) | |
| ds=load_imagenet100(split="train") | |
| victim=VictimModel(device="cuda") | |
| print(f"B={B}") | |
| print(f"{'row':<9}{'score':<9}{'margin':<8}{'dens%':<8}{'rmse':<10}{'steps'}") | |
| for row in rows: | |
| if 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()) | |
| m0=cl.clone(); m0[ti]=-1e12 | |
| rivals=[int(i) for i in torch.topk(m0,10).indices.tolist()] | |
| # adaptive target via short climb | |
| 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+1/255.*0.25*torch.sign(gm)).clamp(-1/255.,1/255.) | |
| b,steps=run(victim,x0f,x0,ti,B,28.0,rivals,at) | |
| print(f"{row:<9}{b['score']:<9.4f}{b['margin']:<8.2f}{b['dens']*100:<8.1f}{b['rmse']:<10.6f}{steps}",flush=True) | |
| print("ref single-cp / UID126 dens: 96196 13.4/2.9 18414 19.4/5.2 18726 21.5/8.5") | |
| if __name__=="__main__": main() | |