File size: 15,291 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 | """Offline ensemble for low-score images from a previous online benchmark.
Reads a list of low-score indices, runs multiple attack/budget configurations,
keeps the best-scoring adversarial PNG per image, and compares with the online
baseline.
Usage:
# Pilot on the worst 108 images (score < 0.90)
python scripts/offline_low_score_ensemble.py \
--online-dir /workspace/Perturb/benchmark_2000_v15 \
--indices-file /workspace/Perturb/benchmark_2000_v15/low_score_090_indices.json \
--workers 4
# Full run on all score < 0.95 images
python scripts/offline_low_score_ensemble.py \
--online-dir /workspace/Perturb/benchmark_2000_v15 \
--indices-file /workspace/Perturb/benchmark_2000_v15/low_score_095_indices.json \
--configs v15:60 v13:60 v15:120 \
--workers 4
"""
from __future__ import annotations
import argparse
import base64
import io
import json
import os
import subprocess
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
def build_validator_stub(*, device: torch.device, model: torch.nn.Module) -> PerturbValidator:
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 load_clean_b64_and_label(dataset: Any, ds_idx: int, device: torch.device, model: torch.nn.Module) -> tuple[str, str]:
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_adv(stub: PerturbValidator, *, clean_b64: str, adv_b64: str, true_label: str, ds_idx: int) -> Any:
challenge = ChallengeSpec(
task_id=f"offline-{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 tensor_to_pil(image_chw: torch.Tensor) -> Image.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 parse_config(s: str) -> dict:
"""Parse 'attack:budget' or 'attack:budget:retries'."""
parts = s.split(":")
if len(parts) == 2:
return {"attack": parts[0], "budget": float(parts[1]), "retries": 0}
if len(parts) == 3:
return {"attack": parts[0], "budget": float(parts[1]), "retries": int(parts[2])}
raise ValueError(f"Invalid config '{s}', expected attack:budget or attack:budget:retries")
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,
"avg_time": sum(r.get("time", r.get("total_time", 0.0)) for r in records) / n if n else 0.0,
}
def run_offline_ensemble(
*,
indices: list[int],
configs: list[dict],
output_dir: Path,
device: torch.device,
worker_id: int,
workers: int,
early_stop_score: float = 0.965,
) -> dict:
"""Run all configs for a shard of indices and keep the best per image."""
dataset = load_imagenet100()
model = load_efficientnet_v2_l(device=device)
stub = build_validator_stub(device=device, model=model)
offline_dir = output_dir / "offline_ensemble"
offline_dir.mkdir(parents=True, exist_ok=True)
records: list[dict] = []
prefix = f"[w{worker_id}] "
for i, ds_idx in enumerate(indices):
json_path = offline_dir / f"{ds_idx:07d}.json"
if json_path.exists():
record = json.loads(json_path.read_text())
records.append(record)
print(f"{prefix}[{i+1}/{len(indices)}] idx={ds_idx} (cached)")
continue
clean_b64, true_label = load_clean_b64_and_label(dataset, ds_idx, device, model)
clean = decode_image_b64(clean_b64).to(device)
best_score = -1.0
best_adv = None
best_cfg_name = None
best_result = None
attempts: list[dict] = []
for cfg in configs:
for attempt in range(1 + cfg["retries"]):
t0 = time.time()
adv, info = ATTACKS[cfg["attack"]](model, clean, device, time_budget=cfg["budget"])
elapsed = time.time() - t0
adv_b64 = encode_image_b64(adv)
result = score_adv(stub, clean_b64=clean_b64, adv_b64=adv_b64, true_label=true_label, ds_idx=ds_idx)
attempts.append({
"attack": cfg["attack"],
"budget": cfg["budget"],
"attempt": attempt,
"score": result.score,
"reason": result.reason,
"rmse": result.rmse,
"norm": result.norm,
"margin": result.margin,
"ssim": result.ssim,
"time": elapsed,
"path": info.get("attack", cfg["attack"]),
})
if result.score > best_score:
best_score = result.score
best_adv = adv
best_cfg_name = f"{cfg['attack']}@{cfg['budget']}s"
best_result = result
if result.score >= early_stop_score:
break
if best_score >= early_stop_score:
break
adv_path = offline_dir / f"{ds_idx:07d}_adv.png"
save_tensor_png(adv_path, best_adv)
record = {
"ds_idx": ds_idx,
"true_label": true_label,
"score": best_result.score,
"reason": best_result.reason,
"prediction": best_result.model_prediction,
"norm": best_result.norm,
"rmse": best_result.rmse,
"ssim": best_result.ssim,
"psnr_db": best_result.psnr_db,
"margin": best_result.margin,
"best_config": best_cfg_name,
"attempts": attempts,
"total_time": sum(a["time"] for a in attempts),
"adv_path": str(adv_path),
}
json_path.write_text(json.dumps(record, indent=2, default=str))
records.append(record)
print(
f"{prefix}[{i+1}/{len(indices)}] idx={ds_idx} best={best_result.score:.4f} "
f"config={best_cfg_name} tried={len(attempts)}"
)
summary = summarize(records)
summary.update({"worker_id": worker_id, "workers": workers, "configs": configs})
summary_path = offline_dir / f"summary_worker{worker_id}.json"
summary_path.write_text(json.dumps(summary, indent=2, default=str))
return summary
def compare_with_online(online_dir: Path, offline_dir: Path, indices: list[int]) -> dict:
online_records = {}
online_json_dir = online_dir / "v15"
for idx in indices:
path = online_json_dir / f"{idx:07d}.json"
if path.exists():
online_records[idx] = json.loads(path.read_text())
offline_records = {}
offline_json_dir = offline_dir / "offline_ensemble"
for path in offline_json_dir.glob("[0-9][0-9][0-9][0-9][0-9][0-9][0-9].json"):
rec = json.loads(path.read_text())
offline_records[rec["ds_idx"]] = rec
common = [idx for idx in indices if idx in online_records and idx in offline_records]
if not common:
return {}
online_scores = [online_records[idx]["score"] for idx in common]
offline_scores = [offline_records[idx]["score"] for idx in common]
gains = [offline_records[idx]["score"] - online_records[idx]["score"] for idx in common]
improved = sum(1 for g in gains if g > 0)
worsened = sum(1 for g in gains if g < 0)
unchanged = sum(1 for g in gains if g == 0)
return {
"n": len(common),
"online_avg": sum(online_scores) / len(common),
"offline_avg": sum(offline_scores) / len(common),
"avg_gain": sum(gains) / len(common),
"max_gain": max(gains),
"max_loss": min(gains),
"improved": improved,
"worsened": worsened,
"unchanged": unchanged,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Offline ensemble for low-score images")
parser.add_argument("--online-dir", type=Path, required=True, help="Directory with existing online benchmark")
parser.add_argument("--indices-file", type=Path, required=True, help="JSON file with list of low-score indices")
parser.add_argument("--output-dir", type=Path, default=Path("offline_ensemble_output"), help="Output directory")
parser.add_argument("--configs", type=str, nargs="+", default=["v15:60", "v13:60", "v15:120"], help="Configs like 'v15:60' or 'v15:120:2'")
parser.add_argument("--workers", type=int, default=4, help="Number of parallel workers")
parser.add_argument("--early-stop-score", type=float, default=0.965, help="Stop trying more configs if this score reached")
parser.add_argument("--indices-file-internal", type=Path, default=None, help=argparse.SUPPRESS)
args = parser.parse_args()
if args.indices_file_internal:
indices = json.loads(args.indices_file_internal.read_text())
is_top_level = False
else:
indices = json.loads(args.indices_file.read_text())
if isinstance(indices, dict):
indices = indices.get("indices", [])
is_top_level = True
configs = [parse_config(c) for c in args.configs]
print(f"[info] {'top-level' if is_top_level else 'worker'}: {len(indices)} images, configs={configs}")
args.output_dir.mkdir(parents=True, exist_ok=True)
if args.workers == 1:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
run_offline_ensemble(
indices=indices,
configs=configs,
output_dir=args.output_dir,
device=device,
worker_id=0,
workers=1,
early_stop_score=args.early_stop_score,
)
else:
log_dir = args.output_dir / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
(args.output_dir / "indices.json").write_text(
json.dumps({"n": len(indices), "indices": indices}, indent=2)
)
processes = []
for worker_id in range(args.workers):
shard = [idx for i, idx in enumerate(indices) if i % args.workers == worker_id]
if not shard:
continue
shard_file = args.output_dir / f"shard_worker{worker_id}.json"
shard_file.write_text(json.dumps(shard, indent=2))
cmd = [
sys.executable,
str(Path(__file__).resolve()),
"--online-dir", str(args.online_dir),
"--indices-file", str(args.indices_file),
"--output-dir", str(args.output_dir),
"--early-stop-score", str(args.early_stop_score),
"--workers", "1",
"--indices-file-internal", str(shard_file),
"--configs", *args.configs,
]
log_path = log_dir / f"worker{worker_id}.log"
log_file = open(log_path, "w")
proc = subprocess.Popen(cmd, stdout=log_file, stderr=subprocess.STDOUT)
processes.append(proc)
print(f"[info] worker {worker_id} PID={proc.pid} shard={len(shard)}")
for proc in processes:
proc.wait()
if is_top_level:
comparison = compare_with_online(args.online_dir, args.output_dir, indices)
if comparison:
print("\n" + "=" * 64)
print("OFFLINE vs ONLINE COMPARISON")
print("=" * 64)
print(json.dumps(comparison, indent=2))
(args.output_dir / "comparison.json").write_text(json.dumps(comparison, indent=2))
# Also show what the overall 2000-image average would be if we merged offline bests.
online_json_dir = args.online_dir / "v15"
offline_json_dir = args.output_dir / "offline_ensemble"
merged_scores = []
for path in online_json_dir.glob("[0-9][0-9][0-9][0-9][0-9][0-9][0-9].json"):
rec = json.loads(path.read_text())
idx = rec["ds_idx"]
offline_path = offline_json_dir / f"{idx:07d}.json"
if offline_path.exists():
offline_rec = json.loads(offline_path.read_text())
merged_scores.append(max(rec["score"], offline_rec["score"]))
else:
merged_scores.append(rec["score"])
if merged_scores:
original_scores = []
for path in online_json_dir.glob("[0-9][0-9][0-9][0-9][0-9][0-9][0-9].json"):
rec = json.loads(path.read_text())
original_scores.append(rec["score"])
original_avg = sum(original_scores) / len(original_scores)
merged_avg = sum(merged_scores) / len(merged_scores)
print("\n" + "=" * 64)
print("PROJECTED OVERALL 2000-IMAGE AVERAGE")
print("=" * 64)
print(f"original online avg: {original_avg:.4f}")
print(f"after offline merge: {merged_avg:.4f}")
print(f"improvement: +{merged_avg - original_avg:.4f}")
print(f"\n[info] outputs saved to {args.output_dir}")
if __name__ == "__main__":
main()
|