File size: 10,375 Bytes
152228b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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