File size: 11,082 Bytes
39dbe99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import argparse
import json
import os
import sys
import time
from pathlib import Path

import numpy as np
import torch
import torch.distributed as dist
import torch.nn.functional as F
from PIL import Image, ImageFile
from sklearn.metrics import roc_auc_score
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models import create_model
from torchvision import transforms

ImageFile.LOAD_TRUNCATED_IMAGES = True

IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
BENCHMARKS = [
    ("DeepFakeDetection", "DeepFakeDetection"),
    ("CDFv2", "CDFv2"),
    ("Wild_Deepfake", "Wild_Deepfake"),
    ("ForgeryNet", "ForgeryNet"),
    ("DeepFakeFace", "DeepFakeFace"),
    ("DF40", "DF40"),
    ("ScaleDF", "ScaleDF"),
]


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--benchmark-root", required=True)
    parser.add_argument("--checkpoint", required=True)
    parser.add_argument("--output-dir", required=True)
    parser.add_argument("--manifest", default="")
    parser.add_argument("--code-root", default="/tmp/ScaleDF_repro_20260724/code/deit")
    parser.add_argument("--model", default="deit_huge_patch14_LS")
    parser.add_argument("--input-size", type=int, default=224)
    parser.add_argument("--batch-size", type=int, default=256)
    parser.add_argument("--num-workers", type=int, default=8)
    parser.add_argument("--print-freq", type=int, default=50)
    parser.add_argument("--max-samples-per-class", type=int, default=0)
    parser.add_argument("--rebuild-manifest", action="store_true")
    parser.add_argument("--skip-load-errors", action="store_true")
    return parser.parse_args()


def init_distributed():
    if "RANK" not in os.environ:
        return 0, 1, 0, torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    rank = int(os.environ["RANK"])
    world_size = int(os.environ["WORLD_SIZE"])
    local_rank = int(os.environ.get("LOCAL_RANK", "0"))
    torch.cuda.set_device(local_rank)
    dist.init_process_group("nccl", init_method="env://")
    return rank, world_size, local_rank, torch.device(f"cuda:{local_rank}")


def is_main(rank):
    return rank == 0


def iter_images(root):
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames.sort()
        for name in sorted(filenames):
            if Path(name).suffix.lower() in IMAGE_EXTS:
                yield os.path.join(dirpath, name)


def build_manifest(args, manifest_path):
    root = Path(args.benchmark_root)
    tmp_path = manifest_path.with_suffix(manifest_path.suffix + ".tmp")
    stats = []
    with tmp_path.open("w") as f:
        for bench_id, (bench_name, rel_name) in enumerate(BENCHMARKS):
            val_root = root / rel_name / "val"
            real_dir = val_root / "000real_faces"
            fake_dir = val_root / "fake"
            counts = {"real": 0, "fake": 0}
            for label, label_name, label_dir in [(0, "real", real_dir), (1, "fake", fake_dir)]:
                if not label_dir.exists():
                    raise FileNotFoundError(f"Missing {label_name} directory for {bench_name}: {label_dir}")
                for path in iter_images(label_dir):
                    f.write(f"{bench_id}\t{label}\t{path}\n")
                    counts[label_name] += 1
                    if args.max_samples_per_class and counts[label_name] >= args.max_samples_per_class:
                        break
            stats.append({
                "benchmark": bench_name,
                "real": counts["real"],
                "fake": counts["fake"],
                "total": counts["real"] + counts["fake"],
            })
    os.replace(tmp_path, manifest_path)
    with manifest_path.with_suffix(".stats.json").open("w") as f:
        json.dump({"benchmarks": stats, "total": sum(x["total"] for x in stats)}, f, indent=2)


class ManifestShardDataset(torch.utils.data.Dataset):
    def __init__(self, manifest_path, rank, world_size, transform, input_size, skip_load_errors):
        self.transform = transform
        self.input_size = input_size
        self.skip_load_errors = skip_load_errors
        self.samples = []
        with open(manifest_path, "r") as f:
            for idx, line in enumerate(f):
                if idx % world_size != rank:
                    continue
                bench_id, label, path = line.rstrip("\n").split("\t", 2)
                self.samples.append((path, int(label), int(bench_id)))

    def __len__(self):
        return len(self.samples)

    def __getitem__(self, index):
        path, label, bench_id = self.samples[index]
        try:
            with Image.open(path) as img:
                image = img.convert("RGB")
                image = self.transform(image)
        except Exception as exc:
            print(f"LOAD_ERROR\t{path}\t{type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
            if not self.skip_load_errors:
                raise
            image = torch.zeros(3, self.input_size, self.input_size)
        return image, label, bench_id


def build_transform(input_size):
    return transforms.Compose([
        transforms.Resize(input_size, interpolation=transforms.InterpolationMode.BICUBIC),
        transforms.CenterCrop(input_size),
        transforms.ToTensor(),
        transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD),
    ])


def load_model(args, device):
    sys.path.insert(0, args.code_root)
    import models  # noqa: F401
    import models_v2  # noqa: F401

    model = create_model(
        args.model,
        pretrained=False,
        num_classes=2,
        drop_rate=0.0,
        drop_path_rate=0.2,
        drop_block_rate=None,
        img_size=args.input_size,
    )
    checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
    state = checkpoint["model"] if isinstance(checkpoint, dict) and "model" in checkpoint else checkpoint
    missing, unexpected = model.load_state_dict(state, strict=False)
    if len(missing) > 10 or len(unexpected) > 10:
        raise RuntimeError(f"Too many load_state_dict mismatches: missing={len(missing)} unexpected={len(unexpected)}")
    model.to(device).eval()
    return model, {"missing": missing, "unexpected": unexpected}


@torch.no_grad()
def run_inference(args, rank, world_size, device, manifest_path, output_dir):
    dataset = ManifestShardDataset(
        manifest_path,
        rank,
        world_size,
        build_transform(args.input_size),
        args.input_size,
        args.skip_load_errors,
    )
    loader = torch.utils.data.DataLoader(
        dataset,
        batch_size=args.batch_size,
        shuffle=False,
        num_workers=args.num_workers,
        pin_memory=True,
        persistent_workers=args.num_workers > 0,
        prefetch_factor=4 if args.num_workers > 0 else None,
    )
    model, load_info = load_model(args, device)
    scores, labels, benches = [], [], []
    start = time.time()
    seen = 0
    for step, (images, y, b) in enumerate(loader):
        images = images.to(device, non_blocking=True)
        with torch.cuda.amp.autocast(enabled=device.type == "cuda"):
            logits = model(images)
            score = F.softmax(logits.float(), dim=1)[:, 1]
        scores.append(score.detach().cpu().numpy().astype(np.float32))
        labels.append(y.numpy().astype(np.uint8))
        benches.append(b.numpy().astype(np.uint8))
        seen += len(y)
        if args.print_freq and step % args.print_freq == 0:
            elapsed = max(time.time() - start, 1e-6)
            print(
                f"rank={rank} step={step} seen={seen}/{len(dataset)} "
                f"rate={seen / elapsed:.1f} img/s",
                flush=True,
            )
    shard_path = output_dir / f"shard_rank{rank:05d}.npz"
    np.savez_compressed(
        shard_path,
        scores=np.concatenate(scores) if scores else np.empty((0,), dtype=np.float32),
        labels=np.concatenate(labels) if labels else np.empty((0,), dtype=np.uint8),
        benches=np.concatenate(benches) if benches else np.empty((0,), dtype=np.uint8),
    )
    with (output_dir / f"rank{rank:05d}.done.json").open("w") as f:
        json.dump({"rank": rank, "world_size": world_size, "samples": seen, "load_info": load_info}, f)
    print(f"rank={rank} wrote={shard_path} samples={seen}", flush=True)


def aggregate(output_dir):
    shard_paths = sorted(output_dir.glob("shard_rank*.npz"))
    scores, labels, benches = [], [], []
    for path in shard_paths:
        arr = np.load(path)
        scores.append(arr["scores"])
        labels.append(arr["labels"])
        benches.append(arr["benches"])
    scores = np.concatenate(scores)
    labels = np.concatenate(labels)
    benches = np.concatenate(benches)
    rows = []
    for bench_id, (bench_name, _) in enumerate(BENCHMARKS):
        mask = benches == bench_id
        y = labels[mask]
        s = scores[mask]
        auc = float("nan") if len(np.unique(y)) < 2 else float(roc_auc_score(y, s))
        rows.append({
            "benchmark": bench_name,
            "n": int(mask.sum()),
            "real": int((y == 0).sum()),
            "fake": int((y == 1).sum()),
            "auc": auc,
        })
    mean_auc = float(np.nanmean([r["auc"] for r in rows]))
    with (output_dir / "auc_summary.tsv").open("w") as f:
        f.write("benchmark\tn\treal\tfake\tauc\n")
        for r in rows:
            f.write(f"{r['benchmark']}\t{r['n']}\t{r['real']}\t{r['fake']}\t{r['auc']:.8f}\n")
        f.write(f"MEAN_7_BENCHMARKS\t{sum(r['n'] for r in rows)}\t{sum(r['real'] for r in rows)}\t{sum(r['fake'] for r in rows)}\t{mean_auc:.8f}\n")
    with (output_dir / "auc_summary.json").open("w") as f:
        json.dump({"benchmarks": rows, "mean_auc": mean_auc, "num_shards": len(shard_paths)}, f, indent=2)
    print(f"MEAN_7_BENCHMARKS_AUC {mean_auc:.8f}", flush=True)


def main():
    args = parse_args()
    rank, world_size, local_rank, device = init_distributed()
    output_dir = Path(args.output_dir)
    if is_main(rank):
        output_dir.mkdir(parents=True, exist_ok=True)
    if dist.is_available() and dist.is_initialized():
        dist.barrier()

    manifest_path = Path(args.manifest) if args.manifest else output_dir / "benchmark_manifest.tsv"
    if is_main(rank) and (args.rebuild_manifest or not manifest_path.exists()):
        print(f"building_manifest path={manifest_path}", flush=True)
        build_manifest(args, manifest_path)
        print(f"manifest_ready path={manifest_path}", flush=True)
    if dist.is_available() and dist.is_initialized():
        dist.barrier()

    if is_main(rank):
        with (output_dir / "run_config.json").open("w") as f:
            json.dump(vars(args) | {"world_size": world_size}, f, indent=2)

    run_inference(args, rank, world_size, device, manifest_path, output_dir)
    if dist.is_available() and dist.is_initialized():
        dist.barrier()
    if is_main(rank):
        aggregate(output_dir)
    if dist.is_available() and dist.is_initialized():
        dist.barrier()


if __name__ == "__main__":
    main()