reneeice's picture
full research archive: code, models, datasets, experiments, logs
152228b verified
Raw History Blame Contribute Delete
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