Download code/miner_lib/chunkwalk_attack.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 5.54 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/miner_lib/chunkwalk_attack.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/miner_lib/chunkwalk_attack.py
-
curl -L -o chunkwalk_attack.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/miner_lib/chunkwalk_attack.py
5.54 kB
| """Chunkwalk polish: multi-scale verified migration on top of any margin-10 flip. | |
| Validated +0.0041 over cp basins on row 53898 (25.0% -> 20.37% @m10.6). | |
| Per round: drop/add/migrate proposals at multiple scales -> batched trial-reconverge | |
| (fixed-target, fractional lr) -> exact batch scores -> best-eligible pick -> commit+bank. | |
| """ | |
| from __future__ import annotations | |
| import dataclasses | |
| import time | |
| import torch | |
| from miner_lib.scoring import quick_score | |
| class ChunkwalkResult: | |
| x_adv: torch.Tensor | None = None | |
| flipped: bool = False | |
| score: float = -1.0 | |
| margin: float = -1e9 | |
| rmse: float = 1.0 | |
| density: float = 1.0 | |
| elapsed: float = 0.0 | |
| def _score_batch(victim, x0, x0f, dus, ti): | |
| 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 _batched_reconverge(victim, x0f, ti, tg, dus, steps): | |
| B = dus.shape[0] | |
| gmom = torch.zeros_like(dus) | |
| act = dus != 0 | |
| for _ in range(steps): | |
| d = (dus / 255.).requires_grad_(True) | |
| rows = victim.net(victim._differentiable_preprocess((x0f.unsqueeze(0) + d).clamp(0, 1))) | |
| g = torch.autograd.grad(rows[:, tg].sum() - rows[:, ti].sum(), d)[0] | |
| with torch.no_grad(): | |
| gmom.mul_(0.9).add_(g) | |
| dus.add_(0.25 * torch.sign(gmom) * act.float()).clamp_(-1, 1) | |
| return dus | |
| def run_chunkwalk_attack(victim, x_clean, true_index, target, du_start, cfg, *, deadline): | |
| started = time.time() | |
| res = ChunkwalkResult() | |
| dev = x_clean.device | |
| x0f = x_clean.detach().float().clamp(0, 1) | |
| x0 = (x0f * 255).round().long() | |
| N = x0.numel() | |
| ti = int(true_index) | |
| tg = int(target) | |
| du = du_start.detach().float().clamp(-1, 1) | |
| def snap_eval(d_): | |
| xi = (x0 + d_.round().long()).clamp(0, 255) | |
| xf = xi.float() / 255.0 | |
| pred, marg, logits = victim.evaluate(xf.unsqueeze(0), ti) | |
| sc, det = (quick_score(x0f, xf, logits, ti) if pred != ti else (-1.0, {})) | |
| return float(sc), float(marg), float((xi != x0).float().mean().item()) * 100 | |
| bs, bm, bd = snap_eval(du) | |
| best_du = du.clone() | |
| can_plus = x0f.flatten() <= 254.0 / 255.0 | |
| can_minus = x0f.flatten() >= 1.0 / 255.0 | |
| rnd = 0 | |
| while time.time() < deadline - 1.5: | |
| rnd += 1 | |
| d_ = (du / 255.).unsqueeze(0).requires_grad_(True) | |
| r = victim.net(victim._differentiable_preprocess((x0f + d_[0]).unsqueeze(0)))[0] | |
| gf = torch.autograd.grad(r[tg] - r[ti], d_)[0][0].flatten() | |
| imp = du.flatten().abs() * gf.abs() | |
| n_act = int((du != 0).sum().item()) | |
| if n_act <= 400: | |
| break | |
| keep_order = torch.where(du.flatten() != 0, imp, torch.full_like(imp, -1.0)).argsort(descending=True) | |
| inact_order = torch.where(du.flatten() == 0, gf.abs(), torch.zeros_like(gf)).argsort(descending=True) | |
| base = du.flatten() | |
| cands = [] | |
| for s_frac in (0.30, 0.18, 0.10): | |
| k_keep = max(200, int(n_act * (1.0 - s_frac))) | |
| dvv = torch.zeros(N, device=dev) | |
| dvv[keep_order[:k_keep]] = base[keep_order[:k_keep]] | |
| cands.append(dvv.view_as(x0f)) | |
| for j_frac in (0.03, 0.05): | |
| j = max(24, int(n_act * j_frac)) | |
| add_idx = inact_order[:j] | |
| dvv = base.clone() | |
| sg = torch.sign(gf[add_idx]) | |
| sg[sg == 0] = 1.0 | |
| sg = torch.where((sg > 0) & ~can_plus[add_idx], -sg, sg) | |
| sg = torch.where((sg < 0) & ~can_minus[add_idx], -sg, sg) | |
| dvv[add_idx] = sg | |
| cands.append(dvv.view_as(x0f)) | |
| dus = torch.stack(cands) | |
| actb = dus != 0 | |
| dus = _batched_reconverge(victim, x0f, ti, tg, dus, 14) | |
| scs, mgs = _score_batch(victim, x0, x0f, dus, ti) | |
| elig = [k for k in range(len(cands)) if float(mgs[k]) >= 8.4] | |
| if not elig: | |
| break | |
| pick = max(elig, key=lambda k: float(scs[k])) | |
| dn_k = float((dus[pick] != 0).float().mean().item()) * 100 | |
| if not (float(scs[pick]) > bs + 1e-9 or (dn_k < bd * 0.96 and float(scs[pick]) > bs - 0.0012)): | |
| break | |
| du = dus[pick].clone() | |
| du = _batched_reconverge(victim, x0f, ti, tg, du.unsqueeze(0), 6)[0] | |
| s2, m2, d2 = snap_eval(du) | |
| if s2 > bs + 1e-9 and m2 > 0: | |
| bs, bm, bd = s2, m2, d2 | |
| best_du = du.clone() | |
| else: | |
| du = best_du.clone() | |
| if rnd >= 20: | |
| break | |
| if bs > 0: | |
| xi = (x0 + best_du.round().long()).clamp(0, 255) | |
| res.x_adv = xi | |
| res.flipped = True | |
| res.score = bs | |
| res.margin = bm | |
| res.density = bd / 100.0 | |
| res.rmse = (bd / 100.0) ** 0.5 / 255.0 | |
| res.elapsed = time.time() - started | |
| return res | |