"""Brendel-Bethge-style L0 boundary-walk REFINEMENT, adapted to the pinned-Linf (amp-1) min-L0 game. WHY (Session-14): on ~13% of live rows ("category C") cp reaches margin 10 but at EXACTLY 2x the top-cluster's density (our 42% vs their 21%; often 5x). Pure min-L0 support-quality wall. The cluster's fingerprint (Session-12) is a BOUNDARY min-L0: support = top-K by |grad| AT the adversarial point, signs = sign(grad). cp prunes MONOTONICALLY by converged-contribution from a dense basin (support IoU vs theirs ~0.20) so it can never MIGRATE to a sparser support (once it drops a pixel it can't re-add it). Brendel-Bethge (NeurIPS'19, arXiv:1907.01003) walks ALONG the boundary from a held adversarial point toward the clean input, each step a small trust-region move. KEY lessons from diagnosing the first cut: * reaching margin 10 is EXPENSIVE (~150 steps); do NOT rebuild it from scratch on a fresh support (10-step reconverge on a fresh top-K support loses the flip entirely). * instead START from a held margin-M flip (cp's output) and make TINY support changes, re-projecting cheaply because each move is small. This module therefore REFINES a warm-start flip `warm_delta` (cp's margin-10 delta): each step drops a few lowest-|g| active pixels AND adds a few highest-|g| inactive pixels (the MIGRATION cp lacks), then runs a short sign re-convergence over the whole current support to restore margin>=M. best-by-score (quick_score), evaluated on the exact uint8 grid, delta clamped to +/-1 unit. Portfolio candidate: best-by-score can only help. Knobs via getattr so no config.py change is needed to A/B it. """ from __future__ import annotations import dataclasses import logging import time import torch from miner_lib.scoring import quick_score logger = logging.getLogger(__name__) @dataclasses.dataclass class BBResult: x_adv: torch.Tensor | None flipped: bool score: float margin: float rmse: float density: float target: int elapsed: float def _margin_grad(victim, x0f, delta, ti, tg): d = delta.detach().requires_grad_(True) row = victim((x0f + d).unsqueeze(0))[0] g = torch.autograd.grad(row[tg] - row[ti], d)[0] return g, row.detach() def run_bb_l0_attack(victim, x_clean, true_index, cfg, *, deadline, target=None, warm_delta=None): started = time.time() eps = 1.0 / 255.0 x0 = (x_clean.detach().clamp(0.0, 1.0) * 255.0).round().long() x0f = x0.float() / 255.0 N = int(x0.numel()) ti = int(true_index) warm_steps = int(getattr(cfg, "bb_warm_steps", 150)) M = float(getattr(cfg, "bb_margin_target", 10.2)) drop_frac = float(getattr(cfg, "bb_drop_frac", 0.04)) # small trust-region step on the support add_frac = float(getattr(cfg, "bb_add_frac", 0.015)) # migration: re-add high-|g| inactive pixels reconv = int(getattr(cfg, "bb_reconv_steps", 5)) k_min = max(8, int(getattr(cfg, "bb_kmin_frac", 0.001) * N)) best = BBResult(None, False, -1.0, -1e9, 1.0, 1.0, -1, 0.0) def consider(delta, tg): xi = ((x0f + delta).clamp(0.0, 1.0) * 255.0).round().long() xi = x0 + (xi - x0).clamp(-1, 1) xf = xi.float() / 255.0 pred, tmargin, logits = victim.evaluate(xf, ti) if pred == ti: return float(tmargin), False score, det = quick_score(x0f, xf, logits, ti) ok = det.get("reason") == "success" if ok and score > best.score: best.x_adv = xi.clone(); best.flipped = True; best.score = float(score) best.margin = float(tmargin); best.rmse = float(det.get("rmse", 0.0)) best.density = float((xi != x0).float().mean().item()); best.target = int(tg) return float(tmargin), ok try: # ---- obtain a held margin-M flip: use warm_delta (cp's) if given, else converge full support if target is not None: tg = int(target) else: _, _, cl0 = victim.evaluate(x0f, ti) m0 = cl0.clone(); m0[ti] = -1e12; tg = int(m0.argmax().item()) if warm_delta is not None: delta = warm_delta.detach().clamp(-eps, eps).clone() else: delta = torch.zeros_like(x0f); gmom = torch.zeros_like(x0f) for _ in range(warm_steps): if time.time() > deadline - 0.4: break g, row = _margin_grad(victim, x0f, delta, ti, tg) with torch.no_grad(): gmom = 0.9 * gmom + g delta = (delta + eps * 0.5 * torch.sign(gmom)).clamp(-eps, eps) if float((row.max() - row[ti]).item()) >= M + 2.0: break # re-fix the target to the class the held flip lands on (stable for the walk) with torch.no_grad(): _, _, rowc = victim.evaluate((x0f + delta).clamp(0, 1), ti) m = rowc.clone(); m[ti] = -1e12; tg = int(m.argmax().item()) consider(delta, tg) def reconverge(d, steps): """short sign re-convergence over the CURRENT support of d: restore margin to ~M after a small support change, WITHOUT overshooting (holding just above M keeps the support prunable and avoids wasting density saturating pixels the margin-10 cap does not reward). only active pixels move.""" gm = torch.zeros_like(x0f) supp = (d.abs() > 0).float() for _ in range(steps): if time.time() > deadline - 0.3: break g2, row = _margin_grad(victim, x0f, d, ti, tg) if float((row.max() - row[ti]).item()) >= M + 0.3: break # already on the margin-M surface -> stop with torch.no_grad(): gm = 0.9 * gm + g2 d = (d + eps * 0.5 * torch.sign(gm)).clamp(-eps, eps) * supp return d # ---- boundary walk: small-step migrate (drop low-|g| active + add high-|g| inactive) + reproject stall = 0 while time.time() < deadline - 0.5: g, _ = _margin_grad(victim, x0f, delta, ti, tg) with torch.no_grad(): flat = delta.flatten(); absg = g.abs().flatten() active = (flat.abs() > 0) nact = int(active.sum().item()) if nact <= k_min: break aidx = active.nonzero().flatten() nd_drop = max(1, int(drop_frac * nact)) drop = aidx[torch.argsort(absg[aidx])[:nd_drop]] # lowest-|g| active -> remove na_add = int(add_frac * nact) nf = flat.clone(); nf[drop] = 0.0 if na_add > 0: # MIGRATION: re-add best inactive inact_mask = (nf.abs() == 0) ig = absg.clone(); ig[~inact_mask] = -1.0 add = torch.topk(ig, na_add).indices sgn = torch.sign(g.flatten()[add]) sgn[sgn == 0] = 1.0 nf[add] = sgn * eps nd = nf.view_as(x0f) nd = reconverge(nd, reconv) prev_best = best.score tmargin, ok = consider(nd, tg) # bb_accept_any_score (Session-17 lever E): in margin-LIFT mode (sparse corner) the walk # must keep moving even while tmargin < M -- any exact-score improvement advances the # state; best-by-score still banks everything evaluated. Default off = live behavior. acc_ok = bool(ok and tmargin >= M) if (not acc_ok) and bool(getattr(cfg, "bb_accept_any_score", False)) and ok \ and best.score > prev_best: acc_ok = True if acc_ok: delta = nd; stall = 0 else: stall += 1 if stall == 1: # one gentler retry (half step) with torch.no_grad(): nf = flat.clone() drop2 = aidx[torch.argsort(absg[aidx])[:max(1, nd_drop // 2)]] nf[drop2] = 0.0; nd2 = nf.view_as(x0f) nd2 = reconverge(nd2, reconv) tm2, ok2 = consider(nd2, tg) if ok2 and tm2 >= M: delta = nd2; stall = 0; continue break # cannot sparsify further while holding margin -> min-L0 reached except Exception as exc: logger.warning("bb-l0 aborted: %s", exc) best.elapsed = time.time() - started if best.x_adv is not None: logger.info("bb-l0 score=%.4f margin=%.2f rmse=%.6f density=%.1f%% target=%d elapsed=%.1fs", best.score, best.margin, best.rmse, best.density * 100.0, best.target, best.elapsed) else: logger.info("bb-l0 no valid flip (elapsed=%.1fs)", best.elapsed) return best