reneeice's picture
full research archive: code, models, datasets, experiments, logs
152228b verified
Raw History Blame Contribute Delete
10.4 kB
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 GridResult:
x_adv: torch.Tensor | None
flipped: bool
score: float
margin: float
pred: int
changed_values: int
amplitude: int
steps: int
pruned: bool
target_index: int | None
elapsed: float
def _to_int_grid(x_float: torch.Tensor) -> torch.Tensor:
return (x_float.detach().clamp(0.0, 1.0) * 255.0).round().long()
def _prune(
victim,
x0_int: torch.Tensor,
x_int: torch.Tensor,
true_index: int,
last_grad: torch.Tensor | None,
*,
chunk_size: int,
deadline: float,
) -> tuple[torch.Tensor, int]:
"""Score-aware backward selection with adaptive chunk sizes: revert chunks of changes
whenever the exact validator score improves (trading margin down for RMSE up along the
true objective). Passes run coarse-to-fine until a full pass at the finest granularity
reverts nothing or the deadline hits (GreedyFool-style budgeted shrink)."""
flat0 = x0_int.flatten()
flat = x_int.flatten()
changed = (flat != flat0).nonzero(as_tuple=False).squeeze(-1)
reverted_total = 0
if changed.numel() == 0:
return x_int, 0
if last_grad is not None:
saliency = last_grad.detach().abs().flatten()
order = changed[torch.argsort(saliency[changed], stable=True)]
else:
order = changed
x0_float = x0_int.float() / 255.0
current_float = flat.view_as(x_int).float() / 255.0
_, _, logits = victim.evaluate(current_float, true_index)
best_score, _ = quick_score(x0_float, current_float, logits, true_index)
chunk = max(1, chunk_size)
while chunk >= 1 and time.time() <= deadline:
reverted_this_pass = 0
for start in range(0, order.numel(), chunk):
if time.time() > deadline:
break
idx = order[start : start + chunk]
trial = flat.clone()
trial[idx] = flat0[idx]
trial_float = trial.view_as(x_int).float() / 255.0
pred, _, trial_logits = victim.evaluate(trial_float, true_index)
if pred == true_index:
continue
score, _ = quick_score(x0_float, trial_float, trial_logits, true_index)
if score > best_score:
flat = trial
best_score = score
reverted_total += int(idx.numel())
reverted_this_pass += int(idx.numel())
if chunk == 1 or reverted_this_pass == 0:
break
chunk = max(1, chunk // 4)
return flat.view_as(x_int), reverted_total
def _greedy_run(
victim,
x0_int: torch.Tensor,
true_index: int,
cfg,
*,
amplitude: int,
deadline: float,
started: float,
best: GridResult,
initial_x_int: torch.Tensor | None = None,
target_index: int | None = None,
) -> tuple[GridResult, torch.Tensor | None]:
device = x0_int.device
x0_float = x0_int.float() / 255.0
n_values = int(x0_int.numel())
base_topk = (
int(cfg.grid_topk_values)
if int(cfg.grid_topk_values) > 0
else max(1, int(round(float(cfg.grid_topk_fraction) * n_values)))
)
cur_topk = base_topk
if initial_x_int is not None and tuple(initial_x_int.shape) == tuple(x0_int.shape):
x_int = initial_x_int.detach().to(device=device, dtype=torch.long).clone()
amplitude = max(amplitude, int((x_int - x0_int).abs().max().item()))
else:
x_int = x0_int.clone()
last_grad: torch.Tensor | None = None
ema_buffer: torch.Tensor | None = None
margin_history: list[float] = []
score_history: list[float] = []
for step in range(int(cfg.grid_max_steps)):
if time.time() > deadline:
break
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)
score_history.append(score)
if score > best.score:
best = dataclasses.replace(
best,
x_adv=x_int.clone(), flipped=True, score=score, margin=margin, pred=pred,
changed_values=int(det.get("changed_values", 0)), amplitude=amplitude,
steps=step + 1, pruned=False, target_index=target_index,
)
if margin >= float(cfg.grid_target_margin):
break
margin_history.append(margin)
if len(margin_history) > 5 and (margin - margin_history[-6]) < float(cfg.grid_plateau_tolerance):
break
patience = max(1, int(getattr(cfg, 'grid_score_patience', 8)))
if len(score_history) > patience and (score - max(score_history[-patience - 1:-1])) <= 0.0:
break
else:
margin_history = []
score_history = []
grad = victim.margin_grad(x_float, true_index, target_index=target_index)
last_grad = grad
saliency_ema = float(getattr(cfg, "grid_saliency_momentum", 0.0))
raw_abs = grad.detach().abs()
if saliency_ema > 0.0:
if ema_buffer is None:
ema_buffer = raw_abs.clone()
else:
ema_buffer.mul_(saliency_ema).add_(raw_abs, alpha=1.0 - saliency_ema)
saliency = ema_buffer.clone()
else:
saliency = raw_abs.clone()
delta = x_int - x0_int
direction = grad.detach().sign().long()
allowed_pos = (direction > 0) & (delta < amplitude) & (x_int < 255)
allowed_neg = (direction < 0) & (delta > -amplitude) & (x_int > 0)
eligible = allowed_pos | allowed_neg
n_eligible = int(eligible.sum().item())
if n_eligible == 0:
break
saliency = torch.where(eligible, saliency, torch.zeros_like(saliency))
k = min(int(cur_topk), n_eligible)
flat_saliency = saliency.flatten()
kth_value = torch.topk(flat_saliency, k, largest=True).values[-1]
selected = flat_saliency >= kth_value
move = torch.where(
allowed_pos.flatten() & selected,
torch.ones_like(delta).flatten(),
torch.where(
allowed_neg.flatten() & selected,
-torch.ones_like(delta).flatten(),
torch.zeros_like(delta).flatten(),
),
)
if int((move != 0).sum().item()) == 0:
break
x_int = (x_int.flatten() + move).view_as(x_int)
if step > 0 and (step + 1) % 10 == 0 and not best.flipped:
cur_topk = max(1, int(cur_topk * float(cfg.grid_topk_growth)))
if cfg.grid_prune and best.flipped and best.x_adv is not None and best.target_index == target_index:
pruned_int, _ = _prune(
victim, x0_int, best.x_adv.to(x0_int.device), true_index, last_grad,
chunk_size=int(cfg.grid_prune_chunk), deadline=deadline,
)
pruned_float = pruned_int.float() / 255.0
pred, margin, logits = victim.evaluate(pruned_float, true_index)
if pred != true_index:
score, det = quick_score(x0_float, pruned_float, logits, true_index)
if score > best.score:
best = dataclasses.replace(
best,
x_adv=pruned_int.clone(), score=score, margin=margin, pred=pred,
changed_values=int(det.get("changed_values", 0)), pruned=True,
)
return best, last_grad
def _runner_up_classes(victim, x0_int: torch.Tensor, true_index: int, k: int) -> list[int]:
x0_float = x0_int.float() / 255.0
_, _, logits = victim.evaluate(x0_float, true_index)
masked = logits.clone()
masked[true_index] = -float("inf")
top = torch.topk(masked, min(k, masked.numel() - 1)).indices
return [int(i) for i in top.tolist()]
def run_grid_attack(
victim,
x_clean: torch.Tensor,
true_index: int,
cfg,
*,
amplitudes: list[int] | None = None,
initial_x_int: torch.Tensor | None = None,
deadline: float | None = None,
) -> GridResult:
"""Greedy discrete +-1/255 margin attack on the uint8 grid.
Maintains an integer pixel state; each step backprops a CW margin through the victim,
moves the top-k most salient eligible pixel-values by one unit, and keeps the best
verified candidate by validator score. Runs one adaptive pass (runner-up re-selected
each step) plus, when cfg.grid_target_classes > 0, pinned-target passes over the top
runner-up classes — the shortest path to a flip is often not through the argmax rival.
"""
started = time.time()
if deadline is None:
deadline = started + cfg.time_budget_seconds
x0_int = _to_int_grid(x_clean.detach().to(x_clean.device))
amp_list = amplitudes if amplitudes is not None else list(range(1, max(1, cfg.grid_max_amplitude) + 1))
best = GridResult(
x_adv=None, flipped=False, score=-1.0, margin=-1e9, pred=true_index,
changed_values=0, amplitude=0, steps=0, pruned=False, target_index=None, elapsed=0.0,
)
targets: list[int | None] = [None]
n_target_classes = max(0, int(getattr(cfg, "grid_target_classes", 0)))
if n_target_classes > 0:
targets += _runner_up_classes(victim, x0_int, true_index, n_target_classes)
for amplitude in amp_list:
if time.time() > deadline or best.flipped:
break
for target in targets:
if time.time() > deadline:
break
initial = initial_x_int if target is None else None
best, _ = _greedy_run(
victim, x0_int, true_index, cfg,
amplitude=amplitude, deadline=deadline, started=started, best=best,
initial_x_int=initial, target_index=target,
)
if best.flipped:
logger.debug(
"grid flip amplitude=%d target=%s score=%.4f margin=%.3f elapsed=%.1fs",
amplitude, "adaptive" if target is None else target, best.score, best.margin,
time.time() - started,
)
best.elapsed = time.time() - started
return best