File size: 12,439 Bytes
f9ed2b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()