reneeice's picture
full research archive: code, models, datasets, experiments, logs (part 2)
d656622 verified
Raw History Blame Contribute Delete
4.09 kB
"""Continuous L1/elastic-net support proposal: optimize delta in [-eps,eps] via Adam with an L1
penalty (homotopy), then round->support->sign-converge. Compare density@margin10 to cp & UID126."""
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 miner_lib.converge_prune_attack import _screen_best_target, _mgrad, _sign_converge
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 l1_attack(victim,x0f,x0,ti,tg,deadline,margin_target=10.5):
"""Adam on w with delta=eps*tanh(w); loss = relu(mt - margin) + lam*|delta|_1/eps. Homotopy on lam."""
eps=1.0/255.0; N=int(x0.numel())
w=torch.zeros_like(x0f, requires_grad=True)
opt=torch.optim.Adam([w], lr=0.05)
best=(-1.0,-1e9,1.0,1.0)
def snap():
with torch.no_grad():
delta=eps*torch.tanh(w)
xi=((x0f+delta).clamp(0,1)*255).round().long(); xf=xi.float()/255
pred,margin,logits=victim.evaluate(xf,ti)
nonlocal best
if pred!=ti:
score,det=quick_score(x0f,xf,logits,ti)
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()))
lam=0.0
for it in range(400):
if time.time()>deadline: break
# homotopy: ramp L1 after reaching margin
delta=eps*torch.tanh(w)
row=victim((x0f+delta).unsqueeze(0))[0]
margin=row[tg]-row[ti]
l1=(delta.abs().sum())/eps/N
loss=torch.relu(margin_target-margin)+lam*l1
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
cm=float(margin.item())
# once margin reached, increase L1 to sparsify; else keep low
if cm>=margin_target: lam=min(lam+0.02, 3.0)
elif cm<margin_target-1.0: lam=max(lam-0.03, 0.0)
if it%3==0: snap()
# extract support from the continuous solution, sign-converge on it
with torch.no_grad():
delta=eps*torch.tanh(w)
# keep pixels that round to nonzero on the grid
xi=((x0f+delta).clamp(0,1)*255).round().long()
mask=(xi!=x0)
if int(mask.sum().item())>0 and time.time()<deadline:
d0=eps*torch.sign(torch.tanh(w).detach())*mask.float()
d0,_=_sign_converge(victim,x0f,d0,mask.float(),ti,tg,30)
with torch.no_grad():
xi=((x0f+d0).clamp(0,1)*255).round().long(); xf=xi.float()/255
pred,margin,logits=victim.evaluate(xf,ti)
if pred!=ti:
score,det=quick_score(x0f,xf,logits,ti)
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()))
return best
def main():
rows=[int(a) for a in sys.argv[1:]] or [106323,57196,52826,57028,65975]
ds=load_imagenet100(split="train")
victim=VictimModel(device="cuda" if torch.cuda.is_available() else "cpu")
print(f"{'row':<9}{'l1_score':<10}{'l1_m':<7}{'l1_dens':<9}")
for row in rows:
if 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())
tg=_screen_best_target(victim,x0f,ti,10,8)
b=l1_attack(victim,x0f,x0,ti,tg,deadline=time.time()+22)
print(f"{row:<9}{b[0]:<10.4f}{b[1]:<7.2f}{b[3]*100:<9.1f}",flush=True)
print("ref cp/UID126 dens@m10: 106323 18.4/9.9 57196 12/4.3 52826 5.4/2.4 57028 17.5/13.1 65975 20.4/17.1")
if __name__=="__main__": main()