File size: 10,454 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
"""Iterated Local Search over the SUPPORT SET with batched neighborhood evaluation.

WHY THIS EXISTS: every gradient-guided method tried across 15 sessions (cp prune,
BB migrate, FMN eps-step, spgd-IHT, sigma-zero, OMP, APGD...) searches basins defined
by the gradient field, and all plateau at ~2x the top-cluster's density at margin 10.
But the quantity actually scored by the validator is an EXACT closed-form function of
(support size, achieved margin):  S = 0.7*0.933043 + 0.3*(1-rmse/0.03)^2 + 0.003*min(m,10) + 0.01.
So treat the attack as what it is -- discrete optimization over support sets -- and
hill-climb THE SCORE DIRECTLY, evaluating B neighbor supports per round in ONE batched
fp16 forward pass (~50-100ms for B=48). Gradient methods evaluate ONE direction per
backward; this evaluates dozens of set-perturbations per forward.

Moves (all ternary +-1/255 on the uint8 grid, validator-exact):
  drop_i  : remove active pixel i                     -> density -1 (pure rmse gain while margin>10)
  add_j   : add inactive j with sign(g_j)             -> can buy margin (repair path) at rmse cost
  swap_ij : drop i, add j                             -> same size, better pixels (the move cp CANNOT make)
Proposal distributions are STOCHASTIC around contribution/gradient rankings (sample from
bottom-half contributors / top-gradient inactives) so the search samples many neighborhoods
instead of greedily committing -- this is what escapes the prune basin. On stall: random kick
(k swaps), annealed; global best-ever tracked. Final candidate re-verified with quick_score.
"""
from __future__ import annotations

import time
import dataclasses

import torch

from miner_lib.scoring import quick_score


@dataclasses.dataclass
class ILSResult:
    x_adv: torch.Tensor | None
    flipped: bool
    score: float
    margin: float
    rmse: float
    ssim: float = 1.0
    psnr_db: float = 99.0
    elapsed: float = 0.0
    rounds: int = 0


def _batch_scores(victim, x0, x0f, dus, ti):
    """Vectorized exact validator score for a batch of ternary unit-deltas.

    dus: (B,3,H,W) float tensor with values in {-1,0,+1} (=+-1/255 units).
    Returns (scores(B), margins(B)). Invalid (no flip / <8 changed px) -> -1.
    """
    B = dus.shape[0]
    with torch.inference_mode():
        xf = (x0f.unsqueeze(0) + dus * (1.0 / 255.0)).clamp_(0.0, 1.0)
        with torch.autocast(device_type="cuda", dtype=torch.float16):
            logits = victim.net(victim.preprocess(xf))
        rows = logits.float()
        tl = rows[:, ti]
        tmp = rows.clone()
        tmp[:, ti] = -float("inf")
        margins = tmp.max(dim=1).values - tl
        xi = xf.mul_(255.0).round_().long()
        changed = (xi != x0.unsqueeze(0)).flatten(1).sum(1).float()
        rmse = (changed / float(x0.numel())).clamp_min(0).sqrt() / 255.0
        rmse_s = (1.0 - rmse / 0.03).clamp(max=1.0).pow(2)
        scores = 0.7 * 0.933043 + 0.3 * rmse_s + 0.003 * margins.clamp(max=10.0) + 0.01
        scores = torch.where((margins > 0) & (changed >= 8), scores, torch.full_like(scores, -1.0))
    return scores.clone(), margins.clone()


def run_ils_attack(victim, x_clean, true_index, cfg, *, deadline, warm_delta=None,
                   target=None):
    started = time.time()
    torch.backends.cudnn.benchmark = True
    dev = x_clean.device
    eps = 1.0 / 255.0
    x0f = x_clean.detach().float().clamp(0.0, 1.0)
    x0 = (x0f * 255.0).round().long()
    N = int(x0.numel())
    ti = int(true_index)

    batch = int(getattr(cfg, "ils_batch", 48))
    stall_kick = int(getattr(cfg, "ils_stall_kick", 6))
    refresh_every = int(getattr(cfg, "ils_refresh_every", 12))
    max_add_frac = float(getattr(cfg, "ils_max_add_frac", 0.02))

    best = ILSResult(None, False, -1.0, -1e9, 1.0)

    def verify(du):
        xi = ((x0f + du).clamp(0.0, 1.0) * 255.0).round().long()
        xi = x0 + (xi - x0).clamp(-1, 1)
        xf = xi.float() / 255.0
        pred, tmargin, logits = victim.evaluate(xf, ti)
        s, det = quick_score(x0f, xf, logits, ti)
        if pred != ti and s > best.score:
            best.x_adv = xi.clone()
            best.flipped = True
            best.score = float(s)
            best.margin = float(tmargin)
            best.rmse = float(det.get("rmse", 0.0))
            best.elapsed = time.time() - started
        return s

    try:
        # ---- obtain a starting flip ------------------------------------------
        if warm_delta is not None:
            du = (warm_delta.detach().float().clamp(-eps, eps) * 255.0).round().clamp(-1, 1)
        else:
            du = torch.zeros_like(x0f)
            gmom = torch.zeros_like(x0f)
            for _ in range(int(getattr(cfg, "ils_warm_steps", 160))):
                if time.time() > deadline - 1.0:
                    break
                d = du.detach().requires_grad_(True)
                row = victim.net(victim._differentiable_preprocess((x0f + d).unsqueeze(0)))[0]
                g = torch.autograd.grad(row.masked_fill(torch.arange(len(row), device=dev) == ti, -1e12).max() - row[ti], d)[0]
                with torch.no_grad():
                    gmom = 0.9 * gmom + g
                    du = (du + torch.sign(gmom)).clamp(-1, 1)
                with torch.no_grad():
                    _, m, _ = victim.evaluate(((x0f + du).clamp(0, 1)), ti)
                if m >= 11:
                    break
        verify(du)
        if not best.flipped:
            return best  # nothing to local-search from

        # ---- ILS main loop ----------------------------------------------------
        flat0 = x0.flatten().float()
        stall = rounds = 0
        _s0, _m0 = _batch_scores(victim, x0, x0f, du.unsqueeze(0), ti)
        cur_score = float(_s0[0])
        g = None
        while time.time() < deadline - 0.25:
            rounds += 1
            # refresh gradient ranking at the current point periodically
            if rounds % refresh_every == 1 or g is None:
                dg = (du / 255.0).detach().requires_grad_(True)
                row = victim.net(victim._differentiable_preprocess((x0f + dg).unsqueeze(0)))[0]
                masked = row.masked_fill(torch.arange(len(row), device=dev) == ti, -1e12)
                g = torch.autograd.grad(masked.max() - row[ti], dg)[0].flatten()

            dflat = du.flatten()
            active = (dflat != 0)
            aidx = active.nonzero().flatten()
            contrib = (dflat.abs() * g.abs()) [aidx] if aidx.numel() else aidx.new_zeros(0)
            nact = aidx.numel()

            # proposal pool: stochastic drops / adds / swaps around the rankings
            props = []
            order_c = contrib.argsort()          # ascending contribution
            if nact > 12:
                lo = order_c[: max(1, nact // 2)]  # bottom half contributors
                for _ in range(batch // 2):
                    i = int(aidx[int(lo[torch.randint(lo.numel(), (1,)).item()])])
                    j = -1
                    props.append((i, j))
            ig = g.clone()
            ig[dflat != 0] = -1.0
            top_inact = ig.topk(min(400, N)).indices
            live_top = top_inact[ig[top_inact] > 0]
            if live_top.numel() > 0:
                cand = live_top[torch.randint(live_top.numel(), (batch,), device=dev)]
                for jj in cand.tolist():
                    i = int(aidx[int(order_c[torch.randint(nact, (1,)).item()] )]) if nact > 0 else -1
                    props.append((i, int(jj)))
            while len(props) < batch:
                props.append((-1, -1))
            # interleave so both drops and adds fit in the batch budget
            import random as _rnd
            _rnd.shuffle(props)
            props = props[:batch]

            # materialize neighbor deltas
            base = du.unsqueeze(0).repeat(min(batch, len(props)), 1, 1, 1).view(-1, N)
            ok = torch.zeros(base.shape[0], dtype=torch.bool)
            for bidx, (i, j) in enumerate(props[: base.shape[0]]):
                if j >= 0:
                    js = int(j)
                    can_plus = flat0[js] <= 254.0
                    can_minus = flat0[js] >= 1.0
                    sgn = 1.0 if (can_plus and (g[js] >= 0 or not can_minus)) else -1.0
                    if (sgn > 0 and not can_plus) or (sgn < 0 and not can_minus):
                        continue
                    base[bidx, js] = sgn
                    if i >= 0 and base[bidx, i] != 0 and i != js:
                        base[bidx, i] = 0.0
                elif i >= 0:
                    base[bidx, i] = 0.0
                ok[bidx] = True
            if ok.sum() == 0:
                break
            dus_b = base.view(-1, *x0.shape)[ok]

            scores, margins = _batch_scores(victim, x0, x0f, dus_b, ti)
            bi = int(scores.argmax().item())
            if scores[bi] > cur_score + 1e-6:
                du = dus_b[bi].clone().view_as(du)
                cur_score = float(scores[bi])
                stall = 0
                verify(du)
            else:
                stall += 1
                if stall % stall_kick == 0:
                    # random kick: a few random drops + random adds, then test; keep only valid
                    dkick = du.flatten().clone()
                    kk = int(torch.randint(1, 5, (1,)).item())
                    aa = (dkick != 0).nonzero().flatten()
                    if aa.numel() > 16:
                        perm = torch.randperm(aa.numel(), device=dev)[:kk]
                        for pidx in perm.tolist():
                            dkick[aa[pidx]] = 0.0
                            # random add
                            for _try in range(8):
                                jt = int(torch.randint(N, (1,)).item())
                                if abs(dkick[jt]) == 0 and flat0[jt] < 254.5 and flat0[jt] > 0.5:
                                    dkick[jt] = 1.0 if torch.rand(1).item() < 0.5 else -1.0
                                    break
                        du_k = dkick.view_as(du)
                        sc_k, _ = _batch_scores(victim, x0, x0f, du_k.unsqueeze(0), ti)
                        if float(sc_k[0]) > -0.5:
                            du = du_k
        best.rounds = rounds
        best.elapsed = time.time() - started
    except Exception as exc:  # never crash the caller
        import logging
        logging.getLogger("miner_lib").warning("ils aborted: %s", exc)
    return best