Download code/scripts/ab_sigma.py from reneeice/sparse-adversarial-research-archive: direct link, hf CLI and curl.
- Browser
- Download file 4.28 kB
-
https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/ab_sigma.py
- Command line
-
hf download hf://datasets/reneeice/sparse-adversarial-research-archive/code/scripts/ab_sigma.py
-
curl -L -o ab_sigma.py https://huggingface.co/datasets/reneeice/sparse-adversarial-research-archive/resolve/main/code/scripts/ab_sigma.py
4.28 kB
| from __future__ import annotations | |
| import argparse | |
| 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, attack_config_from_args, add_attack_args # noqa: E402 | |
| from miner_lib.runner import resolve_device, run_attack # noqa: E402 | |
| from miner_lib.sigma_zero_attack import run_sigma_zero_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_sigma") | |
| RANK1_AVG = 0.9616 | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="A/B: pipeline vs sigma-zero on random ImageNet-100 rows") | |
| parser.add_argument("--start", type=int, default=120000) | |
| parser.add_argument("--n", type=int, default=20) | |
| parser.add_argument("--budget", type=float, default=18.0) | |
| add_attack_args(parser) | |
| args = parser.parse_args() | |
| cfg = attack_config_from_args(args) | |
| device = resolve_device(cfg.device if args.attack_device == "auto" else args.attack_device) | |
| logger.info("device=%s budget=%.1fs rows=%d..%d", device, args.budget, args.start, args.start + args.n) | |
| victim = VictimModel(device=device) | |
| device = victim.device | |
| dataset = load_imagenet100(split="train") | |
| rows = [] | |
| 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()) | |
| base_cfg = AttackConfig( | |
| mode="auto", device=str(device), time_budget_seconds=args.budget, | |
| apgd_iterations=int(cfg.apgd_iterations), | |
| ) | |
| t0 = time.time() | |
| outcome = run_attack(x_clean=x_clean, cfg=base_cfg, net=victim.net, device=device, task_id=f"in100-{i}") | |
| base_score = outcome.validator_score if outcome.flipped else -1.0 | |
| base_margin = outcome.margin | |
| base_rmse = outcome.rmse | |
| sz_cfg = AttackConfig(device=str(device), time_budget_seconds=args.budget, | |
| sz_steps=180) | |
| sz = run_sigma_zero_attack(victim, x_clean, true_index, sz_cfg, deadline=t0 + args.budget) | |
| sz_score = sz.score if sz.flipped else -1.0 | |
| sz_rmse = sz.rmse if sz.flipped else 1.0 | |
| sz_margin = sz.margin if sz.flipped else -99.0 | |
| portfolio = max(base_score, sz_score) | |
| rows.append((i, base_score, base_margin, base_rmse, sz_score, sz_rmse, sz_margin, portfolio)) | |
| logger.info( | |
| "[in100-%d] base=%.4f(m=%.2f,rmse=%.6f) sigma=%.4f(m=%.2f,rmse=%.6f) portfolio=%.4f", | |
| i, base_score, base_margin, base_rmse, sz_score, sz_margin, sz_rmse, portfolio, | |
| ) | |
| base_scores = [r[1] for r in rows] | |
| sz_scores = [r[4] for r in rows] | |
| port_scores = [r[7] for r in rows] | |
| print() | |
| print(f"{'idx':<8}{'base':<9}{'b_m':<7}{'b_rmse':<10}{'sigma':<9}{'s_m':<7}{'s_rmse':<10}{'port':<9}") | |
| for r in rows: | |
| print(f"{r[0]:<8}{r[1]:<9.4f}{r[2]:<7.2f}{r[3]:<10.6f}{r[4]:<9.4f}{r[6]:<7.2f}{r[5]:<10.6f}{r[7]:<9.4f}") | |
| print() | |
| print(f"base mean={sum(base_scores)/len(base_scores):.4f} min={min(base_scores):.4f}") | |
| print(f"sigma-zero mean={sum(sz_scores)/len(sz_scores):.4f} min={min(sz_scores):.4f} flips={sum(1 for s in sz_scores if s>0)}/{len(sz_scores)}") | |
| print(f"portfolio mean={sum(port_scores)/len(port_scores):.4f} min={min(port_scores):.4f}") | |
| print(f"sigma beats base on {sum(1 for r in rows if r[4] > r[1])}/{len(rows)} images") | |
| print(f"portfolio > base on {sum(1 for r in rows if r[7] > r[1] + 1e-4)}/{len(rows)} images") | |
| print(f"rank1_today={RANK1_AVG}") | |
| def _pil_b64(image) -> str: | |
| import base64 | |
| import io | |
| buf = io.BytesIO() | |
| image.convert("RGB").save(buf, format="PNG") | |
| return base64.b64encode(buf.getvalue()).decode("utf-8") | |
| if __name__ == "__main__": | |
| main() | |