"""APGD-guided prune of a warm cp flip — the untested lever wired. cp reaches margin≥10 at ~23% density because its momentum-PGD sign optimizer cannot hold margin below that. APGD holds margin far better (signopt 4.37→8.06, rescued -2→9 rows). This module iteratively prunes cp's support with APGD re-convergence, shaving density at fixed margin 9.0. Verified on box 12 rows (apgd_prune_test.out DONE): mean +0.0021 (5/12 wins +0.0022-0.0156 on dense>20%, 7/12 0 on sparse≤18% where cp already optimal, portfolio best-by-score → 0 regression). e.g. 118423 57.0% 0.9313→34.7% 0.9469 +0.0156, 98715 40.7%→33.8% +0.0049, 82368 24.5%→20.4% +0.0025, 50068 11.4%→9.4% +0.0022. Runs only on dense cp flips in the cp-end→bb_hard_cap slack, so sparse rows stay ~30.5s submit <35s cutoff. Gate 0.20 ensures time only spent where proven. """ from __future__ import annotations import dataclasses import logging import math import time import torch from miner_lib.scoring import quick_score logger = logging.getLogger(__name__) @dataclasses.dataclass class APGDPruneResult: x_adv: torch.Tensor | None flipped: bool score: float margin: float rmse: float density: float elapsed: float def _mgrad(victim, x0f, delta, ti, tg): d = delta.detach().clone().requires_grad_(True) with torch.enable_grad(): row = victim.net(victim._differentiable_preprocess((x0f + d).unsqueeze(0)))[0] g = torch.autograd.grad(row[tg] - row[ti], d, retain_graph=False, create_graph=False)[0] return g.detach(), row.detach() def _sign_converge_apgd(victim, x0f, delta, maskf, ti, tg, steps): eps = 1.0 / 255.0 best = delta.clone() best_m = -1e18 cur = delta.clone() for it in range(int(steps)): cos = 0.5 * (1.0 + math.cos(math.pi * it / max(1, int(steps)))) alpha = (0.01 + (1.0 - 0.01) * cos) * eps * 4.0 g, _ = _mgrad(victim, x0f, cur, ti, tg) g = g * maskf gn = g / (g.flatten().norm() + 1e-12) with torch.no_grad(): cur = (cur + alpha * gn).clamp(-eps, eps) * maskf xi = ((x0f + cur).clamp(0.0, 1.0) * 255.0).round().long() xf = xi.float() / 255.0 # quick margin for best tracking (no score yet) pred, mm, _ = victim.evaluate(xf, ti) if mm > best_m: best_m = mm best = cur.clone() g, _ = _mgrad(victim, x0f, best, ti, tg) return best, g def run_apgd_prune(victim, x_clean, true_index, cfg, *, warm_x_adv, deadline=None): started = time.time() if deadline is None: deadline = started + float(getattr(cfg, "time_budget_seconds", 35.0)) eps = 1.0 / 255.0 x0 = (x_clean.detach().clamp(0.0, 1.0) * 255.0).round().long() x0f = x0.float() / 255.0 ti = int(true_index) hold = float(getattr(cfg, "apgd_prune_hold", 9.0)) steps = int(getattr(cfg, "apgd_prune_steps", 24)) reconv = int(getattr(cfg, "apgd_prune_reconv", 18)) drop_frac = float(getattr(cfg, "apgd_prune_drop", 0.06)) best = APGDPruneResult(None, False, -1.0, -1e9, 1.0, 1.0, 0.0) best_score = -1.0 def keep(delta): nonlocal best, best_score xi = ((x0f + delta).clamp(0.0, 1.0) * 255.0).round().long() xf = xi.float() / 255.0 pred, margin, logits = victim.evaluate(xf, ti) if pred == ti: return -1e9 score, det = quick_score(x0f, xf, logits, ti) if det.get("reason") != "success": return -1e9 if float(score) > best_score: best_score = float(score) best = APGDPruneResult( xi.clone(), True, float(score), float(margin), float(det.get("rmse", 0.0)), float((xi != x0).float().mean().item()), time.time() - started, ) return float(margin) try: delta = (warm_x_adv.to(x0f.device).float() / 255.0 - x0f).clamp(-eps, eps) mask = delta.abs() > 1e-9 # infer target from warm adv point (more stable than clean argmax) with torch.no_grad(): _, _, cl = victim.evaluate((warm_x_adv.float() / 255.0).to(x0f.device), ti) m0 = cl.clone() m0[ti] = -1e12 tg = int(m0.argmax().item()) # seed best with warm point keep(delta) # iterative prune with APGD reconverge for _ in range(8): if time.time() > deadline - 0.5: break delta_c, _ = _sign_converge_apgd(victim, x0f, delta, mask.float(), ti, tg, steps) m = keep(delta_c) if m < hold + 0.1: break # need at least 200 pixels to keep meaningful prune act = mask.flatten().nonzero().flatten() if int(act.numel()) < 200: break with torch.no_grad(): g, _ = _mgrad(victim, x0f, delta_c, ti, tg) contrib = (delta_c * g).flatten() ca = contrib[act] b = max(1, int(drop_frac * int(act.numel()))) drop = act[torch.argsort(ca)[:b]] newmask = mask.clone().flatten() newmask[drop] = False newmask = newmask.view_as(mask) nd = delta_c * newmask.float() nd, _ = _sign_converge_apgd(victim, x0f, nd, newmask.float(), ti, tg, reconv) xi = ((x0f + nd).clamp(0.0, 1.0) * 255.0).round().long() xf = xi.float() / 255.0 pred, mm, logits = victim.evaluate(xf, ti) if mm >= hold: score, det = quick_score(x0f, xf, logits, ti) if det.get("reason") == "success": mask = newmask delta = nd # keep already updated via keep inside loop; also consider nd keep(nd) else: break else: break except Exception as exc: logger.warning("apgd-prune aborted: %s", exc) best.elapsed = time.time() - started if best.x_adv is not None: logger.info("apgd-prune best score=%.4f margin=%.2f rmse=%.6f density=%.1f%% elapsed=%.1fs", best.score, best.margin, best.rmse, best.density * 100.0, best.elapsed) else: logger.info("apgd-prune no flip (elapsed=%.1fs)", best.elapsed) return best