Download code/scripts/climb_attack.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 5.37 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/climb_attack.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/climb_attack.py
-
curl -L -o climb_attack.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/climb_attack.py
5.37 kB
| """v2 attack: screen targets -> climb margin to ~10.5 at full support -> sparsify holding margin. | |
| A/B against UID126 actuals on the poller rows.""" | |
| from __future__ import annotations | |
| import sys, time, json, 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 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 screen_target(victim,x0f,true_index,target,steps=8,alpha_frac=0.4,mom=0.9): | |
| eps=1.0/255.0; alpha=eps*alpha_frac; delta=torch.zeros_like(x0f); gmom=torch.zeros_like(x0f); best_m=-1e9 | |
| for it in range(steps): | |
| 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+alpha*torch.sign(gmom)).clamp(-eps,eps) | |
| xi=((x0f+delta).clamp(0,1)*255).round().long() | |
| _,m,_=victim.evaluate(xi.float()/255,true_index); best_m=max(best_m,m) | |
| return best_m | |
| def climb_sparsify(victim,x0f,x0,true_index,target,deadline,climb_target=10.5,climb_max=60, | |
| shrink=0.965,k_min_frac=0.005,alpha_frac=0.25,mom=0.9,total=300): | |
| 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); climbing=True; climbed=0 | |
| for it in range(total): | |
| if 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 | |
| # phase control | |
| mm=row.detach().clone(); mm[true_index]=-1e12 | |
| cont_pred=int(mm.argmax().item()); cont_flip = row[cont_pred] > row[true_index] | |
| if not climbing: | |
| 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 | |
| # snapshot when continuously flipped (cheap gate) or during shrink | |
| if cont_flip or not climbing: | |
| 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" and score>best[0]: | |
| best=(float(score),float(margin),float(det.get("rmse",0)),float((xi!=x0).float().mean().item())) | |
| if climbing: | |
| climbed+=1 | |
| if margin>=climb_target or climbed>=climb_max: climbing=False | |
| elif climbing: | |
| climbed+=1 | |
| if climbed>=climb_max: climbing=False | |
| return best | |
| def attack(victim,x0f,x0,true_index,budget): | |
| t0=time.time() | |
| _,_,cl=victim.evaluate(x0f,true_index); m0=cl.clone(); m0[true_index]=-1e12 | |
| rivals=[int(i) for i in torch.topk(m0,12).indices.tolist()] | |
| sd=t0+0.28*budget; scored=[] | |
| for t in rivals: | |
| if time.time()>sd: break | |
| scored.append((screen_target(victim,x0f,true_index,t),t)) | |
| scored.sort(key=lambda z:-z[0]); commit=[t for _,t in scored[:2]] | |
| best=(-1.0,-1e9,1.0,1.0,-1) | |
| rem=budget-(time.time()-t0); per=rem/max(1,len(commit)) | |
| for t in commit: | |
| r=climb_sparsify(victim,x0f,x0,true_index,t,deadline=time.time()+per) | |
| if r[0]>best[0]: best=(*r,t) | |
| return best | |
| def main(): | |
| budget=float(sys.argv[1]) if len(sys.argv)>1 else 32.0 | |
| recs=[json.loads(l) for l in open("/root/lb_snapshot.jsonl") if l.strip()] | |
| ds=load_imagenet100(split="train") | |
| victim=VictimModel(device="cuda" if torch.cuda.is_available() else "cpu") | |
| print(f"n={len(recs)} budget={budget}s") | |
| print(f"{'row':<9}{'v2':<9}{'u126':<9}{'delta':<9}{'v2_m':<7}{'v2_dens':<8}{'tgt'}") | |
| import statistics | |
| v2s=[]; u126=[] | |
| 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(victim.device) | |
| 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,budget) | |
| v2s.append(b[0]); u126.append(u["score"]) | |
| print(f"{row:<9}{b[0]:<9.4f}{u['score']:<9.4f}{b[0]-u['score']:<+9.4f}{b[1]:<7.2f}{b[3]*100:<8.1f}{b[4]}") | |
| print(f"\nV2 mean={statistics.mean(v2s):.4f} UID126 mean={statistics.mean(u126):.4f} delta={statistics.mean(v2s)-statistics.mean(u126):+.4f}") | |
| print(f"v2 beats UID126 on {sum(1 for a,b in zip(v2s,u126) if a>b)}/{len(v2s)} | current pipeline was 0.9526 (-0.0122)") | |
| if __name__=="__main__": main() | |