Download code/scripts/cap_ab.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 7.97 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/cap_ab.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/cap_ab.py
-
curl -L -o cap_ab.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/cap_ab.py
7.97 kB
| """Margin-cap A/B (offline): on the SAME 30 hard rows from grid_budget_ab + grid_ab2. | |
| Per row: run cp (dense, live portfolio primary) -> if margin overshoots 10.3: | |
| (a) apgd-prune (reconverge+prune machinery) | |
| (b) cap-shrink (custom: zero lowest-|delta| support in 5% chunks while flip holds & margin>=10.05) | |
| Join: live score, g12 (from round jsonl), uid64. 'What could have been' = max over all variants. | |
| Idle-window gated. Usage: python3 scripts/cap_ab.py | |
| """ | |
| 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.converge_prune_attack import run_converge_prune_attack | |
| from miner_lib.apgd_prune import run_apgd_prune | |
| from perturbnet.imagenet100_bootstrap import load_imagenet100 | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--out", default="/root/cap_ab.jsonl") | |
| ap.add_argument("--cp_seconds", type=float, default=25.0) | |
| ap.add_argument("--prune_seconds", type=float, default=12.0) | |
| a = ap.parse_args() | |
| dev = "cuda:0" | |
| v = VictimModel(device=dev) | |
| ds = load_imagenet100(split="train") | |
| # ---- gather the SAME 30 rows (round 1 + round 2) with their g12/live/uid64 ---- | |
| rows = {} | |
| for f in ("/root/grid_budget_ab.jsonl", "/root/grid_ab2.jsonl"): | |
| try: | |
| for l in open(f, errors="ignore"): | |
| if not l.strip(): | |
| continue | |
| d = json.loads(l) | |
| r = {"row": d["row"], "live": d["live"], "g12": d.get("g12", {}).get("score", 0.0), | |
| "uid64": d.get("refs", {}).get("uid64")} | |
| rows[d["row"]] = r | |
| except FileNotFoundError: | |
| pass | |
| rows = list(rows.values()) | |
| print(f"rows: {[r['row'] for r in rows]}", 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 cap_shrink(x, x_int, ti, cap=10.05, chunk=0.05): | |
| """Zero lowest-|delta| support pixels in chunks while flip holds and margin >= cap. | |
| Track best-by-score snapshot.""" | |
| x0 = (x * 255.0).round().long() | |
| delta = (x_int - x0) | |
| sup = (delta != 0).flatten().nonzero().flatten() | |
| if sup.numel() == 0: | |
| return None | |
| cur = x_int.clone() | |
| best = exact(x, cur, ti) | |
| t0 = time.time() | |
| for _ in range(40): | |
| if time.time() - t0 > 12.0: | |
| break | |
| d = (cur - x0).flatten() | |
| act = (d != 0).nonzero().flatten() | |
| if act.numel() < 50: | |
| break | |
| imp = d[act].abs() | |
| k = max(1, int(act.numel() * chunk)) | |
| drop = act[torch.argsort(imp)[:k]] | |
| cand = cur.clone().flatten() | |
| cand[drop] = x0.flatten()[drop] | |
| cand = cand.view_as(cur) | |
| s = exact(x, cand, ti) | |
| if s["score"] > 0.0 and s["margin"] >= cap: | |
| cur = cand | |
| if s["score"] > best["score"]: | |
| best = s | |
| else: | |
| break | |
| best["elapsed"] = round(time.time() - t0, 1) | |
| return best | |
| results = [] | |
| print(f"{'row':<8}{'cp':<8}{'cp_m':<7}{'cp_d%':<7}{'apgd':<8}{'capsh':<8}{'gain':<8}{'g12':<8}{'live':<8}{'u64':<8}{'couldbe':<9}", flush=True) | |
| for r in rows: | |
| row = r["row"] | |
| gate_idle() | |
| x, src = load_clean(row) | |
| ti = int(v.forward(x).argmax(dim=1).item()) | |
| cfg = AttackConfig() | |
| t0 = time.time() | |
| cp = run_converge_prune_attack(v, x, ti, cfg, deadline=time.time() + a.cp_seconds) | |
| rec = {"row": row, "src": src, "live": r["live"], "g12": r["g12"], "uid64": r["uid64"], | |
| "cp": {"score": 0.0, "margin": -1e9, "density": 1.0, "elapsed": round(time.time() - t0, 1)}} | |
| if cp is not None and getattr(cp, "flipped", False) and cp.x_adv is not None: | |
| cpx = cp.x_adv.long().to(dev) | |
| rec["cp"] = {**exact(x, cpx, ti), "elapsed": round(time.time() - t0, 1)} | |
| rec["apgd"] = {"score": 0.0, "margin": -1e9, "density": 1.0, "skip": "m<=10.3"} | |
| rec["capsh"] = {"score": 0.0, "skip": "m<=10.3"} | |
| if rec["cp"]["margin"] > 10.3: | |
| gate_idle() | |
| t0 = time.time() | |
| ap_ = run_apgd_prune(v, x, ti, cfg, warm_x_adv=cp.x_adv, deadline=time.time() + a.prune_seconds) | |
| if ap_ is not None and getattr(ap_, "flipped", False) and ap_.x_adv is not None: | |
| rec["apgd"] = {**exact(x, ap_.x_adv.long().to(dev), ti), "elapsed": round(time.time() - t0, 1)} | |
| t0 = time.time() | |
| cs = cap_shrink(x, cpx, ti) | |
| rec["capsh"] = cs if cs is not None else {"score": 0.0, "skip": "no support"} | |
| else: | |
| rec["apgd"] = {"score": 0.0, "skip": "cp no flip"} | |
| rec["capsh"] = {"score": 0.0, "skip": "cp no flip"} | |
| variants = [rec["cp"].get("score", 0), rec["apgd"].get("score", 0), rec["capsh"].get("score", 0), | |
| r["g12"], r["live"]] | |
| rec["could_have_been"] = max(variants) | |
| results.append(rec) | |
| with open(a.out, "a") as f: | |
| f.write(json.dumps(rec) + "\n") | |
| gain = max(rec["apgd"].get("score", 0), rec["capsh"].get("score", 0)) - rec["cp"].get("score", 0) | |
| print(f"{row:<8}{rec['cp']['score']:<8.4f}{rec['cp']['margin']:<7.2f}{100*rec['cp']['density']:<7.2f}" | |
| f"{rec['apgd'].get('score',0):<8.4f}{rec['capsh'].get('score',0):<8.4f}{gain:<+8.4f}" | |
| f"{r['g12']:<8.4f}{r['live']:<8.4f}{(r['uid64'] or 0):<8.4f}{rec['could_have_been']:<9.4f}", flush=True) | |
| print("\n==== SUMMARY ====", flush=True) | |
| def mm(key, sub="score"): | |
| vals = [rr[key].get(sub, 0.0) for rr in results if isinstance(rr.get(key), dict)] | |
| return st.mean(vals) if vals else float("nan") | |
| ov = [rr for rr in results if rr["cp"].get("margin", 0) > 10.3] | |
| print(f"cp flips={sum(1 for rr in results if rr['cp']['score']>0)}/{len(results)} cp mean={mm('cp'):.4f} " | |
| f"margin={st.mean([rr['cp']['margin'] for rr in results if rr['cp']['margin']>-1e8]):.2f}") | |
| print(f"overshoot rows (cp m>10.3): {len(ov)}") | |
| if ov: | |
| print(f" apgd-prune mean={st.mean([rr['apgd'].get('score',0) for rr in ov]):.4f} " | |
| f"margin={st.mean([rr['apgd'].get('margin',0) for rr in ov if rr['apgd'].get('margin',0)>-1e8]):.2f}") | |
| print(f" cap-shrink mean={st.mean([rr['capsh'].get('score',0) for rr in ov]):.4f} " | |
| f"margin={st.mean([rr['capsh'].get('margin',0) for rr in ov if rr['capsh'].get('margin',0)>-1e8]):.2f}") | |
| print(f" cp mean={st.mean([rr['cp']['score'] for rr in ov]):.4f}") | |
| print(f"live mean={st.mean([rr['live'] for rr in results]):.4f} g12 mean={st.mean([rr['g12'] for rr in results]):.4f} " | |
| f"uid64 mean={st.mean([rr['uid64'] for rr in results if rr['uid64']]):.4f}") | |
| print(f"WHAT COULD HAVE BEEN (max of live+all offline variants): {st.mean([rr['could_have_been'] for rr in results]):.4f} " | |
| f"(+{st.mean([rr['could_have_been'] for rr in results])-st.mean([rr['live'] for rr in results]):.4f} vs live)") | |
| print("CAP_AB_DONE") | |