Datasets:
Tasks:
Image Classification
Sub-tasks:
multi-class-image-classification
Languages:
English
Size:
100K - 1M
Tags:
adversarial-robustness
common-corruptions
robustness
benchmark
transfer-attacks
vision-language-models
License:
Download scripts/build_parquet.py from legolasflagstaff/RobustGenBench: direct link, hf CLI and curl.
- Browser
- Download file 7.81 kB
-
https://huggingface.co/datasets/legolasflagstaff/RobustGenBench/resolve/main/scripts/build_parquet.py
- Command line
-
hf download hf://datasets/legolasflagstaff/RobustGenBench/scripts/build_parquet.py
-
curl -L -o build_parquet.py https://huggingface.co/datasets/legolasflagstaff/RobustGenBench/resolve/main/scripts/build_parquet.py
7.81 kB
| """ | |
| Convert the v1.0 RobustGenBench archives (.tar.zst) into the v2.0 Parquet layout. | |
| Layout: data/<dataset>/<split>-XXXXX-of-YYYYY.parquet | |
| splits: train, validation, test (clean, standardized) | |
| common (11 corruptions, severity 3) | |
| random_linf_30 (uniform noise, linf <= 30/255) | |
| <surrogate>_<norm>_<eps> (transfer attacks, AutoAttack standard) | |
| Images are copied byte-for-byte from the source PNGs (no re-encoding), so | |
| perturbations are preserved exactly. | |
| Usage: python build_parquet.py [dataset ...] | |
| """ | |
| import csv | |
| import io | |
| import json | |
| import sys | |
| import tarfile | |
| from pathlib import Path | |
| import numpy as np | |
| import zstandard as zstd | |
| from datasets import ClassLabel, Dataset, Features, Image, Value | |
| from PIL import Image as PILImage | |
| SRC = Path(__file__).parent / "src" | |
| OUT = Path(__file__).parent / "out" / "data" | |
| MAX_SHARD_BYTES = 400 * 1024**2 | |
| ROWS_PER_GROUP = 100 # small row groups keep the Dataset Viewer responsive | |
| DATASETS = ["caltech101", "fgvc-aircraft-2013b", "flowers-102", | |
| "oxford-iiit-pet", "stanford_cars", "uc-merced-land-use-dataset"] | |
| # Common corruptions: the test_common/ split of the original processed archives | |
| # (paper_code/save_final_dataset.py), i.e. the images used to evaluate the vision | |
| # models. Image i receives COMMON_CORRUPTIONS[(i // s) % 11] with s = n // 11 | |
| # (paper_code/corruptions/common.py; verified on the pixel data). | |
| COMMON_CORRUPTIONS = ["shot_noise", "impulse_noise", "defocus_blur", "motion_blur", | |
| "zoom_blur", "snow", "brightness", "contrast", | |
| "elastic_transform", "pixelate", "jpeg_compression"] | |
| # Surrogates kept in v2.0 (those reported in the paper). | |
| SURROGATES = { | |
| # folder -> (short name, checkpoint as loaded in robust_training/vision_enabled_language_models/craft_adversarial.py) | |
| "zeroshot_clip_vitb16_laion2b": ("clip_vitb16", "open_clip ViT-B-16 / laion2b_s34b_b88k"), | |
| "zeroshot_clip_vith14_laion2b": ("clip_vith14", "open_clip ViT-H-14 / laion2b_s32b_b79k"), | |
| "zeroshot_metaclip_vith14_fullcc2_5b": ("metaclip_vith14", "open_clip ViT-H-14-quickgelu / metaclip_fullcc"), | |
| "zeroshot_siglip2_so400m_patch14_384": ("siglip2_so400m", "google/siglip2-so400m-patch14-384"), | |
| "zeroshot_siglip2_base_patch16_224": ("siglip2_base", "google/siglip2-base-patch16-224"), | |
| } | |
| # threat folder -> (norm, epsilon as stored, display) | |
| THREATS = { | |
| "l1_eps75_autoattack_standard": ("l1", 75.0, "75"), | |
| "l1_eps300_autoattack_standard": ("l1", 300.0, "300"), | |
| "l2_eps2_autoattack_standard": ("l2", 2.0, "2"), | |
| "l2_eps8_autoattack_standard": ("l2", 8.0, "8"), | |
| "linf_eps4_autoattack_standard": ("linf", 4 / 255, "4"), | |
| "linf_eps8_autoattack_standard": ("linf", 8 / 255, "8"), | |
| "linf_eps30_autoattack_standard": ("linf", 30 / 255, "30"), | |
| } | |
| # SigLIP2 base is only reported at linf 30/255 in the paper. | |
| KEEP_ONLY = {"siglip2_base": {"linf_eps30_autoattack_standard"}} | |
| ORIG = Path(__file__).parent / "orig" # archives at revision 0790625f (with test_common/) | |
| def read_archive(path, split): | |
| with open(path, "rb") as f: | |
| buf = io.BytesIO(zstd.ZstdDecompressor().stream_reader(f).read()) | |
| tar = tarfile.open(fileobj=buf, mode="r:") | |
| rows = list(csv.DictReader(io.TextIOWrapper(tar.extractfile(f"{split}/labels.csv")))) | |
| return [(int(r["filename"].split(".")[0]), int(r["label"]), | |
| tar.extractfile(f"{split}/{r['filename']}").read()) for r in rows] | |
| def features(class_names): | |
| return Features({ | |
| "image": Image(), | |
| "label": ClassLabel(names=class_names), | |
| "image_id": Value("int32"), | |
| "perturbation": Value("string"), | |
| "surrogate": Value("string"), | |
| "norm": Value("string"), | |
| "epsilon": Value("float32"), | |
| "corruption": Value("string"), | |
| "is_modified": Value("bool"), | |
| }) | |
| def write_split(records, feats, out_dir, split): | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| total = sum(len(r["image"]["bytes"]) for r in records) | |
| n_shards = max(1, -(-total // MAX_SHARD_BYTES)) | |
| per = -(-len(records) // n_shards) | |
| for s in range(n_shards): | |
| chunk = records[s * per:(s + 1) * per] | |
| ds = Dataset.from_list(chunk, features=feats) | |
| ds.to_parquet(str(out_dir / f"{split}-{s:05d}-of-{n_shards:05d}.parquet"), | |
| batch_size=ROWS_PER_GROUP) | |
| return len(records), n_shards | |
| def pixels(b): | |
| return np.asarray(PILImage.open(io.BytesIO(b)).convert("RGB")) | |
| def build(dataset, only=None): | |
| class_names_map = json.loads((SRC / "class_names" / f"{dataset}.json").read_text()) | |
| class_names = [class_names_map[str(i)] for i in range(len(class_names_map))] | |
| feats = features(class_names) | |
| out_dir = OUT / dataset | |
| summary = {} | |
| clean = SRC / f"{dataset}_processed.tar.zst" | |
| clean_test = None | |
| for split, name in [("train", "train"), ("val", "validation"), ("test", "test")]: | |
| items = read_archive(clean, split) | |
| if split == "test": | |
| clean_test = {i: (lab, pixels(b)) for i, lab, b in items} | |
| recs = [dict(image={"bytes": b, "path": f"{i:05d}.png"}, label=lab, image_id=i, | |
| perturbation="clean", surrogate=None, norm=None, epsilon=None, | |
| corruption=None, is_modified=False) for i, lab, b in items] | |
| summary[name] = write_split(recs, feats, out_dir, name) | |
| def perturbed(path, split_name, perturbation, surrogate, norm, eps, corr_fn=None, | |
| split="test"): | |
| items = read_archive(path, split) | |
| assert len(items) == len(clean_test), (path, len(items)) | |
| recs = [] | |
| for i, lab, b in items: | |
| clab, cpix = clean_test[i] | |
| assert lab == clab, f"label mismatch {path} image {i}" | |
| recs.append(dict(image={"bytes": b, "path": f"{i:05d}.png"}, label=lab, image_id=i, | |
| perturbation=perturbation, surrogate=surrogate, norm=norm, | |
| epsilon=eps, corruption=corr_fn(i) if corr_fn else None, | |
| is_modified=bool((pixels(b) != cpix).any()))) | |
| summary[split_name] = write_split(recs, feats, out_dir, split_name) | |
| adv = SRC / "adversarial" | |
| step = max(1, len(clean_test) // len(COMMON_CORRUPTIONS)) | |
| perturbed(ORIG / f"{dataset}_processed.tar.zst", "common", "common_corruption_severity3", | |
| None, None, None, split="test_common", | |
| corr_fn=lambda i: COMMON_CORRUPTIONS[(i // step) % len(COMMON_CORRUPTIONS)]) | |
| perturbed(adv / f"random/linf_eps30_random_uniform/{dataset}__random__linf_eps30_random_uniform_processed.tar.zst", | |
| "random_linf_30", "random_uniform", None, "linf", 30 / 255) | |
| for folder, (short, _hf_id) in SURROGATES.items(): | |
| for threat, (norm, eps, disp) in THREATS.items(): | |
| if short in KEEP_ONLY and threat not in KEEP_ONLY[short]: | |
| continue | |
| files = list((adv / folder / threat).glob(f"{dataset}__*.tar.zst")) | |
| if not files: | |
| continue | |
| assert len(files) == 1, files | |
| perturbed(files[0], f"{short}_{norm}_{disp}", "transfer_autoattack", | |
| short, norm, float(eps)) | |
| (out_dir.parent.parent / "manifests").mkdir(parents=True, exist_ok=True) | |
| (out_dir.parent.parent / "manifests" / f"{dataset}.json").write_text(json.dumps( | |
| {"num_classes": len(class_names), "class_names": class_names, | |
| "splits": {k: {"num_rows": v[0], "num_shards": v[1]} for k, v in summary.items()}}, | |
| indent=1)) | |
| print(dataset, {k: v[0] for k, v in summary.items()}) | |
| if __name__ == "__main__": | |
| for d in sys.argv[1:] or DATASETS: | |
| build(d) | |