Download code/scripts/hard_diag.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 2.39 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/hard_diag.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/hard_diag.py
-
curl -L -o hard_diag.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/hard_diag.py
2.39 kB
| """Diagnose hard-task margin-climb: for top-15 targets, max margin reachable at FULL support, | |
| and whether a sparse margin-10 exists. Reveals if failures are target-selection or genuine.""" | |
| 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 mgrad(victim,x0f,delta,ti,tg): | |
| d=delta.detach().requires_grad_(True); row=victim((x0f+d).unsqueeze(0))[0] | |
| g=torch.autograd.grad(row[tg]-row[ti], d)[0]; return g | |
| def climb_full(victim,x0f,ti,tg,steps=60,alpha_frac=0.25): | |
| eps=1.0/255.0; delta=torch.zeros_like(x0f); gmom=torch.zeros_like(x0f); bm=-1e9 | |
| for it in range(steps): | |
| g=mgrad(victim,x0f,delta,ti,tg) | |
| with torch.no_grad(): | |
| gmom=0.9*gmom+g; delta=(delta+eps*alpha_frac*torch.sign(gmom)).clamp(-eps,eps) | |
| xi=((x0f+delta).clamp(0,1)*255).round().long() | |
| _,m,_=victim.evaluate(xi.float()/255,ti); bm=max(bm,float(m)) | |
| return bm | |
| def main(): | |
| for row_idx in [int(a) for a in sys.argv[1:]] or [34209,45539]: | |
| 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); ti=int(cl.argmax().item()) | |
| m0=cl.clone(); m0[ti]=-1e12 | |
| rivals=[int(i) for i in torch.topk(m0,15).indices.tolist()] | |
| print(f"\nrow={row_idx} true={ti} img={tuple(x0f.shape)}") | |
| best=(-1e9,None) | |
| for t in rivals: | |
| bm=climb_full(victim,x0f,ti,t,steps=60) | |
| if bm>best[0]: best=(bm,t) | |
| print(f" best full-support margin over top15 targets: {best[0]:.2f} (target {best[1]})") | |
| # deeper climb on best target | |
| bm2=climb_full(victim,x0f,ti,best[1],steps=150,alpha_frac=0.15) | |
| print(f" deeper climb (150 steps) on target {best[1]}: margin {bm2:.2f}") | |
| if __name__=="__main__": main() | |