reneeice's picture
full research archive: code, models, datasets, experiments, logs
152228b verified
Raw History Blame Contribute Delete
8.27 kB
"""Bare-flip grinder: convert the amp-1-feasible-but-missed rescue rows (0.50-0.72)
to real amp-1 flips (~0.90-0.93) by accepting ANY flip and letting score decide.
EVIDENCE (verified on our faithful model vs competitors' actual PNGs):
row 102024: uid230 flips amp-1 -> 0.9340 (m8.04 @ 50.6%); we rescue amp-3 -> 0.498
row 18992 : uid131 -> 0.9377 (m1.49 @ 15.2%); we rescue amp-2 -> 0.694
row 5348 : uid126 -> 0.9212 (m0.02 @ 30.8%); we rescue amp-2 -> 0.708
Offline proof: targeted momentum climb flips 18992's rank-1 rival in 40 steps (4s);
row 102024 needs ~200 steps (or 120 Adam steps). These are NOT infeasible images --
our attacks merely demanded margin>=9-10 and gave up.
Design: runs ONLY when the primary pipeline produced no amp-1 candidate (cp bailed,
finder missed) -- i.e., exactly where guaranteed-flip amplitude escalation would fire.
Spends the free budget on focused per-target climbs (early-stop at margin>=8, then
keep going for score), snapping to the uint8 grid and banking EVERY valid flip via
quick_score -- which automatically prefers a low-margin amp-1 flip (0.92) over any
amp-2 rescue (0.72). Falls through gracefully: caller keeps existing candidates.
"""
from __future__ import annotations
import time
import torch
from miner_lib.scoring import quick_score
def _snap_score(victim, x0f, x0, ti, du):
# clamp to valid uint8 range BEFORE scoring: the submission pipeline encodes
# clamp(0,1) so flips that rely on out-of-range pixels die at validation.
xi = (x0 + du.round().long().clamp(-1, 1)).clamp_(0, 255)
xf = xi.float() / 255.0
pred, m, lg = victim.evaluate(xf.unsqueeze(0), ti)
if pred == ti:
return -1.0, xi
s, det = quick_score(x0f, xf, lg, ti)
return float(s), xi
def run_bareflip(victim, x_clean, true_index, cfg, *, deadline):
started = time.time()
dev = x_clean.device
x0f = x_clean.detach().float().clamp(0.0, 1.0)
x0 = (x0f * 255.0).round().long()
ti = int(true_index)
n_targets = int(getattr(cfg, "bf_targets", 8))
stop_margin = float(getattr(cfg, "bf_stop_margin", 8.0))
max_amp = int(getattr(cfg, "bf_max_amp", 2)) # escalate to +-2/255 if amp-1 starves
screen_steps = int(getattr(cfg, "bf_screen_steps", 36))
screen_frac = float(getattr(cfg, "bf_screen_frac", 0.18)) # of deadline for the screen phase
best_s = -1.0
best_xi = None
def consider(xi):
nonlocal best_s, best_xi
pred, m, lg = victim.evaluate(xi.float().unsqueeze(0) / 255.0, ti)
if pred == ti:
return -1.0
s, det = quick_score(x0f, xi.float() / 255.0, lg, ti)
if s > best_s:
best_s, best_xi = float(s), xi.clone()
return s
try:
torch.backends.cudnn.benchmark = True
with torch.no_grad():
_, _, cl = victim.evaluate(x0f.unsqueeze(0), ti)
masked = cl.clone()
masked[ti] = -float("inf")
cand_tgs = [int(i) for i in torch.topk(masked, n_targets).indices.tolist()]
def climb(tg, amp, steps, dl, warm=None):
"""focused momentum climb at +-amp units; banks snaps; returns last continuous margin."""
lim = float(amp)
du = (warm.clone() if warm is not None else torch.zeros_like(x0f)).clamp(-lim, lim)
gmom = torch.zeros_like(x0f)
m = -1e9
for s in range(steps):
if time.time() > dl - 0.25:
break
d = (du / 255.).unsqueeze(0).requires_grad_(True)
r = victim.net(victim._differentiable_preprocess(x0f.unsqueeze(0) + d))[0]
g = torch.autograd.grad(r[tg] - r[ti], d)[0][0]
with torch.no_grad():
gmom.mul_(0.9).add_(g)
du.add_(torch.sign(gmom)).clamp_(-lim, lim)
if s % 10 == 9:
_, m, _ = victim.evaluate((x0f + du / 255.).clamp(0, 1).unsqueeze(0), ti)
sc, xi = _snap_score(victim, x0f, x0, ti, du)
if sc > 0:
consider(xi)
if m >= stop_margin and amp == 1:
break
return m, du
# ---- PHASE S: DeepFool-style difficulty ranking (one backward per target) --
screen_dl = started + max(2.0, min(3.0, (deadline - started) * 0.12))
diffs = []
for tgc in cand_tgs:
if time.time() > screen_dl:
break
dz = torch.zeros_like(x0f).requires_grad_(True)
r = victim.net(victim._differentiable_preprocess(x0f.unsqueeze(0) + dz))[0]
g_t = torch.autograd.grad(r[tgc] - r[ti], dz)[0].flatten()
gap_t = float(cl[ti].item() - cl[tgc].item()) # positive: true leads by this much
diffs.append((max(gap_t, 0.0) / (g_t.abs().sum().item() + 1e-12), tgc))
diffs.sort()
tgs = [t for _, t in diffs] or cand_tgs
# ---- PHASE A: focused climb on easiest screened target -----------------
m1, du_keep = climb(tgs[0], 1, int(getattr(cfg, "bf_climb_steps", 260)),
started + (deadline - started) * 0.45)
sc, xi = _snap_score(victim, x0f, x0, ti, du_keep)
if sc > 0:
consider(xi)
# ---- PHASE B: next two ranked targets ----------------------------------
for tg in tgs[1:6]:
now = time.time()
if now > deadline - 2.5:
break
_m, _du = climb(tg, 1, int(getattr(cfg, "bf_climb_steps", 260)),
min(deadline - 0.4, now + (deadline - now) * 0.55))
sc, xi = _snap_score(victim, x0f, x0, ti, _du)
if sc > 0:
consider(xi)
if best_s >= getattr(cfg, "bf_good_enough", 0.93):
break
# ---- PHASE C: amp escalation on top-2 (always gets a guaranteed slice) --
if best_s < getattr(cfg, "bf_good_enough", 0.93):
for tg in tgs[:2]:
now = time.time()
if now > deadline - 1.0:
break
_m, _du = climb(tg, max_amp, int(getattr(cfg, "bf_climb_steps", 300)),
min(deadline - 0.3, now + max(3.0, (deadline - now) * 0.6)))
sc, xi = _snap_score(victim, x0f, x0, ti, _du)
if sc > 0:
consider(xi)
# ---- PHASE D: DEEP MODE -- nothing flipped anywhere.
# LIVE EVIDENCE (row 95434, 15:42): gf-amp2 flips rows where every
# TARGETED bf climb fails -- and encode clamps +-2 to +-1, so that flip
# is a FULL-SUPPORT AMP-1 flip along an UNTARGETED (dynamic best-rival)
# direction. Replicate it directly: momentum-flood the current argmax
# rival, banking snaps.
if best_xi is None and time.time() < deadline - 2.0:
du = torch.zeros_like(x0f)
gm = torch.zeros_like(x0f)
_st = 0
while time.time() < deadline - 0.8:
d = (du / 255.).unsqueeze(0).requires_grad_(True)
r = victim.net(victim._differentiable_preprocess(x0f.unsqueeze(0) + d))[0]
with torch.no_grad():
rv = r[0].clone(); rv[ti] = -1e9
tg_now = int(rv.argmax())
g = torch.autograd.grad(r[tg_now] - r[ti], d)[0][0]
with torch.no_grad():
gm.mul_(0.9).add_(g)
du.add_(torch.sign(gm)).clamp_(-1.0, 1.0)
if gm.abs().sum() == 0:
break
_st += 1
if _st % 7 == 0:
sc, xi = _snap_score(victim, x0f, x0, ti, du)
if sc > 0:
consider(xi)
if best_s >= getattr(cfg, "bf_good_enough", 0.93):
break
except Exception as exc:
import logging
logging.getLogger("miner_lib").warning("bareflip aborted: %s", exc)
class _R: # lightweight result compatible with runner checks
flipped = best_xi is not None
x_adv = best_xi
score = best_s
elapsed = time.time() - started
return _R()