Download code/scripts/gen_tsaa_ab.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 3.72 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/gen_tsaa_ab.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/gen_tsaa_ab.py
-
curl -L -o gen_tsaa_ab.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/gen_tsaa_ab.py
3.72 kB
| """A/B: gen_attack with supgen3 head vs TSAA LONG head as the prior. | |
| 30 fresh lb_val rows (disjoint from TSAA training rows). 24s budget each. | |
| Usage: python3 scripts/gen_tsaa_ab.py [--budget 24] [--n 30] | |
| """ | |
| from __future__ import annotations | |
| import sys, os, time, json, argparse, base64, io, 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)) | |
| if "/root/Perturb/scripts" not in sys.path: | |
| sys.path.insert(0, "/root/Perturb/scripts") | |
| import torch | |
| from miner_lib.victim import VictimModel | |
| from miner_lib.config import AttackConfig | |
| from gen_attack import run_gen_attack | |
| from perturbnet.imagenet100_bootstrap import load_imagenet100 | |
| from perturbnet.image_io import decode_image_b64 | |
| def pil_b64(img): | |
| b = io.BytesIO(); img.convert("RGB").save(b, format="PNG") | |
| return base64.b64encode(b.getvalue()).decode() | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--budget", type=float, default=24.0) | |
| ap.add_argument("--n", type=int, default=30) | |
| ap.add_argument("--sup", default="/root/supgen3/head_ep5.pt") | |
| ap.add_argument("--tsaa", default="/root/tsaa/head_LONG_ep50.pt") | |
| ap.add_argument("--out", default="/root/gen_tsaa_ab.jsonl") | |
| a = ap.parse_args() | |
| recs = [json.loads(l) for l in open("/root/lb_val.jsonl") if l.strip()][:a.n] | |
| ds = load_imagenet100(split="train") | |
| v = VictimModel(device="cuda:0") | |
| # train rows for contamination check | |
| train_rows = set() | |
| te = "/root/supgen3/train_ext.jsonl" | |
| if os.path.exists(te): | |
| for l in open(te): | |
| if l.strip(): | |
| train_rows.add(json.loads(l).get("row")) | |
| cfg_sup = AttackConfig() | |
| cfg_sup.gen_head_path = a.sup | |
| cfg_tsaa = AttackConfig() | |
| cfg_tsaa.gen_head_path = a.tsaa | |
| results = [] | |
| print(f"{'row':<9}{'sup_sc':<9}{'tsaa_sc':<9}{'d':<9}{'sup_m':<8}{'tsaa_m':<8}{'sup_dn':<8}{'tsaa_dn':<8}{'u126':<9}") | |
| for r in recs: | |
| row = r["row"] | |
| if row >= ds.num_rows: | |
| continue | |
| contam = "C" if row in train_rows else "." | |
| x = decode_image_b64(pil_b64(ds[row]["image"])).to(v.device) | |
| ti = int(v.forward(x).argmax(dim=1).item()) | |
| # supgen3 | |
| t0 = time.time() | |
| r_sup = run_gen_attack(v, x, ti, cfg_sup, deadline=t0 + a.budget) | |
| # tsaa | |
| t0 = time.time() | |
| r_tsaa = run_gen_attack(v, x, ti, cfg_tsaa, deadline=t0 + a.budget) | |
| u126 = r.get("uid126", {}).get("score", 0.0) | |
| rec = { | |
| "row": row, "contaminated": row in train_rows, | |
| "sup": {"score": r_sup.score if r_sup.flipped else 0.0, | |
| "margin": r_sup.margin, "density": r_sup.density, | |
| "flipped": r_sup.flipped, "tg": r_sup.tg_used}, | |
| "tsaa": {"score": r_tsaa.score if r_tsaa.flipped else 0.0, | |
| "margin": r_tsaa.margin, "density": r_tsaa.density, | |
| "flipped": r_tsaa.flipped, "tg": r_tsaa.tg_used}, | |
| "u126": u126, | |
| } | |
| results.append(rec) | |
| with open(a.out, "a") as f: | |
| f.write(json.dumps(rec) + "\n") | |
| s_s = rec["sup"]["score"]; s_t = rec["tsaa"]["score"] | |
| print(f"{row:<9}{s_s:<9.4f}{s_t:<9.4f}{s_t-s_s:<+9.4f}{rec['sup']['margin']:<8.2f}" | |
| f"{rec['tsaa']['margin']:<8.2f}{rec['sup']['density']*100:<8.2f}" | |
| f"{rec['tsaa']['density']*100:<8.2f}{u126:<9.4f}{contam}", flush=True) | |
| if results: | |
| sup = [r["sup"]["score"] for r in results] | |
| ts = [r["tsaa"]["score"] for r in results] | |
| print(f"\nsupgen3 mean={statistics.mean(sup):.4f} flips={sum(1 for s in sup if s>0)}/{len(sup)}") | |
| print(f"tsaa mean={statistics.mean(ts):.4f} flips={sum(1 for s in ts if s>0)}/{len(ts)}") | |
| print(f"delta (tsaa-sup) = {statistics.mean(ts)-statistics.mean(sup):+.4f}") | |
| print(f"tsaa wins {sum(1 for s,t in zip(sup,ts) if t>s)}/{len(sup)}") | |