Download code/scripts/grid_budget_ab.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 8.36 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/grid_budget_ab.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/grid_budget_ab.py
-
curl -L -o grid_budget_ab.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/grid_budget_ab.py
8.36 kB
| """Grid budget A/B on hard rows: does a bigger grid slice + polish beat the live portfolio? | |
| Hard rows = recent settled rows where live (uid137) scored < 0.948. | |
| Variants per row (idle-window gated, live miner untouched): | |
| g4 / g8 / g12 — grid attack with 4/8/12s deadline (live gets only ~0.12*budget ~= 3.8s) | |
| g12+topup — margin_topup warm-started from the g12 flip | |
| g12+fmn — FMN-L0 polish warm-started from the g12 flip | |
| Joins live / uid64 / uid126 actual scores per row. | |
| Usage: python3 scripts/grid_budget_ab.py [--n 15] [--out /root/grid_budget_ab.jsonl] | |
| """ | |
| from __future__ import annotations | |
| import sys, os, io, json, time, argparse, statistics | |
| 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 numpy as np | |
| import torch | |
| from PIL import Image | |
| from miner_lib.victim import VictimModel | |
| from miner_lib.config import AttackConfig | |
| from miner_lib.scoring import quick_score | |
| from miner_lib.grid_attack import run_grid_attack | |
| from miner_lib.margin_topup import run_margin_topup | |
| from miner_lib.fmn_l0_attack import run_fmn_l0_attack | |
| from perturbnet.imagenet100_bootstrap import load_imagenet100 | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--n", type=int, default=15) | |
| ap.add_argument("--out", default="/root/grid_budget_ab.jsonl") | |
| ap.add_argument("--live-max", type=float, default=0.948, help="hard-row threshold on live score") | |
| a = ap.parse_args() | |
| dev = "cuda:0" | |
| v = VictimModel(device=dev) | |
| ds = load_imagenet100(split="train") | |
| # ---- select hard rows (newest first) ---- | |
| sel, seen = [], set() | |
| for line in reversed(open("/root/lb_real/summary.jsonl", errors="ignore").readlines()): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| if len(sel) >= a.n: | |
| break | |
| d = json.loads(line) | |
| o = d.get("our") or {} | |
| row = d.get("row") | |
| if row in seen or not isinstance(row, int) or not (0 <= row < ds.num_rows): | |
| continue | |
| if o.get("result") == "Valid" and 0.5 < float(o.get("score", 0.0)) < a.live_max: | |
| sel.append({"row": row, "live": float(o["score"])}) | |
| seen.add(row) | |
| if 66907 not in seen: | |
| sel.append({"row": 66907, "live": 0.9309}); seen.add(66907) | |
| print(f"hard rows ({len(sel)}): {[r['row'] for r in sel]}", flush=True) | |
| def gate_idle(): | |
| while True: | |
| pos = time.time() % 120.0 | |
| if 52.0 <= pos <= 102.0: | |
| return | |
| time.sleep(1.0) | |
| def load_clean(row): | |
| p = f"/root/edge_cases/inputs/{row}.png" | |
| if os.path.exists(p): | |
| img = Image.open(p).convert("RGB"); src = "edge" | |
| else: | |
| img = ds[row]["image"].convert("RGB") | |
| buf = io.BytesIO(); img.save(buf, format="JPEG", quality=95); buf.seek(0) | |
| img = Image.open(buf).convert("RGB"); src = "jpeg95" | |
| return torch.from_numpy(np.asarray(img).astype(np.float32) / 255.0).permute(2, 0, 1).to(dev), src | |
| def exact(x, x_int, ti): | |
| xf = x_int.float() / 255.0 | |
| pred, margin, logits = v.evaluate(xf, ti) | |
| if pred == ti: | |
| return {"score": 0.0, "margin": float(margin), "density": 1.0} | |
| score, det = quick_score(x, xf, logits, ti) | |
| ok = det.get("reason") == "success" | |
| dens = float((x_int != (x * 255.0).round().long()).float().mean().item()) | |
| return {"score": float(score) if ok else 0.0, "margin": float(margin), "density": dens} | |
| def refs_for(row): | |
| out = {} | |
| try: | |
| for line in open("/root/lb_real/lb_real.jsonl", errors="ignore"): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| d = json.loads(line) | |
| if d.get("row") == row: | |
| mm = {m.get("uid"): m for m in d.get("miners", []) if isinstance(m, dict)} | |
| for uid in ("64", "126"): | |
| if uid in mm and mm[uid].get("result") == "Valid": | |
| out[f"uid{uid}"] = round(float(mm[uid].get("lastScore", 0.0)), 4) | |
| break | |
| except Exception: | |
| pass | |
| return out | |
| def grid_run(x, ti, secs): | |
| t0 = time.time() | |
| g = run_grid_attack(v, x, ti, AttackConfig(), amplitudes=[1, 2, 3], deadline=time.time() + secs) | |
| el = time.time() - t0 | |
| if g.flipped and g.x_adv is not None: | |
| s = exact(x, g.x_adv.long().to(dev), ti) | |
| else: | |
| s = {"score": 0.0, "margin": -1e9, "density": 1.0} | |
| return g, {**s, "elapsed": round(el, 1)} | |
| results = [] | |
| hdr = f"{'row':<8}{'live':<8}{'g4':<8}{'g8':<8}{'g12':<8}{'g12top':<8}{'g12fmn':<8}{'u64':<8}" | |
| print(hdr, flush=True) | |
| for r in sel: | |
| row = r["row"] | |
| rec = {"row": row, "live": r["live"], "refs": refs_for(row)} | |
| gate_idle() | |
| x, src = load_clean(row) | |
| ti = int(v.forward(x).argmax(dim=1).item()) | |
| rec["ti"] = ti; rec["src"] = src | |
| g4, rec["g4"] = grid_run(x, ti, 4.0) | |
| g8, rec["g8"] = grid_run(x, ti, 8.0) | |
| g12, g12s = grid_run(x, ti, 12.0) | |
| rec["g12"] = g12s | |
| best_g = g12 if (g12 is not None and getattr(g12, "flipped", False) and g12.x_adv is not None) else \ | |
| (g8 if (g8 is not None and getattr(g8, "flipped", False) and g8.x_adv is not None) else g4) | |
| # polishes in the next idle window | |
| rec["g12top"] = {"score": 0.0, "margin": -1e9, "density": 1.0, "elapsed": 0.0, "skip": "no grid flip"} | |
| rec["g12fmn"] = dict(rec["g12top"]) | |
| if best_g is not None and getattr(best_g, "flipped", False) and best_g.x_adv is not None: | |
| gate_idle() | |
| gx = best_g.x_adv | |
| du = gx.float() / 255.0 - x | |
| du = (du * 255.0).round().clamp(-1, 1) / 255.0 # ~integer delta units for topup | |
| t0 = time.time() | |
| try: | |
| tu = run_margin_topup(v, x, ti, AttackConfig(), du, deadline=time.time() + 7.0) | |
| if tu is not None: | |
| xi = (tu if tu.dtype == torch.long or tu.dim() == 3 and tu.max() > 3 else tu) | |
| xi_long = tu.round().clamp(0, 255).long() if tu.dtype != torch.long else tu | |
| rec["g12top"] = {**exact(x, xi_long.to(dev), ti), "elapsed": round(time.time() - t0, 1)} | |
| else: | |
| rec["g12top"] = {"score": 0.0, "margin": -1e9, "density": 1.0, "elapsed": round(time.time() - t0, 1)} | |
| except Exception as e: | |
| rec["g12top"] = {"score": 0.0, "error": str(e)[:80], "elapsed": round(time.time() - t0, 1)} | |
| t0 = time.time() | |
| try: | |
| fm = run_fmn_l0_attack(v, x, ti, AttackConfig(), deadline=time.time() + 7.0, warm_delta=gx.float() / 255.0 - x) | |
| if fm.flipped and fm.x_adv is not None: | |
| rec["g12fmn"] = {**exact(x, fm.x_adv.long().to(dev), ti), "elapsed": round(time.time() - t0, 1)} | |
| else: | |
| rec["g12fmn"] = {"score": 0.0, "margin": -1e9, "density": 1.0, "elapsed": round(time.time() - t0, 1)} | |
| except Exception as e: | |
| rec["g12fmn"] = {"score": 0.0, "error": str(e)[:80], "elapsed": round(time.time() - t0, 1)} | |
| results.append(rec) | |
| with open(a.out, "a") as f: | |
| f.write(json.dumps(rec) + "\n") | |
| print(f"{row:<8}{r['live']:<8.4f}{rec['g4']['score']:<8.4f}{rec['g8']['score']:<8.4f}{rec['g12']['score']:<8.4f}" | |
| f"{rec['g12top'].get('score', 0):<8.4f}{rec['g12fmn'].get('score', 0):<8.4f}" | |
| f"{rec['refs'].get('uid64', 0):<8.4f}", flush=True) | |
| # ---- summary ---- | |
| print("\n==== SUMMARY ====", flush=True) | |
| def m(key, sub="score"): | |
| vals = [r[key].get(sub, 0.0) for r in results if isinstance(r.get(key), dict)] | |
| return statistics.mean(vals) if vals else float("nan") | |
| for k in ("g4", "g8", "g12", "g12top", "g12fmn"): | |
| print(f"{k:<8} mean={m(k):.4f} margin={m(k,'margin') if m(k,'margin')>-1e8 else float('nan'):.2f}", flush=True) | |
| print(f"live mean={statistics.mean(r['live'] for r in results):.4f}", flush=True) | |
| print(f"uid64 mean={statistics.mean([r['refs'].get('uid64', float('nan')) for r in results]):.4f}", flush=True) | |
| flips = {k: sum(1 for r in results if r[k].get("score", 0) > 0) for k in ("g4", "g8", "g12")} | |
| print(f"flip counts: {flips}/{len(results)}", flush=True) | |
| # would-beste: max(g12 variants) vs live | |
| wb = [] | |
| for r in results: | |
| cands = [r["live"]] + [r[k].get("score", 0.0) for k in ("g4", "g8", "g12", "g12top", "g12fmn")] | |
| wb.append(max(cands)) | |
| print(f"portfolio max(live + offline grid variants) = {statistics.mean(wb):.4f} (+{statistics.mean(wb)-statistics.mean(r['live'] for r in results):.4f} vs live)", flush=True) | |
| print("GRID_AB_DONE") | |