sparse-adversarial-research-archive / code /miner_lib /forward_greedy_attack.py
reneeice's picture
full research archive: code, models, datasets, experiments, logs
152228b verified
Raw History Blame Contribute Delete
7.53 kB
"""Forward-greedy (OMP-style) minimum-L0 sparse-margin attack — the density lever.
The rank gap to the top miners is density-at-margin-10: on hard rows cp reaches margin 10 only at
22-29% density while the top miners use ~8-12% (Session-9 leaderboard analysis). Diagnostic proved
the efficient support is NOT gradient-predictable from a single point (our gradient-top-K reaches
only margin ~0-2 at the competitor's 8% density; their exact pixels reach margin ~10). The reason:
~half the efficient pixels only become important AFTER earlier ones are perturbed (interaction).
cp's converge-prune SHRINKS from full support (greedy backward) and keeps ~2x too many pixels.
Forward-greedy GROWS the support from empty, RE-RANKING by the re-computed gradient after each
batch, so interaction-important pixels get selected as the perturbation builds — orthogonal-matching-
pursuit for the sparse attack. It reaches margin ~10 at 6-13% density (validated vs cp on easy AND
hard rows: 80222 0.965->0.974, 23206 0.952->0.968, 97305 0.957->0.967), matching the top miners.
Target selection is adaptive: the argmax rival gets most of the budget; a second rival is tried only
if the first stays weak and budget remains (a fixed multi-target split starves each target — hard
rows need ~15s on the right target). Best-by-score throughout; a converged-contribution prune shaves
residual density while the flip and margin hold.
"""
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 ForwardGreedyResult:
x_adv: torch.Tensor | None # uint8-grid long tensor (like other attacks' x_int)
flipped: bool
score: float
margin: float
rmse: float
density: float
elapsed: float
def _mgrad(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 _converge(victim, x0f, delta, maskf, ti, tg, steps):
eps = 1.0 / 255.0
gmom = torch.zeros_like(x0f)
for _ in range(steps):
g, _ = _mgrad(victim, x0f, delta, ti, tg)
with torch.no_grad():
gmom = 0.9 * gmom + g
delta = (delta + eps * 0.25 * torch.sign(gmom)).clamp(-eps, eps) * maskf
g, _ = _mgrad(victim, x0f, delta, ti, tg)
return delta, g
def _grow_one_target(victim, x0f, x0i, ti, tg, N, deadline, cfg):
"""Grow support from empty toward target tg, then prune. Returns a self-contained best-by-score
result dict for THIS target (score=-1 if it never produced a valid flip)."""
batch = max(1, int(float(getattr(cfg, "fg_batch_frac", 0.012)) * N))
tgt_margin = float(getattr(cfg, "fg_target_margin", 10.0))
conv_steps = int(getattr(cfg, "fg_converge_steps", 12))
prune_rounds = int(getattr(cfg, "fg_prune_rounds", 12))
prune_frac = float(getattr(cfg, "fg_prune_frac", 0.06))
local = {"x_adv": None, "score": -1.0, "margin": -1e9, "rmse": 1.0, "density": 1.0}
def consider(delta):
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 float(margin), False
score, det = quick_score(x0f, xf, logits, ti)
ok = det.get("reason") == "success"
if ok and score > local["score"]:
local["score"] = float(score); local["x_adv"] = xi.clone()
local["margin"] = float(margin); local["rmse"] = float(det.get("rmse", 0.0))
local["density"] = float((xi != x0i).float().mean().item())
return float(margin), ok
mask = torch.zeros_like(x0f)
delta = torch.zeros_like(x0f)
# forward growth: add top-batch pixels by re-computed |g| among not-yet-selected, converge, repeat
while time.time() < deadline:
g, _ = _mgrad(victim, x0f, delta, ti, tg)
with torch.no_grad():
cand = (g.abs() * (1.0 - mask)).flatten()
add = torch.topk(cand, batch).indices
fm = mask.flatten(); fm[add] = 1.0; mask = fm.view_as(x0f)
delta, _ = _converge(victim, x0f, delta, mask, ti, tg, conv_steps)
m, _ = consider(delta)
if m >= tgt_margin:
break
# converged-contribution prune: shave the lowest |delta*g| pixels while the flip + margin hold
if local["x_adv"] is not None:
delta = (local["x_adv"].float() / 255.0) - x0f
mask = (delta.abs() > 1e-9).float()
for _ in range(prune_rounds):
if time.time() > deadline:
break
delta, g = _converge(victim, x0f, delta, mask, ti, tg, conv_steps)
act = mask.flatten().nonzero().flatten()
if act.numel() < 16:
break
contrib = (delta * g).flatten()
b = max(1, int(prune_frac * act.numel()))
drop = act[torch.argsort(contrib[act])[:b]]
nm = mask.clone().flatten(); nm[drop] = False; nm = nm.view_as(mask)
nd, _ = _converge(victim, x0f, delta * nm, nm, ti, tg, conv_steps)
m2, _ = consider(nd) # updates local best if score improved
if m2 >= 9.0:
mask, delta = nm, nd # margin holds -> keep shaving
else:
break
return local
def run_forward_greedy_attack(victim, x_clean, true_index, cfg, *, deadline=None, target=None):
started = time.time()
if deadline is None:
deadline = started + float(getattr(cfg, "time_budget_seconds", 26.0))
dev = x_clean.device
x0f = (x_clean.detach().clamp(0.0, 1.0) * 255.0).round() / 255.0
x0i = (x0f * 255.0).round().long()
N = int(x0i.numel())
best = {"x_adv": None, "score": -1.0, "margin": -1e9, "rmse": 1.0, "density": 1.0}
def merge(res):
if res["x_adv"] is not None and res["score"] > best["score"]:
best.update(res)
try:
if target is not None:
merge(_grow_one_target(victim, x0f, x0i, true_index, int(target), N, deadline, cfg))
else:
with torch.no_grad():
lg = victim.forward(x0f)[0].clone(); lg[true_index] = -1e9
rivals = torch.topk(lg, int(getattr(cfg, "fg_n_targets", 3))).indices.tolist()
reserve = float(getattr(cfg, "fg_second_reserve", 6.0))
merge(_grow_one_target(victim, x0f, x0i, true_index, int(rivals[0]), N, deadline - reserve, cfg))
# weak first target and budget remains -> try the 2nd rival (fixed splits starve each)
if best["margin"] < 9.0 and time.time() < deadline - 4.0 and len(rivals) > 1:
merge(_grow_one_target(victim, x0f, x0i, true_index, int(rivals[1]), N, deadline, cfg))
except Exception as exc:
logger.warning("forward-greedy aborted: %s", exc)
elapsed = time.time() - started
flipped = best["x_adv"] is not None
if flipped:
logger.info("forward-greedy score=%.4f margin=%.2f rmse=%.6f density=%.1f%% elapsed=%.1fs",
best["score"], best["margin"], best["rmse"], best["density"] * 100.0, elapsed)
else:
logger.info("forward-greedy found no flip (elapsed=%.1fs)", elapsed)
return ForwardGreedyResult(
x_adv=best["x_adv"], flipped=flipped, score=best["score"],
margin=best["margin"], rmse=best["rmse"], density=best["density"], elapsed=elapsed,
)