Download code/scripts/fp16_probe.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 1.4 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/fp16_probe.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/fp16_probe.py
-
curl -L -o fp16_probe.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/fp16_probe.py
1.4 kB
| import sys,time | |
| from pathlib import Path | |
| R=Path(__file__).resolve().parents[1]; sys.path.insert(0,str(R)) | |
| import torch, base64, io | |
| from miner_lib.victim import VictimModel | |
| from perturbnet.imagenet100_bootstrap import load_imagenet100 | |
| from perturbnet.image_io import decode_image_b64 | |
| v=VictimModel(device="cuda"); ds=load_imagenet100(split="train") | |
| img=ds[96196]["image"]; b=io.BytesIO(); img.convert("RGB").save(b,format="PNG") | |
| x=decode_image_b64(base64.b64encode(b.getvalue()).decode()).to("cuda") | |
| x0f=(x.clamp(0,1)*255).round().long().float()/255; eps=1/255. | |
| for B in [16,24,32,40,48]: | |
| try: | |
| torch.cuda.reset_peak_memory_stats() | |
| delta=torch.zeros((B,)+x0f.shape,device="cuda",requires_grad=True); t0=time.time() | |
| for _ in range(5): | |
| with torch.autocast('cuda',dtype=torch.float16): | |
| logits=v((x0f.unsqueeze(0)+delta).clamp(0,1)); loss=logits.float().sum() | |
| g=torch.autograd.grad(loss,delta)[0] | |
| delta=delta.detach()+eps*0.25*torch.sign(g); delta.requires_grad_(True) | |
| torch.cuda.synchronize(); dt=(time.time()-t0)/5; mem=torch.cuda.max_memory_allocated()/1e9 | |
| print(f"B={B:<4} {dt*1000:.0f}ms/iter mem={mem:.1f}GB per-restart={dt*1000/B:.1f}ms",flush=True) | |
| del delta,logits,g; torch.cuda.empty_cache() | |
| except RuntimeError as e: | |
| print(f"B={B}: OOM",flush=True); torch.cuda.empty_cache(); break | |