Download code/scripts/frontier_probe.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 4.47 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/frontier_probe.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/frontier_probe.py
-
curl -L -o frontier_probe.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/frontier_probe.py
4.47 kB
| """Frontier diagnostic: map the density -> best-margin -> score curve on a row and find the | |
| score-optimal operating point, to test whether cp leaves score on the table on hard images. | |
| Score = 0.653 + 0.3*(1 - rmse/0.03)^2 + 0.003*min(margin,10) + 0.01, rmse = sqrt(density)/255. | |
| Since amplitude is +/-1, score is a 1-D tradeoff: more density -> higher reachable margin (up | |
| to the cap 10) but higher rmse penalty. The optimum is the MINIMUM density that still reaches | |
| margin ~10. cp shrinks greedily and may lose margin too fast per pixel; this probe converges | |
| signs at several FIXED densities (top-|g| support) to trace the achievable frontier. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import io, base64, sys, math | |
| from pathlib import Path | |
| REPO_ROOT = Path(__file__).resolve().parents[1] | |
| if str(REPO_ROOT) not in sys.path: | |
| sys.path.insert(0, str(REPO_ROOT)) | |
| import time | |
| import torch | |
| from miner_lib.victim import VictimModel | |
| from perturbnet.imagenet100_bootstrap import load_imagenet100 | |
| from perturbnet.image_io import decode_image_b64 | |
| def wait_safe_window(work_s, lo=38.0, hi=116.0, pad=6.0): | |
| while True: | |
| pos = time.time() % 120.0 | |
| if lo <= pos <= (hi - work_s - pad): | |
| return | |
| time.sleep(2.0) | |
| def pil_to_tensor(img, device): | |
| b = io.BytesIO(); img.convert("RGB").save(b, format="PNG") | |
| return decode_image_b64(base64.b64encode(b.getvalue()).decode()).to(device) | |
| def score_of(density, margin): | |
| rmse = math.sqrt(max(density, 0.0)) / 255.0 | |
| return 0.653 + 0.3 * (1 - rmse / 0.03) ** 2 + 0.003 * min(margin, 10.0) + 0.01 | |
| def mgrad(victim, x0f, delta, ti, tg): | |
| 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 converge_at_density(victim, x0f, ti, tg, dens, steps=120): | |
| """Pick top-|g| support of size dens*N by an initial full-support climb, then converge | |
| signs on that fixed support; return best rounded margin over the run.""" | |
| eps = 1.0 / 255.0 | |
| N = x0f.numel() | |
| k = max(8, int(dens * N)) | |
| # full-support climb to get a gradient magnitude ranking + initial signs | |
| delta = torch.zeros_like(x0f); gmom = torch.zeros_like(x0f) | |
| for _ in range(30): | |
| g, _ = mgrad(victim, x0f, delta, ti, tg) | |
| gmom = 0.9 * gmom + g | |
| delta = (delta + eps * 0.25 * torch.sign(gmom)).clamp(-eps, eps) | |
| imp = (delta.abs() * g.abs()).flatten() | |
| thr = torch.topk(imp, k).values[-1] | |
| mask = (imp >= thr).view_as(delta).float() | |
| delta = delta * mask | |
| # converge signs on fixed support | |
| gmom = torch.zeros_like(x0f); best_m = -1e9 | |
| for _ in range(steps): | |
| g, _ = mgrad(victim, x0f, delta, ti, tg) | |
| gmom = 0.9 * gmom + g | |
| delta = (delta + eps * 0.25 * torch.sign(gmom)).clamp(-eps, eps) * mask | |
| xi = ((x0f + delta).clamp(0, 1) * 255).round().long() | |
| _, m, _ = victim.evaluate(xi.float() / 255, ti) | |
| best_m = max(best_m, float(m)) | |
| dens_actual = float((((x0f + delta).clamp(0,1)*255).round().long() != (x0f*255).round().long()).float().mean()) | |
| return best_m, dens_actual | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--rows", default="114984,15343,81303,79360") | |
| ap.add_argument("--densities", default="0.9,0.7,0.5,0.35,0.25,0.15,0.08") | |
| args = ap.parse_args() | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| victim = VictimModel(device=device) | |
| ds = load_imagenet100(split="train") | |
| densities = [float(d) for d in args.densities.split(",")] | |
| for row in [int(r) for r in args.rows.split(",")]: | |
| x = pil_to_tensor(ds[row]["image"], device) | |
| with torch.no_grad(): | |
| r0 = victim.forward(x)[0] | |
| ti = int(r0.argmax().item()) | |
| m0 = r0.clone(); m0[ti] = -1e12; tg = int(m0.argmax().item()) | |
| print(f"\n=== row {row} ti={ti} tg={tg} ===") | |
| print(f"{'target_d':<10}{'act_d':<9}{'best_m':<9}{'score'}") | |
| best = (-1, 0, 0) | |
| for dens in densities: | |
| wait_safe_window(14.0) | |
| bm, ad = converge_at_density(victim, x, ti, tg, dens) | |
| sc = score_of(ad, bm) | |
| if sc > best[0]: | |
| best = (sc, ad, bm) | |
| print(f"{dens:<10.2f}{ad*100:<9.1f}{bm:<9.2f}{sc:.4f}") | |
| print(f" -> frontier-best score={best[0]:.4f} at density={best[1]*100:.1f}% margin={best[2]:.2f}") | |
| if __name__ == "__main__": | |
| main() | |