Download code/scripts/density_probe.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 3.96 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/density_probe.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/density_probe.py
-
curl -L -o density_probe.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/density_probe.py
3.96 kB
| """For a fixed (row, target), find the config reaching margin>=thresh at MIN density. | |
| Compare to UID126's operating point (row 92064 tgt 287: margin 10 @ 8% 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 sparse_pgd(victim,x0f,x0,true_index,target,steps,warmup,shrink,k_min_frac,alpha_frac=0.25,mom=0.9,deadline=None): | |
| eps=1.0/255.0; N=int(x0.numel()) | |
| delta=torch.zeros_like(x0f); mask=torch.ones_like(x0f,dtype=torch.bool); gmom=torch.zeros_like(x0f); k=N | |
| best=(-1.0,-1e9,1.0,1.0) # score,margin,rmse,dens | |
| # also track: min density seen with margin>=9.5 | |
| best_lowdens=(1.0,-1e9) # dens, margin among margin>=9.5 | |
| for it in range(steps): | |
| if deadline and it%8==0 and time.time()>deadline: break | |
| 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+eps*alpha_frac*torch.sign(gmom)).clamp(-eps,eps)*mask | |
| if it>=warmup: | |
| k=max(int(k_min_frac*N), int(k*shrink)) | |
| if int(mask.sum().item())>k: | |
| imp=(delta.abs()*g.abs()*mask.float()).flatten() | |
| kth=torch.topk(imp,k).values[-1] | |
| mask=(imp>=kth).view_as(delta)&mask | |
| delta=delta*mask | |
| xi=((x0f+delta).clamp(0,1)*255).round().long(); xf=xi.float()/255 | |
| pred,margin,logits=victim.evaluate(xf,true_index) | |
| if pred!=true_index: | |
| score,det=quick_score(x0f,xf,logits,true_index) | |
| if det.get("reason")=="success": | |
| dens=float((xi!=x0).float().mean().item()) | |
| if score>best[0]: best=(float(score),float(margin),float(det.get("rmse",0)),dens) | |
| if margin>=9.5 and dens<best_lowdens[0]: best_lowdens=(dens,float(margin)) | |
| return best,best_lowdens | |
| 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 | |
| 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 | |
| _,_,cl=victim.evaluate(x0f,0); true_index=int(cl.argmax().item()) | |
| print(f"row={row_idx} target={target} true_index={true_index}") | |
| configs=[ | |
| ("cur90/.94/2%", dict(steps=90,warmup=15,shrink=0.94,k_min_frac=0.02)), | |
| ("slow200/.97/4%", dict(steps=200,warmup=20,shrink=0.97,k_min_frac=0.04)), | |
| ("slow300/.985/5%",dict(steps=300,warmup=25,shrink=0.985,k_min_frac=0.05)), | |
| ("vslow400/.99/6%",dict(steps=400,warmup=30,shrink=0.99,k_min_frac=0.06)), | |
| ("a0.1_300/.985/5%",dict(steps=300,warmup=25,shrink=0.985,k_min_frac=0.05,alpha_frac=0.1)), | |
| ] | |
| print(f"{'config':<20}{'best_score':<12}{'margin':<9}{'rmse':<10}{'dens%':<8}{'min_dens@m9.5':<14}") | |
| for name,cfg in configs: | |
| b,bl=sparse_pgd(victim,x0f,x0,true_index,target,deadline=time.time()+28,**cfg) | |
| ld = f"{bl[0]*100:.1f}%(m{bl[1]:.1f})" if bl[0]<1.0 else "none" | |
| print(f"{name:<20}{b[0]:<12.4f}{b[1]:<9.2f}{b[2]:<10.6f}{b[3]*100:<8.1f}{ld:<14}") | |
| print("UID126 ref: margin 9.98 @ 8.0% density, rmse 0.001107, score 0.9712") | |
| if __name__=="__main__": | |
| main() | |