File size: 16,858 Bytes
f789875 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | """Large-scale resumable benchmark for Perturb attack versions.
Samples N random ImageNet-100 rows, runs the chosen attack on each image,
saves the clean/adversarial PNGs, and records per-image validator scores.
Designed for 2000-image backtests with crash/resume support.
Usage:
python scripts/benchmark_2000.py --n 2000 --attack v15 --output-dir benchmark_2000
python scripts/benchmark_2000.py --n 2000 --attack v15 --offline --offline-budget 60
python scripts/benchmark_2000.py --n 2000 --attack v15 --resume # skip existing outputs
"""
from __future__ import annotations
import argparse
import base64
import io
import json
import os
import random
import sys
import time
from pathlib import Path
from types import SimpleNamespace
from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import numpy as np
import torch
from PIL import Image
from perturbnet import constants as C
from perturbnet.attacks import ATTACKS
from perturbnet.image_io import decode_image_b64, encode_image_b64
from perturbnet.imagenet100_bootstrap import load_imagenet100
from perturbnet.model import load_efficientnet_v2_l, predict_label
from neurons.validator import ChallengeSpec, PerturbValidator
DEFAULT_SEED = 20260819
def build_validator_stub(*, device: torch.device, model: torch.nn.Module) -> PerturbValidator:
"""Minimal PerturbValidator that can run verify_and_score without a wallet."""
config = SimpleNamespace(
perturb=SimpleNamespace(
min_linf_delta=C.MIN_LINF_DELTA,
max_linf_delta=C.MAX_LINF_DELTA,
min_ssim=C.MIN_SSIM,
min_psnr_db=C.MIN_PSNR_DB,
linf_component_weight=C.LINF_COMPONENT_WEIGHT,
rmse_component_weight=C.RMSE_COMPONENT_WEIGHT,
analyze_bucket_margin_weight=C.ANALYZE_BUCKET_MARGIN_WEIGHT,
analyze_bucket_novelty_weight=C.ANALYZE_BUCKET_NOVELTY_WEIGHT,
analyze_bucket_novelty_target_pixels=C.ANALYZE_BUCKET_NOVELTY_TARGET_PIXELS,
)
)
stub: PerturbValidator = object.__new__(PerturbValidator)
stub.config = config
stub.device = device
stub.model = model
return stub
def pick_indices(num_rows: int, n: int, seed: int) -> list[int]:
rng = random.Random(seed)
return rng.sample(range(num_rows), min(n, num_rows))
def tensor_to_pil(image_chw: torch.Tensor) -> Image.Image:
"""Convert a float CHW tensor in [0,1] to a PIL RGB image."""
arr = (image_chw.detach().clamp(0, 1).cpu().numpy() * 255).astype(np.uint8)
arr = np.transpose(arr, (1, 2, 0))
return Image.fromarray(arr, mode="RGB")
def save_tensor_png(path: Path, image_chw: torch.Tensor) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tensor_to_pil(image_chw).save(path, format="PNG")
def load_clean_b64_and_label(dataset: Any, ds_idx: int, device: torch.device, model: torch.nn.Module) -> tuple[str, str]:
"""Return base64 JPEG of the clean image and its model-predicted label."""
example = dataset[ds_idx]
buffer = io.BytesIO()
example["image"].convert("RGB").save(buffer, format="JPEG", quality=95)
clean_b64 = base64.b64encode(buffer.getvalue()).decode("utf-8")
clean = decode_image_b64(clean_b64).to(device)
true_label = predict_label(model=model, image_chw=clean)
return clean_b64, true_label
def score_image(
stub: PerturbValidator,
*,
clean_b64: str,
adv_b64: str,
true_label: str,
ds_idx: int,
) -> Any:
"""Run the real validator scoring logic on an adversarial image."""
challenge = ChallengeSpec(
task_id=f"bench-{ds_idx:07d}",
image_id=str(ds_idx),
model_name=C.MODEL_NAME,
clean_image_b64=clean_b64,
true_label=true_label,
epsilon=C.MAX_LINF_DELTA,
norm_type="Linf",
)
return PerturbValidator.verify_and_score(stub, challenge=challenge, perturbed_image_b64=adv_b64)
def run_attack_and_record(
*,
ds_idx: int,
clean_b64: str,
true_label: str,
attack_fn: Any,
time_budget: float,
model: torch.nn.Module,
device: torch.device,
stub: PerturbValidator,
out_dir: Path,
save_clean: bool = True,
prefix: str = "",
attempt: int | None = None,
) -> dict:
"""Run one attack on one image, save images + score JSON, return record."""
clean = decode_image_b64(clean_b64).to(device)
suffix = f"_attempt{attempt}" if attempt is not None else ""
clean_path: Path | None = None
if save_clean:
clean_path = out_dir / f"{prefix}{ds_idx:07d}_clean.png"
if not clean_path.exists():
save_tensor_png(clean_path, clean)
started = time.time()
adv, info = attack_fn(model, clean, device, time_budget=time_budget)
elapsed = time.time() - started
adv_path = out_dir / f"{prefix}{ds_idx:07d}{suffix}_adv.png"
save_tensor_png(adv_path, adv)
adv_b64 = encode_image_b64(adv)
result = score_image(stub, clean_b64=clean_b64, adv_b64=adv_b64, true_label=true_label, ds_idx=ds_idx)
record: dict[str, Any] = {
"ds_idx": ds_idx,
"true_label": true_label,
"score": result.score,
"reason": result.reason,
"prediction": result.model_prediction,
"norm": result.norm,
"rmse": result.rmse,
"ssim": result.ssim,
"psnr_db": result.psnr_db,
"margin": result.margin,
"time": elapsed,
"attempt": attempt if attempt is not None else 0,
"clean_path": str(clean_path) if save_clean else None,
"adv_path": str(adv_path),
}
# Merge attack metadata, but avoid overwriting reserved keys.
for k, v in info.items():
if k not in record and k != "true_idx":
record[k] = v
json_path = out_dir / f"{prefix}{ds_idx:07d}{suffix}.json"
json_path.write_text(json.dumps(record, indent=2, default=str))
return record
def summarize(records: list[dict]) -> dict:
n = len(records)
succ = [r for r in records if r["reason"] == "success"]
scores = [r["score"] for r in records]
mean_score = sum(scores) / n if n else 0.0
return {
"n": n,
"success_rate": len(succ) / n if n else 0.0,
"avg_score": mean_score,
"score_std": (sum((s - mean_score) ** 2 for s in scores) / n) ** 0.5 if n else 0.0,
"min_score": min(scores, default=0.0),
"max_score": max(scores, default=0.0),
"p50_score": float(np.median(scores)) if scores else 0.0,
"p95_score": float(np.percentile(scores, 95)) if scores else 0.0,
"avg_norm_succ": sum(r["norm"] for r in succ) / len(succ) if succ else 0.0,
"avg_rmse_succ": sum(r["rmse"] for r in succ) / len(succ) if succ else 0.0,
"min_ssim_succ": min((r["ssim"] for r in succ), default=0.0),
"avg_margin_succ": sum(r["margin"] for r in succ) / len(succ) if succ else 0.0,
"margin_p05": float(np.percentile([r["margin"] for r in succ], 5)) if succ else 0.0,
"margin_p50": float(np.percentile([r["margin"] for r in succ], 50)) if succ else 0.0,
"avg_time": sum(r["time"] for r in records) / n if n else 0.0,
"p95_time": float(np.percentile([r["time"] for r in records], 95)) if records else 0.0,
"max_time": max((r["time"] for r in records), default=0.0),
"fail_reasons": {
reason: sum(1 for r in records if r["reason"] == reason)
for reason in {r["reason"] for r in records if r["reason"] != "success"}
},
}
def run_online_benchmark(
*,
indices: list[int],
attack_name: str,
time_budget: float,
output_dir: Path,
device: torch.device,
force: bool = False,
worker_id: int = 0,
workers: int = 1,
all_indices: list[int] | None = None,
) -> dict:
"""Run the online attack on every sampled row, saving images and scores."""
dataset = load_imagenet100()
model = load_efficientnet_v2_l(device=device)
stub = build_validator_stub(device=device, model=model)
attack = ATTACKS[attack_name]
online_dir = output_dir / attack_name
online_dir.mkdir(parents=True, exist_ok=True)
indices_path = output_dir / "indices.json"
if worker_id == 0 and (not indices_path.exists() or force):
# Persist the full sampled list so other workers and post-processing can see it.
full = all_indices if all_indices is not None else indices
indices_path.write_text(json.dumps({"seed": DEFAULT_SEED, "n": len(full), "indices": full}, indent=2))
records: list[dict] = []
prefix = f"[w{worker_id}] "
for i, ds_idx in enumerate(indices):
json_path = online_dir / f"{ds_idx:07d}.json"
if json_path.exists() and not force:
record = json.loads(json_path.read_text())
records.append(record)
print(f"{prefix}[{i + 1:04d}/{len(indices)}] idx={ds_idx} score={record['score']:.4f} (cached)")
continue
clean_b64, true_label = load_clean_b64_and_label(dataset, ds_idx, device, model)
record = run_attack_and_record(
ds_idx=ds_idx,
clean_b64=clean_b64,
true_label=true_label,
attack_fn=attack,
time_budget=time_budget,
model=model,
device=device,
stub=stub,
out_dir=online_dir,
save_clean=True,
)
records.append(record)
print(
f"{prefix}[{i + 1:04d}/{len(indices)}] idx={ds_idx} score={record['score']:.4f} "
f"reason={record['reason']} norm={record['norm']:.5f} rmse={record['rmse']:.5f} "
f"ssim={record['ssim']:.4f} margin={record['margin']:.2f} time={record['time']:.1f}s "
f"path={record.get('attack', 'n/a')}"
)
summary = summarize(records)
summary.update({"attack": attack_name, "budget": time_budget, "mode": "online", "worker_id": worker_id, "workers": workers})
summary_name = "summary.json" if workers == 1 else f"summary_worker{worker_id}.json"
summary_path = online_dir / summary_name
summary_path.write_text(json.dumps(summary, indent=2))
return summary
def run_offline_benchmark(
*,
indices: list[int],
attack_name: str,
time_budget: float,
retries: int,
output_dir: Path,
device: torch.device,
force: bool = False,
) -> dict:
"""Run a stronger offline attack with retries on the same rows, keeping the best score."""
dataset = load_imagenet100()
model = load_efficientnet_v2_l(device=device)
stub = build_validator_stub(device=device, model=model)
attack = ATTACKS[attack_name]
offline_dir = output_dir / "offline"
offline_dir.mkdir(parents=True, exist_ok=True)
records: list[dict] = []
for i, ds_idx in enumerate(indices):
json_path = offline_dir / f"{ds_idx:07d}.json"
if json_path.exists() and not force:
record = json.loads(json_path.read_text())
records.append(record)
print(f"[offline {i + 1:04d}/{len(indices)}] idx={ds_idx} score={record['score']:.4f} (cached)")
continue
clean_b64, true_label = load_clean_b64_and_label(dataset, ds_idx, device, model)
best_record: dict | None = None
for attempt in range(1 + retries):
record = run_attack_and_record(
ds_idx=ds_idx,
clean_b64=clean_b64,
true_label=true_label,
attack_fn=attack,
time_budget=time_budget,
model=model,
device=device,
stub=stub,
out_dir=offline_dir,
save_clean=(attempt == 0),
attempt=attempt,
)
if best_record is None or record["score"] > best_record["score"]:
best_record = record
if record["score"] >= 0.965:
break
assert best_record is not None
best_attempt = best_record.get("attempt", 0)
# Promote the best attempt's files to the canonical names.
final_adv_path = offline_dir / f"{ds_idx:07d}_adv.png"
final_json_path = offline_dir / f"{ds_idx:07d}.json"
best_adv_path = offline_dir / f"{ds_idx:07d}_attempt{best_attempt}_adv.png"
best_json_path = offline_dir / f"{ds_idx:07d}_attempt{best_attempt}.json"
if best_adv_path.exists() and best_adv_path != final_adv_path:
if final_adv_path.exists():
final_adv_path.unlink()
os.replace(best_adv_path, final_adv_path)
if best_json_path.exists() and best_json_path != final_json_path:
if final_json_path.exists():
final_json_path.unlink()
os.replace(best_json_path, final_json_path)
best_record["attempts"] = 1 + retries
best_record["best_attempt"] = best_attempt
best_record["adv_path"] = str(final_adv_path)
final_json_path.write_text(json.dumps(best_record, indent=2, default=str))
records.append(best_record)
print(
f"[offline {i + 1:04d}/{len(indices)}] idx={ds_idx} score={best_record['score']:.4f} "
f"best_attempt={best_attempt} reason={best_record['reason']} time={best_record['time']:.1f}s"
)
summary = summarize(records)
summary.update({"attack": attack_name, "budget": time_budget, "retries": retries, "mode": "offline"})
summary_path = offline_dir / "summary.json"
summary_path.write_text(json.dumps(summary, indent=2))
return summary
def main() -> None:
parser = argparse.ArgumentParser(description="2000-image Perturb attack benchmark")
parser.add_argument("--n", type=int, default=2000, help="Number of images to sample")
parser.add_argument("--seed", type=int, default=DEFAULT_SEED, help="Random seed for sampling")
parser.add_argument("--attack", type=str, default="v15", choices=list(ATTACKS.keys()), help="Attack version")
parser.add_argument("--budget", type=float, default=25.0, help="Online attack time budget in seconds")
parser.add_argument("--output-dir", type=Path, default=Path("benchmark_2000"), help="Output directory")
parser.add_argument("--force", action="store_true", help="Overwrite existing per-image JSONs")
parser.add_argument("--offline", action="store_true", help="Also run offline precompute benchmark")
parser.add_argument("--offline-attack", type=str, default="v15", choices=list(ATTACKS.keys()), help="Offline attack version")
parser.add_argument("--offline-budget", type=float, default=60.0, help="Offline attack time budget per image")
parser.add_argument("--offline-retries", type=int, default=2, help="Extra retry attempts per image offline")
parser.add_argument("--workers", type=int, default=1, help="Number of parallel workers (multi-GPU or low-GPU-util fill)")
parser.add_argument("--worker-id", type=int, default=0, help="Worker ID for this process [0, workers)")
args = parser.parse_args()
if args.worker_id < 0 or args.worker_id >= args.workers:
raise ValueError(f"--worker-id must be in [0, {args.workers}), got {args.worker_id}")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"[info] worker={args.worker_id}/{args.workers} device={device} n={args.n} seed={args.seed} attack={args.attack}")
dataset = load_imagenet100()
total_rows = int(dataset.num_rows)
all_indices = pick_indices(total_rows, args.n, args.seed)
# Each worker takes its shard of the full sampled list.
indices = [idx for i, idx in enumerate(all_indices) if i % args.workers == args.worker_id]
print(f"[info] sampled {len(all_indices)} rows from {total_rows}; this worker handles {len(indices)}")
args.output_dir.mkdir(parents=True, exist_ok=True)
online_summary = run_online_benchmark(
indices=indices,
attack_name=args.attack,
time_budget=args.budget,
output_dir=args.output_dir,
device=device,
force=args.force,
worker_id=args.worker_id,
workers=args.workers,
all_indices=all_indices,
)
print("\n" + "=" * 64)
print(f"ONLINE SUMMARY (worker {args.worker_id}/{args.workers})")
print("=" * 64)
print(json.dumps(online_summary, indent=2))
if args.offline:
offline_summary = run_offline_benchmark(
indices=indices,
attack_name=args.offline_attack,
time_budget=args.offline_budget,
retries=args.offline_retries,
output_dir=args.output_dir,
device=device,
force=args.force,
)
print("\n" + "=" * 64)
print("OFFLINE SUMMARY")
print("=" * 64)
print(json.dumps(offline_summary, indent=2))
print(f"\n[info] outputs saved to {args.output_dir}")
if __name__ == "__main__":
main()
|