File size: 9,656 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
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 BoundarySparseResult:
    x_adv: torch.Tensor | None
    flipped: bool
    score: float
    margin: float
    rmse: float
    density: float
    elapsed: float

def _mgrad(victim, x0f, delta, ti, tg):
    with torch.enable_grad():
        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 _sign_converge(victim, x0f, delta, maskf, ti, tg, steps, eps):
    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
    return delta

def run_boundary_sparse_attack(victim, x_clean, true_index, cfg, *, deadline=None, warm_delta=None, target=None):
    started = time.time()
    budget = float(getattr(cfg, "time_budget_seconds", 20.0))
    if deadline is None:
        deadline = started + budget
    eps = 1.0 / 255.0
    x0 = (x_clean.detach().clamp(0,1)*255).round().long()
    x0f = x0.float()/255.0
    N = int(x0.numel())
    target_margin = float(getattr(cfg, "bs_margin_target", 10.0))
    hold = float(getattr(cfg, "bs_hold_margin", 9.0))
    reconv = int(getattr(cfg, "bs_reconv_steps", 12))
    # best tracking
    best = BoundarySparseResult(None, False, -1.0, -1e9, 1.0, 1.0, 0.0)
    def maybe(delta):
        xi = ((x0f + delta).clamp(0,1)*255).round().long()
        xf = xi.float()/255.0
        pred, margin, logits = victim.evaluate(xf, true_index)
        if pred != true_index:
            score, det = quick_score(x0f, xf, logits, true_index)
            if det.get("reason")=="success" and score > best.score:
                best.x_adv = xi.clone(); best.flipped=True; best.score=float(score)
                best.margin=float(margin); best.rmse=float(det.get("rmse",0.0))
                best.density=float((xi!=x0).float().mean().item())
        return float(margin), xi
    # target selection: use provided or screen
    if target is not None:
        tg = int(target)
    else:
        with torch.no_grad():
            _, _, cl = victim.evaluate(x0f, true_index)
            m0 = cl.clone(); m0[true_index] = -1e12
            tg = int(m0.argmax().item())
        # if warm_delta provided, infer tg from its logits
        if warm_delta is not None:
            try:
                with torch.no_grad():
                    wf = (x0f + warm_delta).clamp(0,1)
                    lg = victim(wf.unsqueeze(0))[0]
                    tmp = lg.clone(); tmp[true_index] = -1e18
                    tg = int(tmp.argmax().item())
            except: pass
    # init delta/mask from warm_delta if given else zeros
    if warm_delta is not None:
        delta = warm_delta.clone().detach().to(x0f.device).clamp(-eps, eps)
        mask = (delta.abs() > 0.5*eps)
        # ensure signs align with warm
        maybe(delta)
    else:
        delta = torch.zeros_like(x0f)
        mask = torch.zeros_like(x0f, dtype=torch.bool)
    # iterative boundary linear support growth
    # we start from warm support and iteratively EXPAND via |w| ranking if margin < target,
    # then SHRINK via converged contribution if margin >= target (to sparsify)
    it = 0
    while time.time() < deadline - 0.3 and it < 30:
        it += 1
        cur_margin, cur_xi = maybe(delta)
        # if we already have margin, try to prune to sparser
        if cur_margin >= hold:
            # converge then prune lowest contribution
            delta_c = _sign_converge(victim, x0f, delta, mask.float(), true_index, tg, reconv, eps)
            maybe(delta_c)
            delta = delta_c
            # compute converged contribution and prune 6%
            g, _ = _mgrad(victim, x0f, delta, true_index, tg)
            with torch.no_grad():
                if act.numel() <= max(8, int(0.005*N)):
                    break
                contrib = (delta * g).flatten()
                ca = contrib[act]
                b = max(1, int(float(getattr(cfg, "bs_prune_frac", 0.06)) * act.numel()))
                # sort ascending contribution (lowest first)
                drop = act[torch.argsort(ca)[:b]]
                newmask = mask.clone().flatten(); newmask[drop]=False; newmask=newmask.view_as(mask)
                nd = delta * newmask.float()
                nd = _sign_converge(victim, x0f, nd, newmask.float(), true_index, tg, reconv, eps)
                nm, _ = maybe(nd)
                if nm >= hold:
                    mask = newmask; delta = nd
                    continue
                else:
                    # cannot prune further without losing margin -> try boundary expansion not prune
                    pass
        # need more margin or density headroom: boundary-linear expansion
        # compute w at current point (adaptive rival if no fixed tg, else fixed)
        # use current delta's point for w
        try:
            with torch.enable_grad():
                d = (delta).detach().requires_grad_(True)
                row = victim((x0f + d).unsqueeze(0))[0]
                # pick rival: fixed tg if provided, else argmax at current point
                if target is not None:
                    use_tg = tg
                else:
                    mm = row.detach().clone(); mm[true_index] = -1e12
                    use_tg = int(mm.argmax().item())
                    tg = use_tg  # update
                g = torch.autograd.grad(row[use_tg] - row[true_index], d)[0]
        except Exception:
            break
        with torch.no_grad():
            cur_margin2 = float(cur_margin)
            need = target_margin - cur_margin2 + 0.2  # slack
            if need <= 0:
                need = 0.5  # still try to sparsify via prune above; if here, do small expand for swap
                # do a swap: drop low contrib, add high |w| inactive
                act = mask.flatten().nonzero().flatten()
                ina = (~mask).flatten().nonzero().flatten()
                if act.numel()>0 and ina.numel()>0:
                    contrib = (delta * g).flatten()
                    ca = contrib[act]
                    b = max(1, int(0.03*act.numel()))
                    drop = act[torch.argsort(ca)[:b]]
                    # add top |w| inactive
                    wabs = g.abs().flatten()
                    add = ina[torch.argsort(wabs[ina], descending=True)[:b]]
                    newmask = mask.clone().flatten()
                    newmask[drop]=False; newmask[add]=True
                    newmask=newmask.view_as(mask)
                    # set new pixels to eps*sign(w)
                    nd = delta.clone()
                    nd.view(-1)[add] = eps * torch.sign(g.view(-1)[add])
                    nd = nd * newmask.float()
                    nd = _sign_converge(victim, x0f, nd, newmask.float(), true_index, tg, reconv, eps)
                    nm, _ = maybe(nd)
                    if nm >= hold:
                        mask = newmask; delta = nd
                break
            # rank inactive by |w|
            wabs = g.abs().flatten()
            ina = (~mask).flatten().nonzero().flatten()
            if ina.numel()==0:
                break
            sorted_ina = ina[torch.argsort(wabs[ina], descending=True)]
            # estimate k needed: eps * cumsum |w| >= need
            csum = torch.cumsum(wabs[sorted_ina], dim=0) * eps
            # need in logit space, but linear approx scale is raw; use heuristic factor 2
            k = int((csum < need*2).sum().item()) + 1
            k = max(1, min(k, min(int(0.05*N), ina.numel()), 512))
            add = sorted_ina[:k]
            newmask = mask.clone().flatten(); newmask[add]=True; newmask=newmask.view_as(mask)
            nd = delta.clone()
            # set newly added pixels to eps*sign(w)
            flat_nd = nd.view(-1); flat_g = g.view(-1); flat_add = add
            flat_nd[flat_add] = eps * torch.sign(flat_g[flat_add])
            nd = flat_nd.view_as(delta) * newmask.float()
            nd = _sign_converge(victim, x0f, nd, newmask.float(), true_index, tg, reconv, eps)
            nm, _ = maybe(nd)
            # if expansion lost margin (bad linear approx), keep it only if margin improved
            if nm > cur_margin2 - 0.5:
                mask = newmask; delta = nd
            else:
                # try smaller k
                k2 = max(1, k//2)
                add2 = sorted_ina[:k2]
                newmask2 = mask.clone().flatten(); newmask2[add2]=True; newmask2=newmask2.view_as(mask)
                nd2 = delta.clone(); flat_nd2 = nd2.view(-1)
                flat_nd2[add2] = eps * torch.sign(flat_g[add2])
                nd2 = flat_nd2.view_as(delta) * newmask2.float()
                nd2 = _sign_converge(victim, x0f, nd2, newmask2.float(), true_index, tg, reconv, eps)
                nm2,_ = maybe(nd2)
                if nm2 > cur_margin2 -0.5:
                    mask=newmask2; delta=nd2
                break
        if time.time() >= deadline -0.5:
            break
    best.elapsed = time.time() - started
    if best.x_adv is not None:
        logger.info("boundary-sparse best score=%.4f margin=%.2f rmse=%.6f density=%.1f%% elapsed=%.1fs it=%d", best.score, best.margin, best.rmse, best.density*100.0, best.elapsed, it)
    else:
        logger.info("boundary-sparse no flip elapsed=%.1fs it=%d", best.elapsed, it)
    return best