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 LassoResult: x_adv: torch.Tensor | None flipped: bool score: float margin: float elapsed: float def _soft_margin(row: torch.Tensor, true_index: int, n_classes: int) -> torch.Tensor: """Smooth surrogate of (best_non_true_logit - true_logit): LSE over top-M non-true logits.""" masked = row.clone() masked[true_index] = -1e12 top = torch.topk(masked, min(n_classes, masked.numel() - 1)).values return torch.logsumexp(top, dim=0) - row[true_index] def _targeted_margin(row: torch.Tensor, true_index: int) -> torch.Tensor: """Adaptive CW margin: difference to the CURRENT argmax rival (re-selected from detached logits each call, so all gradient mass goes to the single class the validator pays for).""" with torch.no_grad(): masked = row.clone() masked[true_index] = -1e12 target = int(masked.argmax(dim=0).item()) return row[target] - row[true_index] def _snapshot(victim, u, x0_float, mask, step_unit, true_index, best: LassoResult, started: float, stage: str) -> LassoResult: """Quantize the masked tanh state to the uint8 grid, verify exactly, keep the best score.""" with torch.no_grad(): delta = step_unit * torch.tanh(u.detach()) * mask cand = (x0_float + delta).clamp(0.0, 1.0) x_int = (cand * 255.0).round().long() x_float = x_int.float() / 255.0 pred, margin, logits = victim.evaluate(x_float, true_index) if pred != true_index: score, det = quick_score(x0_float, x_float, logits, true_index) if score > best.score: best = LassoResult(x_adv=x_int.clone(), flipped=True, score=score, margin=margin, elapsed=time.time() - started) logger.debug( "lasso %s snapshot score=%.4f margin=%.3f rmse=%.6f density=%.4f", stage, score, margin, det.get("rmse", float("nan")), float((x_int != (x0_float * 255.0).round().long()).float().mean().item()), ) return best def run_lasso_attack( victim, x_clean: torch.Tensor, true_index: int, cfg, *, amplitudes: tuple[int, ...] | list[int] = (1,), deadline: float | None = None, initial_x_int: torch.Tensor | None = None, ) -> LassoResult: """Two-phase minimal-density attack at Linf = amplitude/255 (SparseFool/homotopy, grid-adapted). Phase A (reach): Adam on delta = s*tanh(u), loss = -soft_margin. Snapshots every few steps; stops early once the exact margin clears the stop threshold (validator caps the margin bonus at 10, so margin beyond the buffer is wasted density). Phase B (shrink): iterative hard thresholding — restrict delta to the top-S support by |u|, re-optimize signs/weights under a margin barrier relu(stop - soft_margin)*w, shrink S geometrically, and snapshot exactly at each stage. The best exact-score candidate over the whole path is returned. """ started = time.time() if deadline is None: deadline = started + cfg.time_budget_seconds x0_int = (x_clean.detach().clamp(0.0, 1.0) * 255.0).round().long() x0_float = x0_int.float() / 255.0 n_values = int(x0_int.numel()) best = LassoResult(x_adv=None, flipped=False, score=-1.0, margin=-1e9, elapsed=0.0) amplitude = int(amplitudes[0]) if amplitudes else 1 step_unit = float(amplitude) / 255.0 # ---- Phase A: reach (dense margin maximization with early stop) ---- if initial_x_int is not None and tuple(initial_x_int.shape) == tuple(x0_int.shape): # Warm start: map the int-grid delta to tanh-space (clamp ±1 to a finite u). delta = ((initial_x_int.to(x0_int.device) - x0_int).float() / 255.0) / step_unit delta = delta.clamp(-0.995, 0.995) u0 = torch.atanh(delta) else: u0 = torch.zeros_like(x0_float) u = u0.clone().requires_grad_(True) optimizer = torch.optim.Adam([u], lr=float(cfg.lasso_lr)) margin_stop = float(cfg.lasso_margin_stop) reached = False for it in range(int(cfg.lasso_iterations)): if time.time() > deadline: break delta = step_unit * torch.tanh(u) row = victim((x0_float + delta).unsqueeze(0))[0] soft_margin = _targeted_margin(row, true_index) loss = -soft_margin + float(getattr(cfg, 'lasso_phase_l1', 1.0)) * (delta.abs().mean() / step_unit) optimizer.zero_grad(set_to_none=True) loss.backward() optimizer.step() if (it + 1) % 4 == 0 or it == int(cfg.lasso_iterations) - 1: best = _snapshot(victim, u, x0_float, torch.ones_like(x0_float), step_unit, true_index, best, started, "A") if best.flipped and best.margin >= margin_stop: reached = True logger.info( "lasso phase A done it=%d margin=%.3f score=%.4f elapsed=%.1fs", it, best.margin, best.score, time.time() - started, ) break if not best.flipped: best.elapsed = time.time() - started logger.info("lasso phase A failed to flip (margin=%.3f elapsed=%.1fs)", best.margin, best.elapsed) return best # ---- Phase B: shrink (hard-threshold support homotopy with margin barrier) ---- # Rank by raw |u|: tanh saturates to ~1 for most pixels after phase A, which would # make the top-S threshold keep the entire support; |u| stays discriminative. with torch.no_grad(): support_scores = u.detach().abs().flatten() n_changed = int((support_scores > 0.2).sum().item()) support_size = max(64, n_changed) min_support = max(32, int(0.001 * n_values)) shrink_factor = float(getattr(cfg, "lasso_shrink_factor", 0.7)) barrier_w = float(getattr(cfg, "lasso_barrier_weight", 4.0)) stage_iters = max(4, int(getattr(cfg, "lasso_stage_iterations", 12))) stage_count = 0 while time.time() < deadline and support_size > min_support: stage_count += 1 with torch.no_grad(): k = min(support_size, support_scores.numel()) kth = torch.topk(support_scores, k).values[-1] mask = (support_scores >= kth).view_as(x0_float).float() u = (u.detach() * mask).clone().requires_grad_(True) optimizer = torch.optim.Adam([u], lr=float(cfg.lasso_lr)) for it in range(stage_iters): if time.time() > deadline: break delta = step_unit * torch.tanh(u) * mask row = victim((x0_float + delta).unsqueeze(0))[0] soft_margin = _targeted_margin(row, true_index) barrier = torch.relu(margin_stop - soft_margin) * barrier_w loss = barrier + 0.05 * torch.tanh(u).abs().mean() optimizer.zero_grad(set_to_none=True) loss.backward() optimizer.step() if (it + 1) % 4 == 0 or it == stage_iters - 1: best = _snapshot(victim, u, x0_float, mask, step_unit, true_index, best, started, f"B{stage_count}") with torch.no_grad(): support_scores = (u.detach().abs() * mask).flatten() support_scores[~mask.flatten().bool()] = 0.0 support_size = max(min_support, int(support_size * shrink_factor)) best.elapsed = time.time() - started logger.info( "lasso done stages=%d best score=%.4f margin=%.3f elapsed=%.1fs", stage_count, best.score, best.margin, best.elapsed, ) return best