"""L2 — amortized sparse-attack support generator (TSAA-style, arXiv:2105.14727). Reframing: we have WHITE-BOX access to the exact victim, so we do NOT need competitors' masks. We train a small conv generator G(image) -> per-subpixel inclusion score, end-to-end against the victim with a differentiable CW margin loss + an L0 (sum of soft-inclusion) penalty. The generator learns an amortized *support prior*: which pixels of an image are worth perturbing to flip EfficientNetV2-L cheaply. At attack time the generator proposes a support in one cheap forward; cp then refines signs and prunes from that seed. The hypothesis (the only path that could beat cp's density): a learned prior lands cp in a *different, tighter basin* than greedy-shrink-from-full-support, especially on hard images where cp floods. This trains in gated bursts so it never starves the live miner (checkpoints to /root/l2_gen.pt). It is a research prototype; wiring into the runner is gated behind a validated density win in cp_bench. """ from __future__ import annotations import argparse import sys import time 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 io, base64 import torch import torch.nn as nn import torch.nn.functional as F from miner_lib.victim import VictimModel from perturbnet.imagenet100_bootstrap import load_imagenet100 from perturbnet.image_io import decode_image_b64 class SupportGen(nn.Module): """Lightweight dilated FCN: image (3,H,W in [0,1]) -> raw perturbation field p (3,H,W). A single field encodes BOTH support and sign: soft delta = eps*tanh(p) (so |tanh(p)| is the soft inclusion and sign(p) is the sign). Fixing sign to the clean gradient was proven insufficient (fingerprint: clean-grad signs flip only ~55%), so the generator learns signs jointly with support end-to-end against the victim.""" def __init__(self, ch=48): super().__init__() self.net = nn.Sequential( nn.Conv2d(3, ch, 3, padding=1), nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, ch, 3, padding=1, dilation=1), nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, ch, 3, padding=2, dilation=2), nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, ch, 3, padding=4, dilation=4), nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, ch, 3, padding=8, dilation=8), nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, 3, 1), ) def forward(self, x): return self.net(x) def pil_to_tensor(img, device): b = io.BytesIO(); img.convert("RGB").save(b, format="PNG") return decode_image_b64(base64.b64encode(b.getvalue()).decode()).to(device) def wait_safe_window(work_s, gate, lo=38.0, hi=116.0, pad=6.0): if not gate: return while True: pos = time.time() % 120.0 if lo <= pos <= (hi - work_s - pad): return time.sleep(2.0) def cw_margin(row, ti): m = row.clone(); m[:, ti] = -1e12 return m.max(dim=1).values - row[:, ti] # want > 0 (flip) def main(): ap = argparse.ArgumentParser() ap.add_argument("--steps", type=int, default=400) ap.add_argument("--lr", type=float, default=1e-3) ap.add_argument("--l0-weight", type=float, default=0.02) ap.add_argument("--target-density", type=float, default=0.06) ap.add_argument("--burst", type=float, default=40.0, help="seconds of GPU work per gated burst") ap.add_argument("--no-gate", action="store_true") ap.add_argument("--ckpt", default="/root/l2_gen.pt") args = ap.parse_args() device = "cuda" if torch.cuda.is_available() else "cpu" victim = VictimModel(device=device) for p in victim.net.parameters(): p.requires_grad_(False) ds = load_imagenet100(split="train") N = ds.num_rows gen = SupportGen().to(device) if Path(args.ckpt).exists(): gen.load_state_dict(torch.load(args.ckpt, map_location=device)) print(f"resumed from {args.ckpt}") opt = torch.optim.Adam(gen.parameters(), lr=args.lr) eps = 1.0 / 255.0 gate = not args.no_gate import random step = 0 burst_start = time.time() wait_safe_window(args.burst, gate) while step < args.steps: if gate and time.time() - burst_start > args.burst: wait_safe_window(args.burst, gate) burst_start = time.time() row_idx = random.randrange(N) x = pil_to_tensor(ds[row_idx]["image"], device).unsqueeze(0) # (1,3,H,W) with torch.no_grad(): r_clean = victim.forward(x) ti = int(r_clean.argmax(dim=1).item()) m0c = r_clean.clone(); m0c[:, ti] = -1e12 tg = int(m0c.argmax(dim=1).item()) # fixed target for this step p = gen(x) # (1,3,H,W) raw field tanhp = torch.tanh(p) soft = tanhp.abs() # soft inclusion in [0,1] delta = eps * tanhp # soft delta; sign(p) is the learned sign xadv = (x + delta).clamp(0, 1) row = victim.net(victim._differentiable_preprocess(xadv)) # margin loss toward the fixed target (want row[tg]-row[ti] >= 10) gap = row[0, tg] - row[0, ti] loss_margin = F.relu(10.0 - gap) density = soft.mean() loss_l0 = args.l0_weight * F.relu(density - args.target_density) * 50.0 loss = loss_margin + loss_l0 opt.zero_grad(); loss.backward(); opt.step() if step % 25 == 0: with torch.no_grad(): # hard eval: top-k by |p| at target density, hard sign(p), rounded to uint8 grid k = max(8, int(args.target_density * x.numel())) thr = torch.topk(soft.flatten(), k).values[-1].clamp(min=1e-6) hardmask = (soft >= thr).float() xh = (x + eps * torch.sign(p) * hardmask).clamp(0, 1) xh = (xh * 255).round() / 255 pred, margin, _ = victim.evaluate(xh[0], ti) dens_hard = float((xh[0] != (x[0]*255).round()/255).float().mean()) print(f"step={step} loss={loss.item():.3f} gap_soft={gap.item():.2f} " f"dens_soft={density.item()*100:.1f}% hard_flip={pred!=ti} hard_m={margin:.2f} " f"hard_dens={dens_hard*100:.1f}%", flush=True) torch.save(gen.state_dict(), args.ckpt) step += 1 torch.save(gen.state_dict(), args.ckpt) print(f"saved {args.ckpt}") if __name__ == "__main__": main()