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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/usr/bin/env python3
"""Shardable frame-level evaluator for image-data/test.json."""

import argparse
import datetime as _dt
import json
import os
import random
import sys
import time

import cv2
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.utils.data
import yaml
from PIL import Image, ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True


def log(fp, message):
    line = "[{}] {}".format(_dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), message)
    print(line, flush=True)
    fp.write(line + "\n")
    fp.flush()


def load_yaml(path):
    with open(path, "r") as f:
        return yaml.safe_load(f)


def merge_config(detector_path, test_config_path):
    detector_config = load_yaml(detector_path)
    test_config = load_yaml(test_config_path)
    config = dict(test_config)
    config.update({k: v for k, v in detector_config.items() if v is not None})
    return config


class TestJsonDataset(torch.utils.data.Dataset):
    def __init__(self, json_path, root, config, shard_index, shard_count, max_samples=None):
        json_path = os.path.abspath(json_path)
        with open(json_path, "r") as f:
            payload = json.load(f)
        items = payload.get("items")
        if not isinstance(items, list):
            raise ValueError("{} must contain an items list".format(json_path))

        if root is None:
            root = payload.get("metadata", {}).get("root")
        if not root:
            raise ValueError("Dataset root is required.")
        if not os.path.isabs(root):
            root = os.path.normpath(os.path.join(os.path.dirname(json_path), root))

        selected = items[shard_index::shard_count]
        if max_samples is not None:
            selected = selected[:max_samples]
        self.items = selected
        self.root = root
        self.resolution = int(config.get("resolution", 224))
        self.mean = np.asarray(config.get("mean", [0.485, 0.456, 0.406]), dtype=np.float32)
        self.std = np.asarray(config.get("std", [0.229, 0.224, 0.225]), dtype=np.float32)
        label_map = config.get("image_data_json", {}).get("label_map", {"real": 0, "fake": 1})
        self.label_map = dict(label_map)
        self.paths = []
        self.labels = []
        self.datasets = []
        self.fine_labels = []
        self.methods = []
        self.invalid_read_count = 0

        for idx, item in enumerate(self.items):
            rel_path = item.get("path")
            if not rel_path:
                raise ValueError("Missing path at selected item {}".format(idx))
            raw_label = item.get("label")
            if raw_label not in self.label_map:
                raise ValueError("Unsupported label {} for {}".format(raw_label, rel_path))
            self.paths.append(rel_path)
            self.labels.append(int(self.label_map[raw_label]))
            self.datasets.append(str(item.get("dataset", "")))
            self.fine_labels.append(str(item.get("fine_label", "")))
            self.methods.append(str(item.get("method", "")))

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

    def _abs_path(self, rel_path):
        if os.path.isabs(rel_path):
            return rel_path
        return os.path.join(self.root, rel_path)

    def __getitem__(self, index):
        rel_path = self.paths[index]
        image_path = self._abs_path(rel_path)
        image = cv2.imread(image_path, cv2.IMREAD_COLOR)
        valid_image = True
        if image is None:
            try:
                pil_image = Image.open(image_path).convert("RGB")
                image = np.asarray(pil_image)
            except Exception:
                image = np.zeros((self.resolution, self.resolution, 3), dtype=np.uint8)
                valid_image = False
        else:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image = cv2.resize(image, (self.resolution, self.resolution), interpolation=cv2.INTER_CUBIC)
        image = image.astype(np.float32) / 255.0
        image = (image - self.mean.reshape(1, 1, 3)) / self.std.reshape(1, 1, 3)
        image = torch.from_numpy(image.transpose(2, 0, 1))
        return {
            "image": image,
            "label": int(self.labels[index]),
            "path": rel_path,
            "dataset": self.datasets[index],
            "fine_label": self.fine_labels[index],
            "method": self.methods[index],
            "valid_image": valid_image,
        }


def collate_fn(batch):
    return {
        "image": torch.stack([x["image"] for x in batch], dim=0),
        "label": torch.LongTensor([x["label"] for x in batch]),
        "path": [x["path"] for x in batch],
        "dataset": [x["dataset"] for x in batch],
        "fine_label": [x["fine_label"] for x in batch],
        "method": [x["method"] for x in batch],
        "valid_image": [bool(x["valid_image"]) for x in batch],
        "mask": None,
        "landmark": None,
    }


def init_seed(config):
    seed = config.get("manualSeed")
    if seed is None:
        seed = 1024
        config["manualSeed"] = seed
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if config.get("cuda", True) and torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)


def count_params(model):
    total = sum(p.numel() for p in model.parameters())
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    return int(trainable), int(total)


def adapt_moe_gate_modules_for_checkpoint(model, weights):
    """Match MoE gate scorer modules to the checkpoint key format before strict load."""
    try:
        from networks.fusion import _SharedGateMLP  # noqa: E402
    except Exception:
        return []

    device = next(model.parameters()).device
    adapted = []

    def set_shared_gate(branch_name):
        if not hasattr(model, branch_name):
            return
        branch = getattr(model, branch_name)
        mlp_w0 = "{}.shared_gate.net.0.weight".format(branch_name)
        mlp_w2 = "{}.shared_gate.net.2.weight".format(branch_name)
        linear_w = "{}.shared_gate.weight".format(branch_name)
        if mlp_w0 in weights and mlp_w2 in weights:
            hidden_dim, embed_dim = weights[mlp_w0].shape
            out_dim = weights[mlp_w2].shape[0]
            branch.shared_gate = _SharedGateMLP(
                embed_dim=int(embed_dim),
                gate_hidden_dim=int(hidden_dim),
                out_dim=int(out_dim),
            ).to(device)
            adapted.append("{}:shared_gate=MLP({},{},{})".format(
                branch_name, int(embed_dim), int(hidden_dim), int(out_dim)
            ))
        elif linear_w in weights and not isinstance(getattr(branch, "shared_gate", None), torch.nn.Linear):
            out_dim, embed_dim = weights[linear_w].shape
            branch.shared_gate = torch.nn.Linear(int(embed_dim), int(out_dim)).to(device)
            adapted.append("{}:shared_gate=Linear({},{})".format(
                branch_name, int(embed_dim), int(out_dim)
            ))

    def set_layer_attn_scorer(branch_name):
        if not hasattr(model, branch_name):
            return
        branch = getattr(model, branch_name)
        if not hasattr(branch, "layer_attn_scorer"):
            return
        mlp_w0 = "{}.layer_attn_scorer.net.0.weight".format(branch_name)
        mlp_w2 = "{}.layer_attn_scorer.net.2.weight".format(branch_name)
        linear_w = "{}.layer_attn_scorer.weight".format(branch_name)
        if mlp_w0 in weights and mlp_w2 in weights:
            hidden_dim, embed_dim = weights[mlp_w0].shape
            out_dim = weights[mlp_w2].shape[0]
            branch.layer_attn_scorer = _SharedGateMLP(
                embed_dim=int(embed_dim),
                gate_hidden_dim=int(hidden_dim),
                out_dim=int(out_dim),
            ).to(device)
            adapted.append("{}:layer_attn_scorer=MLP({},{},{})".format(
                branch_name, int(embed_dim), int(hidden_dim), int(out_dim)
            ))
        elif linear_w in weights and not isinstance(branch.layer_attn_scorer, torch.nn.Linear):
            out_dim, embed_dim = weights[linear_w].shape
            branch.layer_attn_scorer = torch.nn.Linear(int(embed_dim), int(out_dim)).to(device)
            adapted.append("{}:layer_attn_scorer=Linear({},{})".format(
                branch_name, int(embed_dim), int(out_dim)
            ))

    for branch_name in ("clip_layer_moe", "dino_layer_moe"):
        set_shared_gate(branch_name)
        set_layer_attn_scorer(branch_name)

    return adapted


def load_detector(config, weights_path, device, training_dir, repo_root):
    if training_dir not in sys.path:
        sys.path.insert(0, training_dir)
    if repo_root not in sys.path:
        sys.path.insert(0, repo_root)
    from detectors import DETECTOR  # noqa: E402

    if config.get("model_name") == "effort":
        patch_effort_svd_builder()

    model = DETECTOR[config["model_name"]](config).to(device)
    ckpt = torch.load(weights_path, map_location=device)
    if isinstance(ckpt, dict) and "state_dict" in ckpt:
        ckpt = ckpt["state_dict"]
    weights = {k.replace("module.", ""): v for k, v in ckpt.items()}
    model_keys = set(model.state_dict())
    for deprecated_key in ("clip_vision.embeddings.position_ids",):
        if deprecated_key in weights and deprecated_key not in model_keys:
            weights.pop(deprecated_key)
    adapted = adapt_moe_gate_modules_for_checkpoint(model, weights)
    if adapted:
        print("Adapted MoE gate modules for checkpoint: {}".format(", ".join(adapted)), flush=True)
    model.load_state_dict(weights, strict=True)
    if config.get("model_name") == "effort":
        model._cached_svd_modules = cache_effort_svd_weights(model)
    model.eval()
    return model


def patch_effort_svd_builder():
    """Skip expensive eval-time SVD; checkpoint loading fills these tensors."""
    try:
        from detectors import effort_detector  # noqa: E402
    except Exception:
        return

    if getattr(effort_detector, "_FAST_EVAL_SVD_PATCHED", False):
        return

    def fast_replace_with_svd_residual(module, r):
        if not isinstance(module, torch.nn.Linear):
            return module
        in_features = int(module.in_features)
        out_features = int(module.out_features)
        bias = module.bias is not None
        new_module = effort_detector.SVDResidualLinear(
            in_features,
            out_features,
            r,
            bias=bias,
            init_weight=module.weight.data.clone(),
        )
        if bias and module.bias is not None:
            new_module.bias.data.copy_(module.bias.data)

        rank = min(int(r), min(in_features, out_features))
        residual_dim = max(min(in_features, out_features) - rank, 0)
        if residual_dim > 0:
            new_module.S_residual = torch.nn.Parameter(torch.empty(residual_dim))
            new_module.U_residual = torch.nn.Parameter(torch.empty(out_features, residual_dim))
            new_module.V_residual = torch.nn.Parameter(torch.empty(residual_dim, in_features))
            new_module.S_r = torch.nn.Parameter(torch.empty(rank), requires_grad=False)
            new_module.U_r = torch.nn.Parameter(torch.empty(out_features, rank), requires_grad=False)
            new_module.V_r = torch.nn.Parameter(torch.empty(rank, in_features), requires_grad=False)
        else:
            new_module.S_residual = None
            new_module.U_residual = None
            new_module.V_residual = None
            new_module.S_r = None
            new_module.U_r = None
            new_module.V_r = None
        new_module.weight_original_fnorm = torch.tensor(0.0)
        new_module.weight_main_fnorm = torch.tensor(0.0)
        return new_module

    effort_detector.replace_with_svd_residual = fast_replace_with_svd_residual
    effort_detector._FAST_EVAL_SVD_PATCHED = True


def cache_effort_svd_weights(model):
    """Cache SVDResidualLinear effective weights for eval-only forward speed."""
    try:
        from detectors import effort_detector  # noqa: E402
    except Exception:
        return 0

    if not getattr(effort_detector.SVDResidualLinear, "_FAST_EVAL_FORWARD_PATCHED", False):
        def fast_forward(self, x):
            cached_weight = getattr(self, "_eval_weight", None)
            if cached_weight is not None:
                return torch.nn.functional.linear(x, cached_weight, self.bias)
            if hasattr(self, 'U_residual') and hasattr(self, 'V_residual') and self.S_residual is not None:
                residual_weight = self.U_residual @ torch.diag(self.S_residual) @ self.V_residual
                weight = self.weight_main + residual_weight
            else:
                weight = self.weight_main
            return torch.nn.functional.linear(x, weight, self.bias)

        effort_detector.SVDResidualLinear.forward = fast_forward
        effort_detector.SVDResidualLinear._FAST_EVAL_FORWARD_PATCHED = True

    cached = 0
    with torch.no_grad():
        for module in model.modules():
            if isinstance(module, effort_detector.SVDResidualLinear):
                if hasattr(module, 'U_residual') and hasattr(module, 'V_residual') and module.S_residual is not None:
                    residual_weight = module.U_residual @ torch.diag(module.S_residual) @ module.V_residual
                    weight = module.weight_main + residual_weight
                else:
                    weight = module.weight_main
                module.register_buffer("_eval_weight", weight.detach().clone())
                cached += 1
    return cached


def build_loader(dataset, batch_size, workers):
    pin_memory = os.environ.get("PIN_MEMORY", "1") not in ("0", "false", "False", "no", "No")
    kwargs = {
        "dataset": dataset,
        "batch_size": batch_size,
        "shuffle": False,
        "num_workers": workers,
        "drop_last": False,
        "collate_fn": collate_fn,
    }
    if workers > 0:
        kwargs["pin_memory"] = pin_memory
        kwargs["persistent_workers"] = True
        kwargs["prefetch_factor"] = 4
    return torch.utils.data.DataLoader(**kwargs)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--repo-root", required=True)
    parser.add_argument("--workdir", required=True)
    parser.add_argument("--detector-path", required=True)
    parser.add_argument("--test-config-path", required=True)
    parser.add_argument("--weights-path", required=True)
    parser.add_argument("--test-json", required=True)
    parser.add_argument("--dataset-root", default=None)
    parser.add_argument("--batch-size", type=int, required=True)
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--shard-index", type=int, required=True)
    parser.add_argument("--shard-count", type=int, required=True)
    parser.add_argument("--raw-output", required=True)
    parser.add_argument("--log-file", required=True)
    parser.add_argument("--max-samples", type=int, default=None)
    args = parser.parse_args()

    if args.dataset_root and not os.path.isabs(args.dataset_root):
        args.dataset_root = os.path.abspath(os.path.join(args.repo_root, args.dataset_root))

    torch.set_num_threads(int(os.environ.get("TORCH_NUM_THREADS", "1")))
    os.makedirs(os.path.dirname(args.raw_output), exist_ok=True)
    os.makedirs(os.path.dirname(args.log_file), exist_ok=True)
    os.chdir(args.workdir)

    with open(args.log_file, "w") as fp:
        log(fp, "repo_root={} workdir={}".format(args.repo_root, args.workdir))
        log(fp, "visible_cuda={} shard={}/{} batch={} workers={}".format(
            os.environ.get("CUDA_VISIBLE_DEVICES"), args.shard_index, args.shard_count,
            args.batch_size, args.workers,
        ))
        config = merge_config(args.detector_path, args.test_config_path)
        config["test_batchSize"] = args.batch_size
        config["workers"] = args.workers
        config["cuda"] = bool(config.get("cuda", True))
        config["lmdb"] = False
        config["image_data_json"] = {
            "enabled": True,
            "root": args.dataset_root,
            "val": args.test_json,
            "label_map": {"real": 0, "fake": 1},
        }
        init_seed(config)
        if config.get("cudnn", True):
            cudnn.benchmark = True

        dataset = TestJsonDataset(
            json_path=args.test_json,
            root=args.dataset_root,
            config=config,
            shard_index=args.shard_index,
            shard_count=args.shard_count,
            max_samples=args.max_samples,
        )
        loader = build_loader(dataset, args.batch_size, args.workers)
        log(fp, "samples={} batches={}".format(len(dataset), len(loader)))

        device = torch.device("cuda" if config["cuda"] and torch.cuda.is_available() else "cpu")
        model = load_detector(
            config=config,
            weights_path=args.weights_path,
            device=device,
            training_dir=os.path.join(args.workdir, "training"),
            repo_root=args.repo_root,
        )
        trainable_params, total_params = count_params(model)
        log(fp, "model_loaded trainable_params={} total_params={}".format(trainable_params, total_params))
        if hasattr(model, "_cached_svd_modules"):
            log(fp, "cached_svd_modules={}".format(model._cached_svd_modules))

        preds = []
        labels = []
        paths = []
        datasets = []
        fine_labels = []
        methods = []
        valid_images = []
        started = time.time()
        with torch.no_grad():
            for batch_index, batch in enumerate(loader, start=1):
                label = torch.where(batch["label"] != 0, 1, 0)
                model_batch = {
                    "image": batch["image"].to(device, non_blocking=True),
                    "label": label.to(device, non_blocking=True),
                    "mask": None,
                    "landmark": None,
                }
                output = model(model_batch, inference=True)
                preds.extend(output["prob"].detach().cpu().numpy().astype(np.float32).tolist())
                labels.extend(label.cpu().numpy().astype(np.int8).tolist())
                paths.extend(batch["path"])
                datasets.extend(batch["dataset"])
                fine_labels.extend(batch["fine_label"])
                methods.extend(batch["method"])
                valid_images.extend(batch["valid_image"])
                if batch_index == 1 or batch_index % 50 == 0 or batch_index == len(loader):
                    elapsed = time.time() - started
                    if device.type == "cuda":
                        used_mb = torch.cuda.max_memory_allocated(0) / (1024 * 1024)
                        log(fp, "progress={}/{} elapsed_sec={:.1f} max_allocated_mb={:.1f}".format(
                            batch_index, len(loader), elapsed, used_mb,
                        ))
                    else:
                        log(fp, "progress={}/{} elapsed_sec={:.1f}".format(batch_index, len(loader), elapsed))

        np.savez_compressed(
            args.raw_output,
            pred=np.asarray(preds, dtype=np.float32),
            label=np.asarray(labels, dtype=np.int8),
            path=np.asarray(paths, dtype=object),
            dataset=np.asarray(datasets, dtype=object),
            fine_label=np.asarray(fine_labels, dtype=object),
            method=np.asarray(methods, dtype=object),
            valid_image=np.asarray(valid_images, dtype=np.bool_),
            shard_index=np.asarray([args.shard_index], dtype=np.int16),
            shard_count=np.asarray([args.shard_count], dtype=np.int16),
            batch_size=np.asarray([args.batch_size], dtype=np.int32),
            trainable_params=np.asarray([trainable_params], dtype=np.int64),
            total_params=np.asarray([total_params], dtype=np.int64),
        )
        invalid_count = int((~np.asarray(valid_images, dtype=np.bool_)).sum())
        if invalid_count:
            log(fp, "invalid_image_placeholders={}".format(invalid_count))
        log(fp, "wrote_raw={} samples={}".format(args.raw_output, len(preds)))
        log(fp, "done elapsed_sec={:.1f}".format(time.time() - started))


if __name__ == "__main__":
    main()