reneeice's picture
full research archive: code, models, datasets, experiments, logs
152228b verified
Raw History Blame Contribute Delete
3.26 kB
"""Dual-target converge-prune: screen-target (sparse-good on easy) + adaptive-argmax-climb target
(high-margin on hard). Run cp on both, best-by-score. Tests fixing the hard-task target failures."""
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.config import AttackConfig
from miner_lib.converge_prune_attack import run_converge_prune_attack, _screen_best_target, _mgrad
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 adaptive_target(victim,x0f,ti,steps=40):
eps=1.0/255.0; delta=torch.zeros_like(x0f); gmom=torch.zeros_like(x0f); tg=None
for it in range(steps):
d=delta.detach().requires_grad_(True); row=victim((x0f+d).unsqueeze(0))[0]
with torch.no_grad():
mm=row.detach().clone(); mm[ti]=-1e12; tg=int(mm.argmax().item())
g=torch.autograd.grad(row[tg]-row[ti], d)[0]
with torch.no_grad():
gmom=0.9*gmom+g; delta=(delta+eps*0.25*torch.sign(gmom)).clamp(-eps,eps)
return tg
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")
import statistics
print(f"{'row':<9}{'dual':<9}{'u126':<9}{'delta':<9}{'d_m':<7}{'d_dens':<8}{'tS':<6}{'tA':<6}",flush=True)
ds_scores=[]; us=[]
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())
t_screen=_screen_best_target(victim,x0f,ti,10,8)
t_adapt=adaptive_target(victim,x0f,ti,40)
targets=[t_screen] if t_screen==t_adapt else [t_screen,t_adapt]
per=budget/len(targets)
best=None
for tg in targets:
cfg=AttackConfig(time_budget_seconds=per)
res=run_converge_prune_attack(victim,x,ti,cfg,deadline=time.time()+per,target=tg)
if res.flipped and (best is None or res.score>best.score): best=res
sc=best.score if best and best.flipped else 0.0
m=best.margin if best and best.flipped else 0.0
dn=best.density if best and best.flipped else 0.0
ds_scores.append(sc); us.append(u["score"])
print(f"{row:<9}{sc:<9.4f}{u['score']:<9.4f}{sc-u['score']:<+9.4f}{m:<7.2f}{dn*100:<8.1f}{t_screen:<6}{t_adapt:<6}",flush=True)
print(f"\nDUAL mean={statistics.mean(ds_scores):.4f} UID126={statistics.mean(us):.4f} delta={statistics.mean(ds_scores)-statistics.mean(us):+.4f}")
print(f"dual beats UID126 on {sum(1 for a,b in zip(ds_scores,us) if a>b)}/{len(ds_scores)} | cp=0.9569 base=0.9526")
if __name__=="__main__": main()