Download code/scripts/data/build_training_splits.py from Shining31/WildGen: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/data/build_training_splits.py
- Command line
-
hf download hf://datasets/Shining31/WildGen/code/scripts/data/build_training_splits.py
-
curl -L -o build_training_splits.py https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/data/build_training_splits.py
12.4 kB
| #!/usr/bin/env python3 | |
| 'Build seeded binary and source-classification training subsets from fixed image pools.' | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import sys | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Any | |
| PROJECT_ROOT = Path(__file__).resolve().parents[2] | |
| DEFAULT_SPLIT_DIR = PROJECT_ROOT / "artifacts" / "metadata" / "fixed_split" | |
| DEFAULT_OUTPUT_DIR = PROJECT_ROOT / "artifacts" / "metadata" / "training" | |
| DEFAULT_N_GRID = [900, 90, 45, 18] | |
| csv.field_size_limit(min(sys.maxsize, 2_147_483_647)) | |
| def stable_rank(seed: int, group_key: str, sample_id: str) -> int: | |
| key = f"{seed}:{group_key}:{sample_id}".encode("utf-8") | |
| return int(hashlib.sha256(key).hexdigest(), 16) | |
| def read_csv(path: Path) -> list[dict[str, str]]: | |
| with path.open("r", newline="", encoding="utf-8") as f: | |
| return list(csv.DictReader(f)) | |
| def write_json(path: Path, data: Any) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", encoding="utf-8") as f: | |
| json.dump(data, f, indent=2, ensure_ascii=False) | |
| def parse_n_grid(value: str) -> list[int]: | |
| n_grid = [int(part.strip()) for part in value.split(",") if part.strip()] | |
| if not n_grid: | |
| raise ValueError("N grid cannot be empty") | |
| return sorted(n_grid, reverse=True) | |
| def group_ai(rows: list[dict[str, str]]) -> dict[str, list[dict[str, str]]]: | |
| grouped: dict[str, list[dict[str, str]]] = defaultdict(list) | |
| for row in rows: | |
| grouped[row["source_model_id"]].append(row) | |
| return grouped | |
| def group_real_sources(rows: list[dict[str, str]]) -> dict[str, list[dict[str, str]]]: | |
| grouped: dict[str, list[dict[str, str]]] = defaultdict(list) | |
| for row in rows: | |
| grouped[row["real_source_id"]].append(row) | |
| return grouped | |
| def ranked_rows(rows: list[dict[str, str]], seed: int, group: str) -> list[dict[str, str]]: | |
| """Independent seeded training ranks; validation order is seed-independent.""" | |
| if "train" in group: | |
| return sorted(rows, key=lambda row: (stable_rank(seed, group, row["sample_id"]), row["sample_id"])) | |
| return sorted(rows, key=lambda row: (int(row.get("split_rank") or 0), row["sample_id"])) | |
| def select_real_rows( | |
| rows: list[dict[str, str]], | |
| total: int, | |
| seed: int, | |
| ) -> list[dict[str, str]]: | |
| ranked = sorted( | |
| rows, | |
| key=lambda row: ( | |
| stable_rank(seed, f"real_train:{row.get('source_dataset', 'unknown')}", row["sample_id"]), | |
| row["sample_id"], | |
| ), | |
| ) | |
| if total > len(ranked): | |
| raise RuntimeError(f"Requested {total} real rows, but only {len(ranked)} are available") | |
| return ranked[:total] | |
| def real_source_counts(total: int, source_ids: list[str]) -> dict[str, int]: | |
| base_count = total // len(source_ids) | |
| remainder = total % len(source_ids) | |
| return { | |
| source_id: base_count + (1 if i < remainder else 0) | |
| for i, source_id in enumerate(source_ids) | |
| } | |
| def to_path_list(rows: list[dict[str, str]]) -> list[str]: | |
| return [row["image_path"] for row in rows] | |
| def build_split( | |
| ai_train_rows: list[dict[str, str]], | |
| ai_val_rows: list[dict[str, str]], | |
| real_train_rows: list[dict[str, str]], | |
| real_val_rows: list[dict[str, str]], | |
| n_grid: list[int], | |
| real_ratio: float, | |
| seed: int, | |
| ) -> tuple[dict[str, dict[str, list[str]]], dict[str, Any]]: | |
| max_n = max(n_grid) | |
| ai_train_by_model = group_ai(ai_train_rows) | |
| ai_val_by_model = group_ai(ai_val_rows) | |
| train: dict[str, list[str]] = {} | |
| test: dict[str, list[str]] = {} | |
| model_summaries: list[dict[str, Any]] = [] | |
| for model_id in sorted(ai_train_by_model, key=lambda x: int(x)): | |
| ranked_train = ranked_rows(ai_train_by_model[model_id], seed, f"ai_train:{model_id}") | |
| ranked_val = ranked_rows(ai_val_by_model.get(model_id, []), seed, f"ai_val:{model_id}") | |
| if len(ranked_train) < max_n: | |
| raise RuntimeError(f"Model {model_id} has {len(ranked_train)} train rows, expected at least {max_n}") | |
| train[model_id] = to_path_list(ranked_train[:max_n]) | |
| test[model_id] = to_path_list(ranked_val) | |
| model_summaries.append( | |
| { | |
| "source_model_id": int(model_id), | |
| "train_images": len(train[model_id]), | |
| "validation_images": len(test[model_id]), | |
| } | |
| ) | |
| max_real_train = int(real_ratio * max_n * len(model_summaries)) | |
| selected_real_train = select_real_rows(real_train_rows, max_real_train, seed) | |
| train["0"] = to_path_list(selected_real_train) | |
| test["0"] = to_path_list(real_val_rows) | |
| split = {"train": train, "test": test, "protocol": {"seed": seed, "version": "release-v1-resampled", "checkpoint": "final"}} | |
| summary = { | |
| "seed": seed, | |
| "n_grid": n_grid, | |
| "max_n": max_n, | |
| "real_ratio": real_ratio, | |
| "ai_model_count": len(model_summaries), | |
| "ai_train_images_at_max_n": max_n * len(model_summaries), | |
| "real_train_images_at_max_n": max_real_train, | |
| "ai_validation_images": sum(len(v) for k, v in test.items() if k != "0"), | |
| "real_validation_images": len(test["0"]), | |
| "models": model_summaries, | |
| "per_n": [ | |
| { | |
| "n": n, | |
| "ai_train_images": n * len(model_summaries), | |
| "real_train_images": int(real_ratio * n * len(model_summaries)), | |
| "total_train_images": n * len(model_summaries) + int(real_ratio * n * len(model_summaries)), | |
| } | |
| for n in n_grid | |
| ], | |
| } | |
| return split, summary | |
| def build_source_multiclass_split( | |
| ai_train_rows: list[dict[str, str]], | |
| ai_val_rows: list[dict[str, str]], | |
| real_train_rows: list[dict[str, str]], | |
| real_val_rows: list[dict[str, str]], | |
| n_grid: list[int], | |
| real_ratio: float, | |
| seed: int, | |
| ) -> tuple[dict[str, dict[str, list[str]]], dict[str, Any]]: | |
| max_n = max(n_grid) | |
| ai_train_by_model = group_ai(ai_train_rows) | |
| ai_val_by_model = group_ai(ai_val_rows) | |
| real_train_by_source = group_real_sources(real_train_rows) | |
| real_val_by_source = group_real_sources(real_val_rows) | |
| train: dict[str, list[str]] = {} | |
| test: dict[str, list[str]] = {} | |
| model_summaries: list[dict[str, Any]] = [] | |
| for model_id in sorted(ai_train_by_model, key=lambda x: int(x)): | |
| ranked_train = ranked_rows(ai_train_by_model[model_id], seed, f"ai_train:{model_id}") | |
| ranked_val = ranked_rows(ai_val_by_model.get(model_id, []), seed, f"ai_val:{model_id}") | |
| if len(ranked_train) < max_n: | |
| raise RuntimeError(f"Model {model_id} has {len(ranked_train)} train rows, expected at least {max_n}") | |
| train[model_id] = to_path_list(ranked_train[:max_n]) | |
| test[model_id] = to_path_list(ranked_val) | |
| model_summaries.append( | |
| { | |
| "source_model_id": int(model_id), | |
| "train_images": len(train[model_id]), | |
| "validation_images": len(test[model_id]), | |
| } | |
| ) | |
| real_source_ids = sorted(real_train_by_source, key=lambda x: int(x)) | |
| max_real_train = int(real_ratio * max_n * len(model_summaries)) | |
| per_source_max_counts = real_source_counts(max_real_train, real_source_ids) | |
| real_source_summaries: list[dict[str, Any]] = [] | |
| for source_id in real_source_ids: | |
| ranked_train = ranked_rows( | |
| real_train_by_source[source_id], | |
| seed, | |
| f"real_train_source:{source_id}", | |
| ) | |
| limit = per_source_max_counts[source_id] | |
| if len(ranked_train) < limit: | |
| raise RuntimeError( | |
| f"Real source {source_id} has {len(ranked_train)} train rows, expected at least {limit}" | |
| ) | |
| train[source_id] = to_path_list(ranked_train[:limit]) | |
| test[source_id] = to_path_list( | |
| ranked_rows(real_val_by_source.get(source_id, []), seed, f"real_val_source:{source_id}") | |
| ) | |
| real_source_summaries.append( | |
| { | |
| "real_source_id": int(source_id), | |
| "train_images": len(train[source_id]), | |
| "validation_images": len(test[source_id]), | |
| } | |
| ) | |
| split = {"train": train, "test": test, "protocol": {"seed": seed, "version": "release-v1-resampled", "checkpoint": "final"}} | |
| summary = { | |
| "seed": seed, | |
| "n_grid": n_grid, | |
| "max_n": max_n, | |
| "real_ratio": real_ratio, | |
| "ai_model_count": len(model_summaries), | |
| "real_source_count": len(real_source_summaries), | |
| "source_class_count": len(model_summaries) + len(real_source_summaries), | |
| "ai_train_images_at_max_n": max_n * len(model_summaries), | |
| "real_train_images_at_max_n": max_real_train, | |
| "ai_validation_images": sum(len(v) for k, v in test.items() if int(k) > 0), | |
| "real_validation_images": sum(len(v) for k, v in test.items() if int(k) < 0), | |
| "models": model_summaries, | |
| "real_sources": real_source_summaries, | |
| "per_n": [ | |
| { | |
| "n": n, | |
| "ai_train_images": n * len(model_summaries), | |
| "real_train_images": int(real_ratio * n * len(model_summaries)), | |
| "total_train_images": n * len(model_summaries) + int(real_ratio * n * len(model_summaries)), | |
| } | |
| for n in n_grid | |
| ], | |
| } | |
| return split, summary | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="Build WildGen training split configs.") | |
| parser.add_argument("--ai-train", type=Path, default=DEFAULT_SPLIT_DIR / "ai_train_pool.csv") | |
| parser.add_argument("--ai-val", type=Path, default=DEFAULT_SPLIT_DIR / "ai_validation.csv") | |
| parser.add_argument("--real-train", type=Path, default=DEFAULT_SPLIT_DIR / "real_train_pool.csv") | |
| parser.add_argument("--real-val", type=Path, default=DEFAULT_SPLIT_DIR / "real_validation.csv") | |
| parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR / "splits") | |
| parser.add_argument("--n-grid", type=str, default=",".join(str(n) for n in DEFAULT_N_GRID)) | |
| parser.add_argument("--real-ratio", type=float, default=0.1) | |
| parser.add_argument("--seed", type=int, default=42) | |
| args = parser.parse_args() | |
| n_grid = parse_n_grid(args.n_grid) | |
| ai_train_rows = read_csv(args.ai_train) | |
| ai_val_rows = read_csv(args.ai_val) | |
| real_train_rows = read_csv(args.real_train) | |
| real_val_rows = read_csv(args.real_val) | |
| split, summary = build_split( | |
| ai_train_rows, | |
| ai_val_rows, | |
| real_train_rows, | |
| real_val_rows, | |
| n_grid=n_grid, | |
| real_ratio=args.real_ratio, | |
| seed=args.seed, | |
| ) | |
| source_split, source_summary = build_source_multiclass_split( | |
| ai_train_rows, | |
| ai_val_rows, | |
| real_train_rows, | |
| real_val_rows, | |
| n_grid=n_grid, | |
| real_ratio=args.real_ratio, | |
| seed=args.seed, | |
| ) | |
| ratio_tag = str(args.real_ratio).replace(".", "p") | |
| split_path = args.output_dir / f"training_split_n{max(n_grid)}_realratio_{ratio_tag}_seed{args.seed}.json" | |
| summary_path = args.output_dir / f"training_split_n{max(n_grid)}_realratio_{ratio_tag}_seed{args.seed}_summary.json" | |
| source_split_path = args.output_dir / f"source_split_n{max(n_grid)}_realratio_{ratio_tag}_seed{args.seed}.json" | |
| source_summary_path = args.output_dir / f"source_split_n{max(n_grid)}_realratio_{ratio_tag}_seed{args.seed}_summary.json" | |
| write_json(split_path, split) | |
| summary["split_file"] = str(split_path) | |
| write_json(summary_path, summary) | |
| write_json(source_split_path, source_split) | |
| source_summary["split_file"] = str(source_split_path) | |
| write_json(source_summary_path, source_summary) | |
| print(json.dumps({ | |
| "binary_split_file": str(split_path), | |
| "binary_summary_file": str(summary_path), | |
| "source_split_file": str(source_split_path), | |
| "source_summary_file": str(source_summary_path), | |
| "binary": summary, | |
| "source_multiclass": source_summary, | |
| }, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |