Download code/scripts/ab_refine.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 3.05 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/ab_refine.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/ab_refine.py
-
curl -L -o ab_refine.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/ab_refine.py
3.05 kB
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import io | |
| import logging | |
| import sys | |
| import time | |
| 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 torch # noqa: E402 | |
| from miner_lib.config import AttackConfig # noqa: E402 | |
| from miner_lib.runner import resolve_device # noqa: E402 | |
| from miner_lib.sparse_pgd_attack import run_sparse_pgd_attack # noqa: E402 | |
| from miner_lib.victim import VictimModel # noqa: E402 | |
| from perturbnet.imagenet100_bootstrap import load_imagenet100 # noqa: E402 | |
| from perturbnet.image_io import decode_image_b64 # noqa: E402 | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s") | |
| logger = logging.getLogger("ab_refine") | |
| def _pil_b64(image) -> str: | |
| buf = io.BytesIO() | |
| image.convert("RGB").save(buf, format="PNG") | |
| return base64.b64encode(buf.getvalue()).decode("utf-8") | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="A/B sparse-PGD refine gap on random rows") | |
| parser.add_argument("--start", type=int, default=60000) | |
| parser.add_argument("--n", type=int, default=15) | |
| parser.add_argument("--budget", type=float, default=22.0) | |
| args = parser.parse_args() | |
| device = resolve_device("auto") | |
| victim = VictimModel(device=device) | |
| device = victim.device | |
| dataset = load_imagenet100(split="train") | |
| configs = { | |
| "r1": AttackConfig(spgd_refine=1), | |
| "r3": AttackConfig(spgd_refine=3), | |
| "r5": AttackConfig(spgd_refine=5), | |
| } | |
| results = {name: [] for name in configs} | |
| for i in range(args.start, args.start + args.n): | |
| row = dataset[i] | |
| x_clean = decode_image_b64(_pil_b64(row["image"])).to(device) | |
| with torch.no_grad(): | |
| logits = victim(x_clean.unsqueeze(0))[0] | |
| true_index = int(logits.argmax(dim=0).item()) | |
| for name, cfg in configs.items(): | |
| t0 = time.time() | |
| r = run_sparse_pgd_attack(victim, x_clean, true_index, cfg, deadline=t0 + args.budget) | |
| results[name].append((r.score, r.margin, r.rmse, r.density)) | |
| logger.info("[in100-%d] %s score=%.4f m=%.2f rmse=%.6f dens=%.1f%%", i, name, r.score, r.margin, r.rmse, r.density * 100) | |
| print() | |
| hdr = f"{'cfg':<6}{'mean':<9}{'min':<9}{'m_mean':<8}{'rmse_mean':<11}{'dens_mean':<10}" | |
| print(hdr) | |
| for name, rs in results.items(): | |
| scores = [r[0] for r in rs] | |
| m = sum(r[1] for r in rs) / len(rs) | |
| rm = sum(r[2] for r in rs) / len(rs) | |
| dn = sum(r[3] for r in rs) / len(rs) | |
| print(f"{name:<6}{sum(scores)/len(scores):<9.4f}{min(scores):<9.4f}{m:<8.2f}{rm:<11.6f}{dn*100:<10.1f}") | |
| print() | |
| print("per-image delta vs r1:") | |
| for idx in range(args.n): | |
| r1s = results["r1"][idx][0] | |
| line = f" in100-{args.start+idx}: " | |
| for name in configs: | |
| line += f"{name}={results[name][idx][0]-r1s:+.4f} " | |
| print(line) | |
| if __name__ == "__main__": | |
| main() | |