from __future__ import annotations import logging import sys import time from dataclasses import dataclass from pathlib import Path import torch from perturbnet.image_io import quantize_image_uint8_grid logger = logging.getLogger(__name__) _REPO_ROOT = Path(__file__).resolve().parents[1] _ADAGAT_DIR = _REPO_ROOT / "Adaptive-Gudiance-AT" def _load_apgd_class(): """Import APGDAttack from the vendored Adaptive-Gudiance-AT research folder. The folder name contains a hyphen so it cannot be a regular package; we put its parent on sys.path and import the inner `autoattack_modified` package directly. """ if str(_ADAGAT_DIR) not in sys.path: sys.path.insert(0, str(_ADAGAT_DIR)) from autoattack_modified.autopgd_base import APGDAttack return APGDAttack @dataclass class ApgdResult: x_adv: torch.Tensor | None flipped: bool amplitude: int elapsed: float def run_apgd_attack( victim, x_clean: torch.Tensor, true_index: int, cfg, *, amplitudes: list[int], deadline: float | None = None, best_loss: bool = False, ) -> ApgdResult: """AutoPGD (Linf) from Adaptive-Gudiance-AT/autoattack_modified/autopgd_base.py. best_loss=True returns the maximum-loss point inside the ball (a margin maximizer), used as a candidate generator even when the grid attack already flipped the image. eps is set slightly above amplitude/255 so the result still rounds to the intended amplitude on the uint8 grid; the perturbation is then clipped to +-amplitude/255. """ started = time.time() if deadline is None: deadline = started + cfg.time_budget_seconds device = x_clean.device x0 = quantize_image_uint8_grid(x_clean.detach()) x = x0.unsqueeze(0).clone() y = torch.tensor([true_index], device=device) try: apgd_cls = _load_apgd_class() except Exception as exc: logger.warning("APGD import failed (%s); falling back to grid-only behavior", exc) return ApgdResult(x_adv=None, flipped=False, amplitude=0, elapsed=time.time() - started) for amplitude in amplitudes: if time.time() > deadline: break # Deadline-aware: scale iterations to fit the remaining slice (~82ms/iter fwd+bwd on A40). # Without this, apgd.perturb() runs all n_iter regardless of the deadline and can blow # past the reserved slice into guaranteed-flip's time (causing a 0.0 regression). remaining = deadline - time.time() max_iters = max(10, int(remaining / 0.09)) # ~9 iters/sec on the A40 iters = min(int(cfg.apgd_iterations), max_iters) if iters < 10: break ball = float(amplitude) / 255.0 apgd = apgd_cls( victim, n_iter=iters, norm="Linf", n_restarts=int(cfg.apgd_restarts), eps=ball, seed=int(cfg.seed), loss=str(cfg.apgd_loss), device=device, ) try: adv = apgd.perturb(x.clone(), y, best_loss=best_loss) except Exception as exc: logger.warning("APGD perturb failed at amplitude %d: %s", amplitude, exc) continue adv_float = adv[0].detach().float() delta = (adv_float - x0).clamp(-ball, ball) adv_float = (x0 + delta).clamp(0.0, 1.0) adv_grid = (adv_float * 255.0).round().long() # Norm-gate guarantee: AutoAttack's continuous Linf-APGD can sit exactly on the # ball boundary, and rounding to the uint8 grid can then push a subpixel to +-2. # Clamp the INTEGER delta to +-amplitude so the result always passes the validator # norm gate (norm in [MIN_LINF_DELTA, MAX_LINF_DELTA] = amp/255). x0_grid = (x0 * 255.0).round().long() adv_grid = (x0_grid + (adv_grid - x0_grid).clamp(-amplitude, amplitude)) pred, _, _ = victim.evaluate(adv_grid.float() / 255.0, true_index) return ApgdResult( x_adv=adv_grid, flipped=bool(pred != true_index), amplitude=amplitude, elapsed=time.time() - started, ) return ApgdResult(x_adv=None, flipped=False, amplitude=0, elapsed=time.time() - started)