"""Margin top-up (Session-26): support-EXPANSION rescue for margin-stuck rows. cp exits stuck rows with a sparse converged solution at margin ~0-8. Below margin 10 the score exchange (+0.003/logit ~ 3 density points) makes buying margin with density +EV. This keeps cp's support and iterates {greedy ADD top-|g| inactive pixels (sign by grad), continuous sign-relax on the enlarged support (fractional du in (-1,1)), bank best by EXACT uint8-grid score}. The fractional relax lets signs flip gradually and lets useless pixels decay through zero — it restructures the support while every banked candidate is a real submittable integer image. Complementary to PnS (which only helps m>=8.5). Validated on gold stuck rows (uint8-grid honest re-run, /root/topup2.log): +0.0064/row, 5W/1T/0L; best row 104765 +0.0234 (m3.7@52% -> m16.9@47%; margin overshoot is capped by `hold` in deployment). """ 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 TopupResult: x_adv: torch.Tensor | None flipped: bool score: float margin: float rmse: float density: float elapsed: float def run_margin_topup(victim, x_clean, true_index, cfg, du_start, *, deadline, hold=10.5, add_frac=0.02, converge_steps=6): """du_start: (3,H,W) float, ~±1 integer delta (0 = inactive). Returns best uint8 image.""" started = time.time() x0f = x_clean.detach().float().clamp(0.0, 1.0) x0 = (x0f * 255.0).round().long() ti = int(true_index) du = du_start.detach().float().round().clamp(-1, 1) best_s = -1.0 best_xi = None best_m = -1e9 def consider(d): nonlocal best_s, best_xi, best_m xi = (x0 + d.round().long()).clamp(0, 255) # uint8 grid FIRST pred, m, l = victim.evaluate(xi.float().unsqueeze(0) / 255.0, ti) if int(pred) == ti: return -1e9 s, det = quick_score(x0f, xi.float() / 255.0, l, ti) if s > best_s: best_s, best_xi, best_m = float(s), xi.clone(), float(m) return float(m) with torch.no_grad(): xi0 = (x0 + du.long()).clamp(0, 255) _, _, lg = victim.evaluate(xi0.float().unsqueeze(0) / 255.0, ti) tg = int(lg.argmax().item()) if tg == ti: return TopupResult(None, False, -1.0, -1e9, 0.0, 0.0, time.time() - started) m_cur = consider(du) try: while time.time() < deadline - 0.3 and m_cur < hold: d = du.clone().requires_grad_(True) row = victim((x0f + d / 255.0).unsqueeze(0))[0] g = torch.autograd.grad(row[tg] - row[ti], d)[0].detach() with torch.no_grad(): gg = g.clone() gg[du.round() != 0] = -1e18 n_add = max(64, int(add_frac * du.numel())) idx = torch.topk(gg.flatten(), n_add).indices add = torch.zeros_like(du).flatten() add[idx] = torch.sign(g.flatten()[idx]) add = add.view_as(du) du = (du.round() + add * (du.round() == 0)).clamp(-1, 1) for _ in range(converge_steps): if time.time() > deadline - 0.2: break d = du.clone().requires_grad_(True) row = victim((x0f + d / 255.0).unsqueeze(0))[0] gc = torch.autograd.grad(row[tg] - row[ti], d)[0] with torch.no_grad(): # continuous relax within [-1,1] on the active support (fractional du) du = ((du + 0.25 * torch.sign(gc)).clamp(-1, 1)) * (du != 0) m_cur = consider(du) except Exception as exc: logger.warning("margin-topup aborted: %s", exc) flipped = best_xi is not None dens = float((best_xi != x0).float().mean().item()) if flipped else 0.0 return TopupResult(best_xi, flipped, best_s if flipped else -1.0, best_m if flipped else -1e9, (dens ** 0.5) / 255.0 if flipped else 0.0, dens, time.time() - started)