Download code/miner_lib/corner_attack.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 8.32 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/miner_lib/corner_attack.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/miner_lib/corner_attack.py
-
curl -L -o corner_attack.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/miner_lib/corner_attack.py
8.32 kB
| """CornerSearch-class sparse adversarial attack (Session-18, ADDITIVE module). | |
| NOT wired into runner.py yet -- offline-validated first via /root/cp_cache.py + | |
| /root/sign_probe.py + /root/corner_lite.py. Safe to import; nothing calls it in | |
| the live path. | |
| Mechanism (adapted from Croce & Hein 2019, "Sparse and imperceptible adversarial | |
| attacks" -- the CornerSearch family): repeatedly sample SMALL pixel subsets from a | |
| gradient-ranked region and run DEEP optimization restricted to each subset with | |
| completely FREE values and signs ([-1/255, 1/255] box). Supports are explored | |
| directly at target cardinality, unlike converge-prune (which locks signs when it | |
| prunes) or FMN-grow (norm-driven growth). Motivation -- Session-6b fingerprinting: | |
| the top cluster's solutions are unreachable from the clean gradient by ANY | |
| single-step criterion and carry quasi-random signs, i.e. the product of a deeply | |
| nonlinear iterative search over (support, signs) pairs. This module implements | |
| exactly that search class. | |
| Batched: B subsets optimized simultaneously through the victim (bf16 autocast), | |
| with exact uint8-grid evaluation every ``eval_every`` steps and best-by-score | |
| tracking identical to the rest of the portfolio. | |
| """ | |
| from __future__ import annotations | |
| import time | |
| from types import SimpleNamespace | |
| import torch | |
| import torch.nn.functional as F | |
| from miner_lib.scoring import quick_score | |
| EPS = 1.0 / 255.0 | |
| def _quant(x: torch.Tensor) -> torch.Tensor: | |
| return torch.clamp((x * 255.0).round(), 0, 255) / 255.0 | |
| def _clean_grad(victim, x_clean, true_index, target): | |
| return victim.margin_grad(x_clean, true_index, target_index=target).detach() | |
| def _sample_subsets(region: torch.Tensor, k: int, batch: int, gen: torch.Generator, | |
| device: torch.device, | |
| seed_ids: torch.Tensor | None = None) -> torch.Tensor: | |
| """[batch, k] long tensors of flat pixel ids. Member 0 is seed-seeded when possible.""" | |
| ridx = torch.randint(region.numel(), (batch, k), generator=gen) | |
| r = region[ridx.to(region.device)] | |
| if seed_ids is not None and seed_ids.numel() > 0: | |
| s = seed_ids | |
| if s.numel() >= k: | |
| sel = s[torch.randperm(s.numel(), generator=gen)[:k].to(s.device)] | |
| else: | |
| fill = region[torch.randint(region.numel(), (k - int(s.numel()),), | |
| generator=gen).to(region.device)] | |
| sel = torch.cat([s, fill]) | |
| r[0] = sel | |
| return r.to(device) | |
| def run_corner_search_attack( | |
| victim, | |
| x_clean: torch.Tensor, | |
| true_index: int, | |
| cfg, | |
| *, | |
| deadline: float | None = None, | |
| target: int | None = None, | |
| seed_delta: torch.Tensor | None = None, | |
| comp_pixels: int | None = None, | |
| k_start: int | None = None, | |
| batch: int = 6, | |
| steps: int = 70, | |
| lr: float = 0.012, | |
| eval_every: int = 10, | |
| region_pixels: int = 18000, | |
| margin_gate: float = 9.5, | |
| k_min: int = 24, | |
| shrink_on_success: float = 0.72, | |
| grow_on_failure: float = 1.42, | |
| max_levels: int = 6, | |
| ): | |
| """Search for the smallest pixel subset (deep free-sign opt per subset) that flips | |
| EfficientNetV2-L with margin >= margin_gate on the exact uint8 grid. | |
| seed_delta: optional float CHW delta (adv - clean, pixel scale) warm-start hint | |
| (e.g. a converged-prune solution) used for member 0 seeding. | |
| comp_pixels: optional cardinality anchor from a reference solution (uid126 count). | |
| """ | |
| dev = x_clean.device | |
| c_, h, w = x_clean.shape | |
| d = c_ * h * w | |
| dl = time.time() if deadline is None else float(deadline) | |
| with torch.no_grad(): | |
| logits0 = victim.forward(x_clean.unsqueeze(0))[0].float() | |
| tl0 = float(logits0[true_index].item()) | |
| masked0 = logits0.clone() | |
| masked0[true_index] = -float("inf") | |
| if target is None: | |
| target = int(masked0.argmax().item()) | |
| gen = torch.Generator() | |
| gen.manual_seed(int(getattr(cfg, "seed", 0)) ^ 0xC0FFEE) | |
| grad_full = _clean_grad(victim, x_clean, true_index, target).reshape(-1) | |
| seed_ids = None | |
| if seed_delta is not None: | |
| sup = seed_delta.detach().abs().reshape(-1) > (EPS * 0.5) | |
| seed_ids = sup.nonzero(as_tuple=False).flatten().to(dev) | |
| if k_start is not None: | |
| k = int(k_start) | |
| elif comp_pixels: | |
| k = max(k_min, int(comp_pixels * 0.9)) | |
| elif seed_ids is not None and seed_ids.numel() > 0: | |
| k = max(k_min, int(seed_ids.numel() * 0.7)) | |
| else: | |
| k = 400 | |
| imp = grad_full.abs() | |
| region = torch.topk(imp, min(int(region_pixels), imp.numel())).indices.to(dev) | |
| x0b = x_clean.unsqueeze(0).expand(batch, -1, -1, -1).contiguous() | |
| gsign = torch.sign(grad_full).to(dev) * EPS # [D] | |
| best = {"score": -1.0, "x_adv": None, "margin": -99.0, "dens": 1.0} | |
| history = [] | |
| n_levels = 0 | |
| while n_levels < max_levels and time.time() < dl - 3.0 and k >= k_min: | |
| n_levels += 1 | |
| kk = min(int(k), int(region.numel())) | |
| ids = _sample_subsets(region, kk, batch, gen, dev, seed_ids=seed_ids) | |
| mask = torch.zeros(batch, d, dtype=torch.bool, device=dev) | |
| mask.scatter_(1, ids, True) | |
| delta = torch.zeros(batch, d, device=dev, requires_grad=True) | |
| with torch.no_grad(): | |
| if seed_ids is not None and seed_ids.numel() > 0 and seed_delta is not None: | |
| sv = seed_delta.detach().reshape(-1).to(dev)[ids] # [B, kk] | |
| signs = torch.where(sv >= 0, EPS, -EPS) | |
| else: | |
| rsgn = (torch.randint(0, 2, ids.shape, generator=gen) * 2 - 1).to(dev) | |
| signs = rsgn * EPS | |
| flat_ids = ids.reshape(-1, 1) | |
| delta.scatter_(1, ids, signs) | |
| m1 = 1 % batch # gsign member | |
| delta[m1] = 0.0 | |
| delta[m1].scatter_(0, ids[m1], gsign[ids[m1]]) | |
| opt = torch.optim.Adam([delta], lr=lr) | |
| tgt = torch.full((batch,), target, dtype=torch.long, device=dev) | |
| true_col = torch.full((batch, 1), true_index, device=dev, dtype=torch.long) | |
| lvl_success = 0 | |
| for step in range(steps): | |
| if time.time() > dl - 2.0: | |
| break | |
| xb = (x0b + delta.view(batch, c_, h, w)).clamp(0.0, 1.0) | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| logits = victim.forward(xb) | |
| loss = F.cross_entropy(logits.float(), tgt) | |
| opt.zero_grad(set_to_none=True) | |
| loss.backward() | |
| opt.step() | |
| with torch.no_grad(): | |
| delta.mul_(mask) | |
| delta.clamp_(-EPS, EPS) | |
| if (step + 1) % 25 == 0: | |
| mg = logits.float().clone() | |
| mg.scatter_(1, true_col, -float("inf")) | |
| tgt.copy_(mg.argmax(dim=1)) | |
| if (step + 1) % eval_every == 0 or step == steps - 1: | |
| with torch.no_grad(): | |
| xi = _quant(x0b + delta.detach().view(batch, c_, h, w)) | |
| lgi = victim.forward(xi).float() | |
| for m in range(batch): | |
| sc, det = quick_score(x0b[m], xi[m], lgi[m], true_index) | |
| if sc > best["score"]: | |
| best.update(score=float(sc), x_adv=xi[m].clone(), | |
| margin=float(det.get("margin", -99.0)), | |
| dens=float((xi[m] != x0b[m]).float().mean().item())) | |
| if sc > 0 and float(det.get("margin", -99.0)) >= margin_gate: | |
| lvl_success += 1 | |
| history.append({"k": int(kk), "success": int(lvl_success), | |
| "best": round(best["score"], 4)}) | |
| if lvl_success > 0: | |
| k = max(k_min, int(kk * shrink_on_success)) | |
| else: | |
| k = min(int(region.numel()), int(kk * grow_on_failure)) | |
| if best["x_adv"] is None: | |
| return SimpleNamespace(flipped=False, x_adv=None, score=-1.0, margin=-99.0, | |
| strategy="corner", history=history) | |
| return SimpleNamespace(flipped=True, x_adv=best["x_adv"], score=best["score"], | |
| margin=best["margin"], strategy="corner", | |
| density=best["dens"], history=history) | |