diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a0848bfd9bae2c98b0c5ab79e43ac64418309e67 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +__pycache__/ +*.pyc +# Downloaded at startup by download_weights.py (official sources) +detectors/PGC/checkpoint/ +detectors/ForensicConcept/checkpoint/ +detectors/MDMF/checkpoint/backbones/ +detectors/MDMF/checkpoint/pretrained/weights/best.pt +detectors/MDMF/checkpoint/pretrained/weights/*.part +detectors/*/checkpoint/weights-manifest.json +detection_results/ +.venv/ \ No newline at end of file diff --git a/README.md b/README.md index 139db83d129024cf5bbe22c52466f4eeaf31fade..f951ca3576c66dd820826e846d1adb2b37d3d81d 100644 --- a/README.md +++ b/README.md @@ -27,12 +27,15 @@ This demonstrator is designed as an open-source contribution to the community. W ## ๐Ÿ› ๏ธ Available Detectors -* **ALL**: Runs all available detectors sequentially. Produces a Weighted Majority Vote verdict based on confident predictions (> 0.6) and generates a Confidence Plot. +* **ALL**: Runs all available detectors sequentially. Shows the result of each detector and generates a Confidence Plot. * **R50_TF**: ResNet-50 based detector trained on the TrueFake dataset. * **R50_nodown**: ResNet-50 without downsampling operations. * **CLIP-D**: CLIP-based deepfake detector. * **P2G**: Prompt2Guard: Conditioned prompt-optimization for continual deepfake detection. * **NPR**: Neural Posterior Regularization. +* **PGC**: Peak-guided calibration on DINOv2-L (official pre-trained weights). +* **ForensicConcept**: CLIP ViT-L/14 with a forensic concept codebook (official pre-trained weights). +* **MDMF**: Local distribution shift (MMD) on DINOv2-L patch embeddings (official pre-trained weights; reference bank and threshold computed on DeepShield data). ## ๐Ÿš€ Usage Guide @@ -46,13 +49,11 @@ This demonstrator is designed as an open-source contribution to the community. W * **Elapsed Time**: The time the model needed to make the prediction (excluding preprocessing or model building). **Understanding the Results produced by "ALL":** -* Produces a **Weighted Majority Vote** verdict (Real/Fake). -* Each model's vote is weighted by a fixed importance score based on empirical results from the **DeepShield dataset**, following this ranking: **CLIP-D > R50_TF > R50_nodown > P2G > NPR**. The weights are scaled so that their sum equals 1. Only confident predictions (> 0.6) are counted. -* Generates a **Confidence Plot** visualizing each model's score and a textual **Explanation** of the consensus. In the plot, **Green** bars indicate a **Real** prediction, while **Red** bars indicate a **Fake** prediction. +* Lists the prediction and confidence of each detector and generates a **Confidence Plot** visualizing each model's score. No aggregated verdict is produced. In the plot, **Green** bars indicate a **Real** prediction, while **Red** bars indicate a **Fake** prediction. ## ๐Ÿง  Training Data Overview -All open-source models featured in this Space have been pretrained using the **[DeepShield dataset](https://zenodo.org/records/15648378)**: +R50_TF, R50_nodown, CLIP-D, P2G and NPR have been pretrained using the **[DeepShield dataset](https://zenodo.org/records/15648378)**: * **Fake Images:** Generated using StyleGAN 2 and Stable Diffusion XL. * **Real Images:** Sourced from the FFHQ Dataset and the FORLAB Dataset. diff --git a/README_HF.md b/README_HF.md index 139db83d129024cf5bbe22c52466f4eeaf31fade..f951ca3576c66dd820826e846d1adb2b37d3d81d 100644 --- a/README_HF.md +++ b/README_HF.md @@ -27,12 +27,15 @@ This demonstrator is designed as an open-source contribution to the community. W ## ๐Ÿ› ๏ธ Available Detectors -* **ALL**: Runs all available detectors sequentially. Produces a Weighted Majority Vote verdict based on confident predictions (> 0.6) and generates a Confidence Plot. +* **ALL**: Runs all available detectors sequentially. Shows the result of each detector and generates a Confidence Plot. * **R50_TF**: ResNet-50 based detector trained on the TrueFake dataset. * **R50_nodown**: ResNet-50 without downsampling operations. * **CLIP-D**: CLIP-based deepfake detector. * **P2G**: Prompt2Guard: Conditioned prompt-optimization for continual deepfake detection. * **NPR**: Neural Posterior Regularization. +* **PGC**: Peak-guided calibration on DINOv2-L (official pre-trained weights). +* **ForensicConcept**: CLIP ViT-L/14 with a forensic concept codebook (official pre-trained weights). +* **MDMF**: Local distribution shift (MMD) on DINOv2-L patch embeddings (official pre-trained weights; reference bank and threshold computed on DeepShield data). ## ๐Ÿš€ Usage Guide @@ -46,13 +49,11 @@ This demonstrator is designed as an open-source contribution to the community. W * **Elapsed Time**: The time the model needed to make the prediction (excluding preprocessing or model building). **Understanding the Results produced by "ALL":** -* Produces a **Weighted Majority Vote** verdict (Real/Fake). -* Each model's vote is weighted by a fixed importance score based on empirical results from the **DeepShield dataset**, following this ranking: **CLIP-D > R50_TF > R50_nodown > P2G > NPR**. The weights are scaled so that their sum equals 1. Only confident predictions (> 0.6) are counted. -* Generates a **Confidence Plot** visualizing each model's score and a textual **Explanation** of the consensus. In the plot, **Green** bars indicate a **Real** prediction, while **Red** bars indicate a **Fake** prediction. +* Lists the prediction and confidence of each detector and generates a **Confidence Plot** visualizing each model's score. No aggregated verdict is produced. In the plot, **Green** bars indicate a **Real** prediction, while **Red** bars indicate a **Fake** prediction. ## ๐Ÿง  Training Data Overview -All open-source models featured in this Space have been pretrained using the **[DeepShield dataset](https://zenodo.org/records/15648378)**: +R50_TF, R50_nodown, CLIP-D, P2G and NPR have been pretrained using the **[DeepShield dataset](https://zenodo.org/records/15648378)**: * **Fake Images:** Generated using StyleGAN 2 and Stable Diffusion XL. * **Real Images:** Sourced from the FFHQ Dataset and the FORLAB Dataset. diff --git a/__pycache__/app.cpython-310.pyc b/__pycache__/app.cpython-310.pyc deleted file mode 100644 index 4a8efee35c09de4fd3556d6b7db7fc9f2b4c9b79..0000000000000000000000000000000000000000 Binary files a/__pycache__/app.cpython-310.pyc and /dev/null differ diff --git a/app.py b/app.py index 71e7ee848362bdc97d220efb48f17f643b2dd998..2b48cf4c65d52e0b5cff63221c79b6486ad9e414 100644 --- a/app.py +++ b/app.py @@ -32,15 +32,8 @@ if os.environ.get("SPACE_ID"): print(f"Warning: Could not download weights: {e}") # Available detectors based on launcher.py -DETECTORS = ['ALL', 'R50_TF', 'R50_nodown', 'CLIP-D', 'P2G', 'NPR'] +DETECTORS = ['ALL', 'R50_TF', 'R50_nodown', 'CLIP-D', 'P2G', 'NPR', 'PGC', 'ForensicConcept', 'MDMF'] -DETECTOR_WEIGHTS = { - 'CLIP-D': 0.30, - 'R50_TF': 0.25, - 'R50_nodown': 0.20, - 'P2G': 0.15, - 'NPR': 0.10 -} def process_image(image_path): """ @@ -88,6 +81,7 @@ def run_single_detection(image_path, detector_name): output=output_path, weights='pretrained', # Use default/pretrained device='cpu', # Force CPU + batch_size=1, dry_run=False, verbose=False ) @@ -144,76 +138,43 @@ def predict(image_path, detector_name): if not results: return "Error: No results obtained from detectors.", None - votes_real = 0.0 - votes_fake = 0.0 - total_weight_used = 0.0 confidences = [] labels = [] colors = [] - + lines = [] + for det, res in results: pred = res.get('prediction', 'Unknown') - raw_conf = res.get('confidence', 0.0) - - # Calculate display confidence (confidence of the prediction) + # fake_score = probability of fake for every detector (support/detect.py fills it in) + raw_conf = res.get('fake_score', res.get('confidence', 0.0)) + + # Display confidence (confidence of the prediction) if pred == 'fake': score = raw_conf color = 'red' else: score = 1 - raw_conf color = 'green' - + labels.append(det) confidences.append(score) colors.append(color) - - # Weighted Voting logic - # Only count vote if confidence > 0.6 - if score > 0.6: - weight = DETECTOR_WEIGHTS.get(det, 0.0) - if pred == 'fake': - votes_fake += weight * score - total_weight_used += weight - elif pred == 'real': - votes_real += weight * score - total_weight_used += weight - - # Majority Voting - if votes_real > votes_fake: - verdict = "REAL" - elif votes_fake > votes_real: - verdict = "FAKE" - else: - verdict = "UNCERTAIN" - - # Calculate weighted average confidence - if total_weight_used > 0: - weighted_conf = (votes_real + votes_fake) / total_weight_used - else: - weighted_conf = 0.0 - - # Explanation - if verdict == "REAL": - explanation = f"Considering the results obtained by all models (weighted by their historical performance), the analyzed image results, with a weighted confidence of {weighted_conf:.4f}, not produced by a generative AI." - elif verdict == "FAKE": - explanation = f"Considering the results obtained by all models (weighted by their historical performance), the analyzed image results, with a weighted confidence of {weighted_conf:.4f}, produced by a generative AI." - else: - explanation = f"The result is uncertain. The detectors produced unconsistent results. The weighted confidence is {weighted_conf:.4f}." - + lines.append(f"{det}: {pred} (confidence {score:.4f})") + + explanation = "Results of each detector:\n" + "\n".join(lines) + # Plotting fig, ax = plt.subplots(figsize=(10, 5)) bars = ax.bar(labels, confidences, color=colors) ax.set_ylim(0, 1.05) ax.set_ylabel('Confidence') ax.set_title('Detector Confidence Scores') - ax.axhline(y=0.6, color='gray', linestyle='--', alpha=0.5, label='Vote Threshold (0.6)') # Add custom legend for colors from matplotlib.patches import Patch legend_elements = [ Patch(facecolor='green', label='Real'), - Patch(facecolor='red', label='Fake'), - ax.lines[0] # The threshold line + Patch(facecolor='red', label='Fake') ] ax.legend(handles=legend_elements) @@ -233,7 +194,7 @@ def predict(image_path, detector_name): if res: prediction = res.get('prediction', 'Unknown') - confidence = res.get('confidence', 0.0) + confidence = res.get('fake_score', res.get('confidence', 0.0)) elapsed_time = res.get('elapsed_time', 0.0) if prediction == 'fake': @@ -290,10 +251,8 @@ with demo: * **Elapsed Time**: The time the model needed to make the prediction (excluding preprocessing or model building). ### The "ALL" Option - * Runs all available detectors (R50_TF, R50_nodown, CLIP-D, P2G, NPR) sequentially on the input image. - * Produces a **Weighted Majority Vote** verdict (Real/Fake). Each model's vote is weighted by a fixed importance score (summing to 1) based on user ranking **and its confidence score**. Only confident predictions (> 0.6) are counted. - * You can find the specific weights used for each model in the **"โš–๏ธ Weight Details"** menu below. - * Also generates a **Confidence Plot** visualizing each model's score and a textual **Explanation** of the consensus. + * Runs all available detectors (R50_TF, R50_nodown, CLIP-D, P2G, NPR, PGC, ForensicConcept, MDMF) sequentially on the input image. + * Lists the prediction and confidence of each detector and generates a **Confidence Plot** visualizing each model's score. No aggregated verdict is produced. * In the plot, **Green** bars indicate a **Real** prediction, while **Red** bars indicate a **Fake** prediction. """) @@ -318,24 +277,11 @@ with demo: ) plot_output = gr.Plot(label="Confidence Scores") - with gr.Accordion("โš–๏ธ Weight Details", open=False): - gr.Markdown(f""" - ### **Detector Weights** - The weights are assigned according to the models' performance ranking on the **[DeepShield dataset](https://zenodo.org/records/15648378)** (**CLIP-D > R50_TF > R50_nodown > P2G > NPR**), ensuring their total sum equals 1. - | Detector | Weight | - | :--- | :---: | - | **CLIP-D** | {DETECTOR_WEIGHTS['CLIP-D']:.2f} | - | **R50_TF** | {DETECTOR_WEIGHTS['R50_TF']:.2f} | - | **R50_nodown** | {DETECTOR_WEIGHTS['R50_nodown']:.2f} | - | **P2G** | {DETECTOR_WEIGHTS['P2G']:.2f} | - | **NPR** | {DETECTOR_WEIGHTS['NPR']:.2f} | - """) - with gr.Accordion("๐Ÿ“š Model Details", open=False): gr.Markdown(""" ### **ALL** - * **Description**: Runs all available detectors (R50_TF, R50_nodown, CLIP-D, P2G, NPR) sequentially on the input image. The complete code for training and testing these models on your own datasets is available in our [GitHub repository](https://github.com/truebees-ai/Image-Deepfake-Detectors-Public-Library). - * **Results**: Produces a **Majority Vote** verdict (Real/Fake) considering only confident predictions (> 0.6). Also generates a **Confidence Plot** visualizing each model's score and a textual **Explanation** of the consensus. + * **Description**: Runs all available detectors (R50_TF, R50_nodown, CLIP-D, P2G, NPR, PGC, ForensicConcept, MDMF) sequentially on the input image. The complete code for training and testing these models on your own datasets is available in our [GitHub repository](https://github.com/truebees-ai/Image-Deepfake-Detectors-Public-Library). + * **Results**: Shows the prediction of each detector and a **Confidence Plot** with each model's score (no aggregated verdict). ### **R50_TF** * **Description**: A ResNet50 architecture modified to exclude downsampling at the first layer. It uses "learned prototypes" in the classification head for robust detection. @@ -361,6 +307,18 @@ with demo: * **Description**: Focuses on Neighboring Pixel Relationships (NPR) to capture generalized structural artifacts stemming from up-sampling operations in generative networks. * **Paper**: [Rethinking the Up-Sampling Operations in CNN-based Generative Network for Generalizable Deepfake Detection](https://arxiv.org/abs/2312.10461) * **Code**: [GitHub Repository](https://github.com/chuangchuangtan/NPR-DeepfakeDetection) + + ### **PGC** + * **Description**: Peak-guided calibration on a DINOv2-L backbone. Uses the **official pre-trained weights** released by the authors (not trained on DeepShield). + * **Weights**: [xiaoyuzhou68/PGC_ckpt](https://huggingface.co/xiaoyuzhou68/PGC_ckpt) + + ### **ForensicConcept** + * **Description**: CLIP ViT-L/14 with a forensic concept codebook. Uses the **official pre-trained weights** released by the authors (not trained on DeepShield). + * **Weights**: [ethan225/ForensicConcept](https://huggingface.co/ethan225/ForensicConcept) ยท **Code**: [GitHub Repository](https://github.com/EthanAdamm/FORENSICCONCEPT) + + ### **MDMF** + * **Description**: Local distribution shift measured with MMD on DINOv2-L patch embeddings. Uses the **official pre-trained weights**; the real-image reference bank and decision threshold were built locally from DeepShield data. + * **Code**: [GitHub Repository](https://github.com/ZBox1005/MDMF) """) gr.Markdown(""" diff --git a/configs/ForensicConcept.yaml b/configs/ForensicConcept.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b52bf75ad32aa0f4616fc12b5e9de7d8daa02c6e --- /dev/null +++ b/configs/ForensicConcept.yaml @@ -0,0 +1,15 @@ +global: + dataset_path: + device_override: cpu + split_file: ./split.json + num_threads: 0 + dry_run: false + only_list: false +detector_args: [] +training: + - data: gan2:pre&sdXL:pre&realFFHQ:pre&realFORLAB:pre +testing: + - all:pre + - all:fb + - all:tl + - all:tw diff --git a/configs/MDMF.yaml b/configs/MDMF.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b52bf75ad32aa0f4616fc12b5e9de7d8daa02c6e --- /dev/null +++ b/configs/MDMF.yaml @@ -0,0 +1,15 @@ +global: + dataset_path: + device_override: cpu + split_file: ./split.json + num_threads: 0 + dry_run: false + only_list: false +detector_args: [] +training: + - data: gan2:pre&sdXL:pre&realFFHQ:pre&realFORLAB:pre +testing: + - all:pre + - all:fb + - all:tl + - all:tw diff --git a/configs/PGC.yaml b/configs/PGC.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b52bf75ad32aa0f4616fc12b5e9de7d8daa02c6e --- /dev/null +++ b/configs/PGC.yaml @@ -0,0 +1,15 @@ +global: + dataset_path: + device_override: cpu + split_file: ./split.json + num_threads: 0 + dry_run: false + only_list: false +detector_args: [] +training: + - data: gan2:pre&sdXL:pre&realFFHQ:pre&realFORLAB:pre +testing: + - all:pre + - all:fb + - all:tl + - all:tw diff --git a/detectors/CLIP-D/__pycache__/parser.cpython-310.pyc b/detectors/CLIP-D/__pycache__/parser.cpython-310.pyc deleted file mode 100644 index 0ed86c21aad9c989282c84884489b0f1e77bf269..0000000000000000000000000000000000000000 Binary files a/detectors/CLIP-D/__pycache__/parser.cpython-310.pyc and /dev/null differ diff --git a/detectors/CLIP-D/networks/__pycache__/__init__.cpython-310.pyc b/detectors/CLIP-D/networks/__pycache__/__init__.cpython-310.pyc index 3ad7b8260231eba512d1004ec39dce5453127830..da110d9f2c5c2368dab67966edb1da80f3eea6a6 100644 Binary files a/detectors/CLIP-D/networks/__pycache__/__init__.cpython-310.pyc and b/detectors/CLIP-D/networks/__pycache__/__init__.cpython-310.pyc differ diff --git a/detectors/CLIP-D/networks/__pycache__/openclipnet.cpython-310.pyc b/detectors/CLIP-D/networks/__pycache__/openclipnet.cpython-310.pyc index c1f95c01470d5e95b8575fdafd4ca22b31049bcc..75d49396d4fa8addcab5bc0dd98240f58a98ee43 100644 Binary files a/detectors/CLIP-D/networks/__pycache__/openclipnet.cpython-310.pyc and b/detectors/CLIP-D/networks/__pycache__/openclipnet.cpython-310.pyc differ diff --git a/detectors/CLIP-D/networks/__pycache__/resnet_mod.cpython-310.pyc b/detectors/CLIP-D/networks/__pycache__/resnet_mod.cpython-310.pyc index 772e7bb738f3512969584bee09f2d4ee7c01e6e5..7bad8565393df3842e60c51294824285d0206324 100644 Binary files a/detectors/CLIP-D/networks/__pycache__/resnet_mod.cpython-310.pyc and b/detectors/CLIP-D/networks/__pycache__/resnet_mod.cpython-310.pyc differ diff --git a/detectors/CLIP-D/utils/__pycache__/__init__.cpython-310.pyc b/detectors/CLIP-D/utils/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 3867ae427fd090a2e4038f9d31ebf4c94e3ebc32..0000000000000000000000000000000000000000 Binary files a/detectors/CLIP-D/utils/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/detectors/CLIP-D/utils/__pycache__/dataset.cpython-310.pyc b/detectors/CLIP-D/utils/__pycache__/dataset.cpython-310.pyc deleted file mode 100644 index d0612836a5bc63fed605244079dc4b48ca1443e7..0000000000000000000000000000000000000000 Binary files a/detectors/CLIP-D/utils/__pycache__/dataset.cpython-310.pyc and /dev/null differ diff --git a/detectors/CLIP-D/utils/__pycache__/processing.cpython-310.pyc b/detectors/CLIP-D/utils/__pycache__/processing.cpython-310.pyc deleted file mode 100644 index 340eeab41435f3d78b65dc460fde821356d1298d..0000000000000000000000000000000000000000 Binary files a/detectors/CLIP-D/utils/__pycache__/processing.cpython-310.pyc and /dev/null differ diff --git a/detectors/CLIP-D/utils/__pycache__/training.cpython-310.pyc b/detectors/CLIP-D/utils/__pycache__/training.cpython-310.pyc deleted file mode 100644 index 44bb4a8ba994a8ac4a158486540317239de56c76..0000000000000000000000000000000000000000 Binary files a/detectors/CLIP-D/utils/__pycache__/training.cpython-310.pyc and /dev/null differ diff --git a/detectors/ForensicConcept/detect.py b/detectors/ForensicConcept/detect.py new file mode 100644 index 0000000000000000000000000000000000000000..522ff9aa1d6e556109504580af8c068d97076239 --- /dev/null +++ b/detectors/ForensicConcept/detect.py @@ -0,0 +1,4 @@ +from run import main + +if __name__ == "__main__": + main("detect") diff --git a/detectors/ForensicConcept/run.py b/detectors/ForensicConcept/run.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77a2fbb280eff19ecafaf5b3d65de868bbf8ae --- /dev/null +++ b/detectors/ForensicConcept/run.py @@ -0,0 +1,134 @@ +"""DeepShield adapter for the official ForensicConcept CLIP codebook model.""" + +import shutil +import sys +import tempfile +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path[:0] = [str(ROOT), str(HERE / "upstream")] + +import torch +from PIL import Image +from torchvision import transforms +from torch.utils.data import DataLoader + +from config_loader import ConfigLoader +from data import get_dataset +from networks.trainer import Trainer +from support.recent_common import checkpoint, detection_result, device_for, parser, timed_score, validate_inputs, write_results +from support.recent_data import samples, stage + + +def configuration(name, device, batch_size, threads, *, train, dataroot=None, checkpoint_path=None): + config = ConfigLoader(str(HERE / "upstream" / "configs" / "clip_codebook.yaml")) + backbone = HERE / "checkpoint" / "backbones" / "ViT-L-14.pt" + codebook = HERE / "upstream" / "codebooks" / "cleandift_codebook.npy" + if not backbone.is_file(): + raise FileNotFoundError(f"CLIP backbone missing: {backbone}; run support/setup_recent_weights.py ForensicConcept") + if not codebook.is_file(): + raise FileNotFoundError(f"Codebook missing: {codebook}") + config.set("models.pretrained.clip_model", str(backbone)) + config.set("models.checkpoints_dir", str(HERE / "checkpoint")) + config.set("training.clip_codebook_path", str(codebook)) + config.set("training.name", name) + config.set("training.gpu_ids", device.index if device.type == "cuda" else -1) + config.set("training.batch_size", batch_size) + config.set("testing.batch_size", batch_size) + config.set("system.num_threads", threads) + config.set("training.continue_train", not train) + config.set("training.epoch", str(checkpoint_path) if checkpoint_path else "best") + config.set("logging.tensorboard", False) + if dataroot: + config.set("data.train_dataroot", str(dataroot)) + config.set("data.train_split", "train") + return config + + +def load(name, device, batch_size, threads): + path = checkpoint("ForensicConcept", name) + config = configuration(name, device, batch_size, threads, train=False, checkpoint_path=path) + opt = config.to_namespace(is_train=False) + opt.local_rank = -1 + return Trainer(opt).model.eval().to(device) + + +def eval_transform(): + # The released CLIP codebook configuration uses legacy_preprocess=true. + # Its eval path is resize -> center crop -> ImageNet normalization. + return transforms.Compose([transforms.Resize((224, 224)), transforms.CenterCrop(224), + transforms.ToTensor(), transforms.Normalize([.485, .456, .406], [.229, .224, .225])]) + + +def main(task): + args = parser("ForensicConcept", task).parse_args() + validate_inputs(args, task) + device = device_for(args.device) + name = args.model or args.name if task == "detect" else args.name + if task == "train": + entries = samples(args.data_root, args.split_file, "train", args.data_keys) + if {label for _, label in entries} != {0, 1}: + raise ValueError("ForensicConcept training needs real and fake images") + with tempfile.TemporaryDirectory(prefix="forensicconcept-") as temporary: + stage(temporary, "train", entries) + config = configuration(name, device, args.batch_size, args.num_threads, + train=True, dataroot=temporary) + opt = config.to_namespace(is_train=True) + opt.dataroot = str(Path(temporary) / "train") + opt.local_rank = -1 + data = get_dataset(opt) + loader = DataLoader(data, batch_size=args.batch_size, shuffle=True, + num_workers=args.num_threads) + trainer = Trainer(opt) + for epoch in range(args.epochs): + trainer.train() + for step, batch in enumerate(loader): + trainer.set_input(batch) + trainer.optimize_parameters() + print(f"epoch={epoch + 1} step={step + 1} loss={trainer.loss.item():.5f}") + if args.max_steps and step + 1 >= args.max_steps: + break + trainer.save_networks("best") + source = Path(trainer.save_dir) / "model_epoch_best.pth" + target = HERE / "checkpoint" / name / "weights" / "best.pt" + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, target) + print(f"Saved {target}") + return + + model = load(name, device, args.batch_size, args.num_threads) + transform = eval_transform() + + @torch.inference_mode() + def score(path): + with Image.open(path) as image: + tensor = transform(image.convert("RGB")).unsqueeze(0).to(device) + output = model(tensor) + raw = float(output["logits"].flatten()[0].item()) + return raw, float(torch.sigmoid(torch.tensor(raw)).item()) + + if task == "detect": + image = Path(args.image) + if not image.is_file(): + raise FileNotFoundError(image) + raw, fake, elapsed = timed_score(score, image) + detection_result("ForensicConcept", image, raw, fake, elapsed, args.output) + else: + rows = [] + entries = samples(args.data_root, args.split_file, "test", args.data_keys) + with torch.inference_mode(): + for offset in range(0, len(entries), args.batch_size): + chunk = entries[offset:offset + args.batch_size] + tensors = [] + for path, _ in chunk: + with Image.open(path) as image: + tensors.append(transform(image.convert("RGB"))) + start = time.perf_counter() + logits = model(torch.stack(tensors).to(device))["logits"].flatten().cpu() + elapsed = (time.perf_counter() - start) / len(chunk) + for (path, label), raw, fake in zip(chunk, logits.tolist(), torch.sigmoid(logits).tolist()): + rows.append({"path": str(path), "label": label, "raw_score": raw, + "fake_score": fake, "prediction": int(fake >= .5), "elapsed_time": elapsed}) + write_results("ForensicConcept", name, args.data_keys, rows) diff --git a/detectors/ForensicConcept/test.py b/detectors/ForensicConcept/test.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1a7a4aa7e0a6d8be04e70943b022b6dfa77d35 --- /dev/null +++ b/detectors/ForensicConcept/test.py @@ -0,0 +1,4 @@ +from run import main + +if __name__ == "__main__": + main("test") diff --git a/detectors/ForensicConcept/train.py b/detectors/ForensicConcept/train.py new file mode 100644 index 0000000000000000000000000000000000000000..c7fd0a1ae6fd21a7b36d8d13da9cb1a9962627d5 --- /dev/null +++ b/detectors/ForensicConcept/train.py @@ -0,0 +1,4 @@ +from run import main + +if __name__ == "__main__": + main("train") diff --git a/detectors/ForensicConcept/upstream/LICENSE b/detectors/ForensicConcept/upstream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bf4f5233727add0795b8c389a3e3a9ca9d364ea0 --- /dev/null +++ b/detectors/ForensicConcept/upstream/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 ForensicConcept Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/detectors/ForensicConcept/upstream/THIRD_PARTY_NOTICES.md b/detectors/ForensicConcept/upstream/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000000000000000000000000000000000000..9bca8080ed5d00aabc871ae8ecb42c2a9f580b8b --- /dev/null +++ b/detectors/ForensicConcept/upstream/THIRD_PARTY_NOTICES.md @@ -0,0 +1,30 @@ +# Third-party notices + +This release contains modified or adapted code from the following projects. +The project-level license for this repository does not replace these notices. + +## OpenAI CLIP + +Files under `models/clip/` include code and tokenizer data adapted from +[OpenAI CLIP](https://github.com/openai/CLIP). OpenAI CLIP is distributed +under the MIT License. The required notice is reproduced in +`LICENSES/CLIP-MIT.txt`. + +## LoRA + +Files under `models/clip/loratorch/` contain a reconstructed LoRA +implementation based on [Microsoft LoRA](https://github.com/microsoft/LoRA), +with additional project-specific modifications. Microsoft LoRA is distributed +under the MIT License. The required notice is reproduced in +`LICENSES/LORA-MIT.txt`. + +## DINOv3 + +DINOv3 source code and pretrained weights are not included in this release. +They are external dependencies and remain subject to the license and model +terms published by the [official DINOv3 repository](https://github.com/facebookresearch/dinov3). + +## Python dependencies + +Packages installed from `requirements.txt` retain their own licenses. This +notice does not modify or replace those licenses. diff --git a/detectors/ForensicConcept/upstream/aug_utils_train/__init__.py b/detectors/ForensicConcept/upstream/aug_utils_train/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf61b8c94487d03bfb1b50228863a43a123db41 --- /dev/null +++ b/detectors/ForensicConcept/upstream/aug_utils_train/__init__.py @@ -0,0 +1 @@ +from .utils_data import distort_images \ No newline at end of file diff --git a/detectors/ForensicConcept/upstream/aug_utils_train/distortions.py b/detectors/ForensicConcept/upstream/aug_utils_train/distortions.py new file mode 100644 index 0000000000000000000000000000000000000000..a71499d8e9bf1140023b6b060b67af8ad3bb2659 --- /dev/null +++ b/detectors/ForensicConcept/upstream/aug_utils_train/distortions.py @@ -0,0 +1,192 @@ +import torch +from torchvision.io.image import decode_jpeg, encode_jpeg +import numpy as np +import math +import kornia +from .utils_distortions import fspecial, filter2D, curves, imscatter, mapmm +from torch.nn import functional as F + +def gaussian_blur(x: torch.Tensor, blur_sigma: int = 0.1) -> torch.Tensor: + fs = 2 * math.ceil(2 * blur_sigma) + 1 + h = fspecial('gaussian', (fs, fs), blur_sigma) + h = torch.from_numpy(h).float() + + if len(x.shape) == 3: + x = x.unsqueeze(0) + + y = filter2D(x, h.unsqueeze(0)).squeeze(0) + return y + + +def lens_blur(x: torch.Tensor, radius: int) -> torch.Tensor: + h = fspecial('disk', radius) + h = torch.from_numpy(h).float() + + if len(x.shape) == 3: + x = x.unsqueeze(0) + + y = filter2D(x, h.unsqueeze(0)).squeeze(0) + return y + + +def color_saturation(x: torch.Tensor, factor: int) -> torch.Tensor: + x = x[[2, 1, 0], ...] + hsv = kornia.color.rgb_to_hsv(x) + hsv[1, ...] *= factor + y = kornia.color.hsv_to_rgb(hsv) + return y[[2, 1, 0], ...] + + +def color_shift(x: torch.Tensor, amount: int) -> torch.Tensor: + def perc(x, perc): + xs = torch.sort(x) + i = len(xs) * perc / 100. + i = max(min(i, len(xs)), 1) + v = xs[round(i - 1)] + return v + + gray = kornia.color.rgb_to_grayscale(x) + gradxy = kornia.filters.spatial_gradient(gray.unsqueeze(0), 'diff') + e = torch.sum(gradxy ** 2, 2) ** 0.5 + + fs = 2 * math.ceil(2 * 4) + 1 + h = fspecial('gaussian', (fs, fs), 4) + h = torch.from_numpy(h).float() + + e = filter2D(e, h.unsqueeze(0)) + + mine = torch.min(e) + maxe = torch.max(e) + + if mine < maxe: + e = (e - mine) / (maxe - mine) + + percdev = [1, 1] + valuehi = perc(e, 100 - percdev[1]) + valuelo = 1 - perc(1 - e, 100 - percdev[0]) + + e = torch.max(torch.min(e, valuehi), valuelo) + + channel = 1 + g = x[channel, :, :] + a = np.random.random((1, 2)) + amount_shift = np.round(a / (np.sum(a ** 2) ** 0.5) * amount)[0].astype(int) + + y = F.pad(g, (amount_shift[0], amount_shift[0]), mode='replicate') + y = F.pad(y.transpose(1, 0), (amount_shift[1], amount_shift[1]), mode='replicate').transpose(1, 0) + y = torch.roll(y, (amount_shift[0], amount_shift[1]), dims=(0, 1)) + + if amount_shift[1] != 0: + y = y[amount_shift[1]:-amount_shift[1], ...] + if amount_shift[0] != 0: + y = y[..., amount_shift[0]:-amount_shift[0]] + + yblend = y * e + x[channel, ...] * (1 - e) + x[channel, ...] = yblend + + return x + + +def jpeg(x: torch.Tensor, quality: int) -> torch.Tensor: + x_loc = x.clone() + x_loc *= 255. + x_loc = x_loc.clamp(0, 255) + y = encode_jpeg(x_loc.byte().cpu(), quality=quality) + y = (decode_jpeg(y) / 255.).to(torch.float32) + return y + + +def white_noise(x: torch.Tensor, var: float, clip: bool = True, rounds: bool = False) -> torch.Tensor: + noise = torch.randn(*x.size(), dtype=x.dtype) * math.sqrt(var) + + y = x + noise + + if clip and rounds: + y = torch.clip((y * 255.0).round(), 0, 255) / 255. + elif clip: + y = torch.clip(y, 0, 1) + elif rounds: + y = (y * 255.0).round() / 255. + return y + + +def impulse_noise(x: torch.Tensor, d: float, s_vs_p: float = 0.5) -> torch.Tensor: + num_sp = int(d * x.shape[0] * x.shape[1] * x.shape[2]) + + coords = np.concatenate((np.random.randint(0, 3, (num_sp, 1)), + np.random.randint(0, x.shape[1], (num_sp, 1)), + np.random.randint(0, x.shape[2], (num_sp, 1))), 1) + + num_salt = int(s_vs_p * num_sp) + + coords_salt = coords[:num_salt].transpose(1, 0) + coords_pepper = coords[num_salt:].transpose(1, 0) + + x[tuple(coords_salt)] = 1 + x[tuple(coords_pepper)] = 0 + + return x + + +def brighten(x: torch.Tensor, amount: float) -> torch.Tensor: + x = x[[2, 1, 0]] + lab = kornia.color.rgb_to_lab(x) + + l = lab[0, ...] / 100. + l_ = curves(l, 0.5 + amount / 2) + lab[0, ...] = l_ * 100. + + y = curves(x, 0.5 + amount / 2) + + j = torch.clamp(kornia.color.lab_to_rgb(lab), 0, 1) + + y = (2 * y + j) / 3 + + return y[[2, 1, 0]] + + +def darken(x: torch.Tensor, amount: float, dolab: bool = False) -> torch.Tensor: + x = x[[2, 1, 0], :, :] + lab = kornia.color.rgb_to_lab(x) + if dolab: + l = lab[0, ...] / 100. + l_ = curves(l, 0.5 + amount / 2) + lab[0, ...] = l_ * 100. + + y = curves(x, 0.5 - amount / 2) + + if dolab: + j = torch.clamp(kornia.color.lab_to_rgb(lab), 0, 1) + y = (2 * y + j) / 3 + + return y[[2, 1, 0]] + + +def jitter(x: torch.Tensor, amount: float) -> torch.Tensor: + y = imscatter(x, amount, 5) + return y + + +def quantization(x: torch.Tensor, levels: int) -> torch.Tensor: + image = kornia.color.rgb_to_grayscale(x) * 255 + image = image.cpu().numpy() + num_classes = levels + + # minimum variance thresholding + hist, bins = np.histogram(image, num_classes, [0, 255]) + + return_thresholds = np.zeros(num_classes - 1) + for i in range(num_classes - 1): + return_thresholds[i] = bins[i + 1] + + # quantize image with thresholds + bins = torch.tensor([0] + return_thresholds.tolist() + [256]) + bins = bins.type(torch.int) + image = torch.bucketize(x.contiguous() * 255., bins).to(torch.float32) + image = mapmm(image) + return image + + +def linear_contrast_change(x: torch.Tensor, amount: float) -> torch.Tensor: + y = curves(x, [0.25 - amount / 4, 0.75 + amount / 4]) + return y \ No newline at end of file diff --git a/detectors/ForensicConcept/upstream/aug_utils_train/utils_data.py b/detectors/ForensicConcept/upstream/aug_utils_train/utils_data.py new file mode 100644 index 0000000000000000000000000000000000000000..969bef0b5e9c71dc9d21f384e00f4a389e1f62f7 --- /dev/null +++ b/detectors/ForensicConcept/upstream/aug_utils_train/utils_data.py @@ -0,0 +1,113 @@ + +from .distortions import * +import random + +distortion_groups = { + "blur": ["gausblur", "lensblur"], + "color_distortion": ["colorshift", "colorsat"], + "jpeg": ["jpeg"], + "noise": ["whitenoise", "impulsenoise"], + "brightness_change": ["brighten", "darken"], + "spatial_distortion": ["jitter", "quantization"], + "sharpness_contrast": ["lincontrchange"], +} + +distortion_groups_mapping = { + "gausblur": "blur", + "lensblur": "blur", + "colorshift": "color_distortion", + "colorsat": "color_distortion", + "jpeg": "jpeg", + "whitenoise": "noise", + "impulsenoise": "noise", + "brighten": "brightness_change", + "darken": "brightness_change", + "jitter": "spatial_distortion", + "quantization": "spatial_distortion", + "lincontrchange": "sharpness_contrast", +} + +distortion_range = { + "gausblur": [0.1, 0.5, 1, 2, 5], + "lensblur": [1, 2, 4, 6, 8], + "colorshift": [1, 3, 6, 8, 12], + "colorsat": [0.4, 0.2, 0.1, 0, -0.4], + "jpeg": [43, 36, 24, 7, 4], + "whitenoise": [0.001, 0.002, 0.003, 0.005, 0.01], + "impulsenoise": [0.001, 0.005, 0.01, 0.02, 0.03], + "brighten": [0.1, 0.2, 0.4, 0.7, 1.1], + "darken": [0.05, 0.1, 0.2, 0.4, 0.8], + "jitter": [0.05, 0.1, 0.2, 0.5, 1], + "quantization": [20, 16, 13, 10, 7], + "lincontrchange": [0., 0.15, -0.4, 0.3, -0.6], +} + +distortion_functions = { + "gausblur": gaussian_blur, + "lensblur": lens_blur, + "colorshift": color_shift, + "colorsat": color_saturation, + "jpeg": jpeg, + "whitenoise": white_noise, + "impulsenoise": impulse_noise, + "brighten": brighten, + "darken": darken, + "jitter": jitter, + "quantization": quantization, + "lincontrchange": linear_contrast_change +} + + +def distort_images(image: torch.Tensor, distort_functions: list = None, distort_values: list = None, + max_distortions: int = 3, num_levels: int = 5) -> torch.Tensor: + """ + Args: + image (Tensor of size [3,H,W] and value range [0,1]): image to distort + distort_functions (list): list of the distortion functions to apply to the image. If None, the functions are randomly chosen. + distort_values (list): list of the values of the distortion functions to apply to the image. If None, the values are randomly chosen. + max_distortions (int): maximum number of distortions to apply to the image + num_levels (int): number of levels of distortion that can be applied to the image + + Returns: + image (Tensor): distorted image + distort_functions (list): list of the distortion functions applied to the image + distort_values (list): list of the values of the distortion functions applied to the image + """ + image_loc = image.clone() + if distort_functions is None or distort_values is None: + distort_functions, distort_values = get_distortions_composition(max_distortions, num_levels) + + for distortion, value in zip(distort_functions, distort_values): + image_loc = distortion(image_loc, value) + image_loc = image_loc.to(torch.float32) + image_loc = torch.clip(image_loc, 0, 1) + + return image_loc, distort_functions, distort_values + + +def get_distortions_composition(max_distortions: int = 3, num_levels: int = 5): + """ + Args: + max_distortions (int): maximum number of distortions to apply to the image + num_levels (int): number of levels of distortion that can be applied to the image + + Returns: + distort_functions (list): list of the distortion functions to apply to the image + distort_values (list): list of the values of the distortion functions to apply to the image + """ + MEAN = 0 + STD = 2.5 + + num_distortions = random.randint(1, max_distortions) + groups = random.sample(list(distortion_groups.keys()), num_distortions) + distortions = [random.choice(distortion_groups[group]) for group in groups] + distort_functions = [distortion_functions[dist] for dist in distortions] + + probabilities = [1 / (STD * np.sqrt(2 * np.pi)) * np.exp(-((i - MEAN) ** 2) / (2 * STD ** 2)) + for i in range(num_levels)] # probabilities according to a gaussian distribution + normalized_probabilities = [prob / sum(probabilities) + for prob in probabilities] # normalize probabilities + distort_values = [np.random.choice(distortion_range[dist][:num_levels], p=normalized_probabilities) for dist + in distortions] + + return distort_functions, distort_values diff --git a/detectors/ForensicConcept/upstream/aug_utils_train/utils_distortions.py b/detectors/ForensicConcept/upstream/aug_utils_train/utils_distortions.py new file mode 100644 index 0000000000000000000000000000000000000000..095d3d7c19c2e92479507629367e434f2903bc37 --- /dev/null +++ b/detectors/ForensicConcept/upstream/aug_utils_train/utils_distortions.py @@ -0,0 +1,281 @@ +import math +import numpy as np +from typing import Union, Tuple +import torch +from torch.nn import functional as F +import scipy + +def sign(x: float) -> int: + return 1 if x >= 0 else -1 + + +def mapmm(x: torch.Tensor) -> torch.Tensor: + minx = torch.min(x) + maxx = torch.max(x) + if minx < maxx: + x = (x - minx) / (maxx - minx) + return x + + +def fspecial(filter_type: str, p2: Union[int, Tuple[int, int]], p3: Union[int, float] = None) -> np.ndarray: + if filter_type == 'gaussian': + m, n = [(ss - 1.) / 2. for ss in p2] + y, x = np.ogrid[-m:m + 1, -n:n + 1] + h = np.exp(-(x * x + y * y) / (2. * p3 * p3)) + h[h < np.finfo(h.dtype).eps * h.max()] = 0 + sumh = h.sum() + if sumh != 0: + h /= sumh + + return h + + elif filter_type == 'disk': + rad = p2 + crad = math.ceil(rad - 0.5) + + x, y = np.ogrid[-rad: rad + 1, -rad: rad + 1] + y = np.tile(y.transpose(), y.shape[1]) + x = np.tile(x, x.shape[0]).transpose() + + y = np.abs(y) + x = np.abs(x) + + maxxy = np.maximum(x, y) + minxy = np.minimum(x, y) + + r1 = (rad ** 2 - (maxxy + 0.5) ** 2) + r2 = (rad ** 2 - (minxy - 0.5) ** 2) + + if (r1 > 0).all(): + warn_m1 = r1 ** 0.5 + else: + warn_m1 = 0 + if (r2 > 0).all(): + warn_m2 = r2 ** 0.5 + else: + warn_m2 = 0 + + m1 = (rad ** 2 < (maxxy + 0.5) ** 2 + (minxy - 0.5) ** 2) * (minxy - 0.5) + ( + rad ** 2 >= (maxxy + 0.5) ** 2 + (minxy - 0.5) ** 2) * warn_m1 + m2 = (rad ** 2 > (maxxy - 0.5) ** 2 + (minxy + 0.5) ** 2) * (minxy + 0.5) + ( + rad ** 2 <= (maxxy - 0.5) ** 2 + (minxy + 0.5) ** 2) * warn_m2 + + sgrid = (rad ** 2 * (0.5 * (np.arcsin(m2 / rad) - np.arcsin(m1 / rad)) + + 0.25 * (np.sin(2 * np.arcsin(m2 / rad)) - np.sin(2 * np.arcsin(m1 / rad)))) - ( + maxxy - 0.5) * (m2 - m1) + (m1 - minxy + 0.5)) * np.logical_or( + np.logical_and((rad ** 2 < (maxxy + 0.5) ** 2 + (minxy + 0.5) ** 2), + (rad ** 2 > (maxxy - 0.5) ** 2 + (minxy - 0.5) ** 2)), + np.logical_and(np.logical_and(minxy == 0, maxxy - 0.5 < rad), maxxy + 0.5 >= rad)) + + sgrid = sgrid + ((maxxy + 0.5) ** 2 + (minxy + 0.5) ** 2 < rad ** 2) + sgrid[crad, crad] = np.minimum(math.pi * rad ** 2, math.pi / 2) + if (crad > 0) and (rad > crad - 0.5) and (rad ** 2 < (crad - 0.5) ** 2 + 0.25): + m1 = np.sqrt(rad ** 2 - (crad - 0.5) ** 2) + m1n = m1 / rad + sg0 = 2 * (rad ** 2 * (0.5 * np.arcsin(m1n) + 0.25 * np.sin(2 * np.arcsin(m1n))) - m1 * (crad - 0.5)) + sgrid[2 * crad, crad] = sg0 + sgrid[crad, 2 * crad] = sg0 + sgrid[crad, 0] = sg0 + sgrid[0, crad] = sg0 + sgrid[2 * crad, crad] = sgrid[2 * crad, crad] - sg0 + sgrid[crad, 2 * crad] = sgrid[crad, 2 * crad] - sg0 + sgrid[crad, 2] = sgrid[crad, 2] - sg0 + sgrid[2, crad] = sgrid[2, crad + 1] - sg0 + + sgrid[crad, crad] = np.minimum(sgrid[crad, crad], 1) + h = sgrid / np.sum(sgrid) + return h + + else: + raise NotImplementedError(f"Filter type {filter_type} not implemented") + + +def filter2D(img: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor: + """PyTorch version of cv2.filter2D + Args: + img (Tensor): (b, c, h, w) + kernel (Tensor): (b, k, k) + """ + img = img.float() + k1 = kernel.size(-2) + k2 = kernel.size(-1) + + b, c, h, w = img.size() + if k1 % 2 == 1 or k2 % 2 == 1: + img = F.pad(img, (k2 // 2, k2 // 2, k1 // 2, k1 // 2), mode='replicate') + else: + raise ValueError('Wrong kernel size') + + ph, pw = img.size()[-2:] + + if kernel.size(0) == 1: + # apply the same kernel to all batch images + img = img.view(b * c, 1, ph, pw) + kernel = kernel.view(1, 1, k1, k2) + return F.conv2d(img, kernel, padding=0).view(b, c, h, w) + else: + img = img.view(1, b * c, ph, pw) + kernel = kernel.view(b, 1, k1, k2).repeat(1, c, 1, 1).view(b * c, 1, k1, k2) + return F.conv2d(img, kernel, groups=b * c).view(b, c, h, w) + + +def curves(xx: torch.Tensor, coef: float) -> torch.Tensor: + if type(coef) == list: + coef = [[0.3, 0.5, 0.7], + [coef[0], 0.5, coef[1]]] + else: + coef = [[0.5], [coef]] + + x = np.array([0] + [p for p in coef[0]] + [1]) + y = np.array([0] + [p for p in coef[1]] + [1]) + + cs = spline(x, y) + + yy = ppval(cs, xx) + + yy = torch.clamp(yy, 0, 1) + + return yy + + +def spline(x: np.ndarray, y: np.ndarray) -> np.ndarray: + n = x.shape[0] + dd = 1 + dx = np.diff(x) + divdif = np.diff(y) / dx + + if n == 3: + y[1:3] = divdif + y[2] = np.diff(divdif.T).T / (x[2] - x[0]) + y[1] -= y[2] * dx[0] + dlk = y[[2, 1, 0]].shape[0] + l = x[[0, 2]].shape[0] - 1 + dl = np.prod(dd) * l + k = np.fix(dlk / dl + 100 * 2.2204e-16) + + pp = (x[[0, 2]], y[[2, 1, 0]], l, int(k), dd) + + elif n > 3: + b = np.zeros(n) + b[1:n - 1] = 3 * (dx[1:n] * divdif[0:n - 2] + dx[0:n - 2] * divdif[1:n]) + + x31 = x[2] - x[0] + xn = x[n - 1] - x[n - 3] + + b[0] = ((dx[0] + 2 * x31) * dx[1] * divdif[0] + dx[0] ** 2 * divdif[1]) / x31 + b[n - 1] = (dx[n - 2] ** 2 * divdif[n - 3] + (2 * xn + dx[n - 2]) * dx[n - 3] * divdif[n - 2]) / xn; + + dxt = dx.T + c = np.zeros((3, 5)) + c[0, :] = [x31] + list(dxt[0:n - 2]) + [0] + c[1, :] = [dxt[1]] + list(2 * (dxt[1:n - 1] + dxt[0:n - 2])) + [dxt[n - 3]] + c[2, :] = [0] + list(dxt[1:n - 1]) + [xn] + + c = scipy.sparse.dia_matrix((c, [-1, 0, 1]), shape=(5, 5)) + c = scipy.sparse.csc_matrix(c) + ic = scipy.sparse.linalg.inv(c) + s = b * ic + + n = x.shape[0] + d = 1 + dxd = dx + + dzzdx = (divdif - s[0:n - 1]) / dxd + dzdxdx = (s[1:n] - divdif) / dxd + + coefs = np.vstack(((dzdxdx - dzzdx) / dxd, 2 * dzzdx - dzdxdx, s[0:n - 1], y[0:n - 1])).T + + pp = (x, coefs, x.shape[0], x.shape[0], d) + else: + raise ValueError('x.shape[0] must be >= 3') + + return pp + + +def ppval(pp: np.ndarray, xx: torch.Tensor) -> torch.Tensor: + lx = torch.numel(xx) + xs = xx.reshape(1, lx) + b, c, l, k, dd = pp + b = torch.as_tensor(b, device=xx.device) + ranges = b.clone() + ranges[0] = -torch.inf + ranges[-1] = torch.inf + index = histc(xs, ranges) + + xs = xs - b[index] + + c = torch.as_tensor(c, device=xx.device) + + if len(c.shape) == 1: + v = c[0] + for i in range(1, k): + v = xs * v + c[i] + else: + v = c[index, 0] + + for i in range(1, k - 1): + v = xs * v + c[index, i] + v = v.view(xx.shape) + return v + + +def histc(x: torch.Tensor, binranges: torch.Tensor) -> torch.Tensor: + indices = torch.bucketize(x, binranges) + return torch.remainder(indices, len(binranges)) - 1 + + +def imscatter(x: torch.Tensor, amount: float, iterations=1) -> torch.Tensor: + y = x + for i in range(iterations): + shiftmap = torch.randn((2, x.shape[1], x.shape[2]), device=x.device) * amount + + sy = shiftmap[0, :, :] + sx = shiftmap[1, :, :] + + m_sx = torch.ceil(torch.abs(torch.max(sx))).to(torch.int32) + m_sy = torch.ceil(torch.abs(torch.max(sy))).to(torch.int32) + + y = F.pad(y, (m_sy, m_sy), mode='replicate') + y = F.pad(y.transpose(2, 1), (m_sx, m_sx), mode='replicate').transpose(2, 1) + + sy = F.pad(sy, (m_sy, m_sy), mode='replicate') + sy = F.pad(sy.transpose(1, 0), (m_sx, m_sx), mode='replicate').transpose(1, 0) + sx = F.pad(sx, (m_sy, m_sy), mode='replicate') + sx = F.pad(sx.transpose(1, 0), (m_sx, m_sx), mode='replicate').transpose(1, 0) + + xx, yy = torch.as_tensor(np.mgrid[0:y.shape[1], 0:y.shape[2]], device=x.device) + + z = torch.zeros_like(y) + bx = (xx - sx) + by = (yy - sy) + for i in range(3): + j = bilinear_interpolate_torch(y[i, ...], by, bx) + z[i, :, :] = j + + y = z[:, m_sy:m_sy + x.shape[1], m_sx:m_sx + x.shape[2]] + return y + + +def bilinear_interpolate_torch(im: torch.Tensor, x: torch.Tensor, y: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: + dtype_long = torch.LongTensor + + x0 = torch.floor(x).type(dtype_long).to(im.device) + x1 = x0 + 1 + + y0 = torch.floor(y).type(dtype_long).to(im.device) + y1 = y0 + 1 + + x0 = torch.clamp(x0, 0, im.shape[1] - 1) + x1 = torch.clamp(x1, 0, im.shape[1] - 1) + y0 = torch.clamp(y0, 0, im.shape[0] - 1) + y1 = torch.clamp(y1, 0, im.shape[0] - 1) + + Ia = im[y0, x0] + Ib = im[y1, x0] + Ic = im[y0, x1] + Id = im[y1, x1] + + R1 = Ia * (x1 - x) / (x1 - x0 + eps) + Ic * (x - x0) / (x1 - x0 + eps) + R2 = Ib * (x1 - x) / (x1 - x0 + eps) + Id * (x - x0) / (x1 - x0 + eps) + P = R1 * (y1 - y) / (y1 - y0 + eps) + R2 * (y - y0) / (y1 - y0 + eps) + return P \ No newline at end of file diff --git a/detectors/ForensicConcept/upstream/codebooks/README.md b/detectors/ForensicConcept/upstream/codebooks/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b9392d2a228bb6680d90c81d8109f9021c7f2aae --- /dev/null +++ b/detectors/ForensicConcept/upstream/codebooks/README.md @@ -0,0 +1,13 @@ +# CLIP codebook + +`cleandift_codebook.npy` contains the raw cluster centers used by the +stage-2 CLIP detector in `configs/clip_codebook.yaml`. The model L2-normalizes +the centers at load time through `clip_codebook_l2: true`. + +- Shape: `200 x 1280` +- Dtype: `float32` +- SHA-256: `0a7cd9555750c5f08b1db0a5a2dc0d866ef195fcd05210bffe53b2c82cdc87ab` + +The stage-2 detector checkpoint stores the normalized matrix as the persistent +`codebook_head.codebook` buffer. The external raw centers are retained for +stage-2 training and for tracing how the injected codebook was produced. diff --git a/detectors/ForensicConcept/upstream/codebooks/cleandift_codebook.npy b/detectors/ForensicConcept/upstream/codebooks/cleandift_codebook.npy new file mode 100644 index 0000000000000000000000000000000000000000..b38ec13e2a67b15f44a576793d43257830a43a45 --- /dev/null +++ b/detectors/ForensicConcept/upstream/codebooks/cleandift_codebook.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a7cd9555750c5f08b1db0a5a2dc0d866ef195fcd05210bffe53b2c82cdc87ab +size 1024128 diff --git a/detectors/ForensicConcept/upstream/config_loader.py b/detectors/ForensicConcept/upstream/config_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..cb3b826a335a374805a83f8217f09e37955a8909 --- /dev/null +++ b/detectors/ForensicConcept/upstream/config_loader.py @@ -0,0 +1,619 @@ +""" +Configuration loader for AIGC Detection project. +Loads configuration from YAML files and provides easy access to parameters. +""" + +import yaml +import os +import argparse +from typing import Dict, Any, Optional + + +ROBUSTNESS_PRESETS = { + 'jpeg_q75': { + 'type': 'jpeg', + 'params': {'jpeg_quality': 75}, + }, + 'jpeg_q70': { + 'type': 'jpeg', + 'params': {'jpeg_quality': 70}, + }, + 'gaussian_blur_sigma1': { + 'type': 'gaussian_blur', + 'params': {'gaussian_blur_sigma': 1.0}, + }, + 'gaussian_blur_sigma2': { + 'type': 'gaussian_blur', + 'params': {'gaussian_blur_sigma': 2.0}, + }, + 'gaussian_noise_std01': { + 'type': 'gaussian_noise', + 'params': {'gaussian_noise_std': 0.1}, + }, + 'gaussian_noise_std02': { + 'type': 'gaussian_noise', + 'params': {'gaussian_noise_std': 0.2}, + }, + 'downsample_scale05': { + 'type': 'downsample', + 'params': {'downsample_scale': 0.5}, + }, + 'color_jitter_brightness02': { + 'type': 'color_jitter', + 'params': { + 'cj_brightness': 0.2, + 'cj_contrast': 0.0, + 'cj_saturation': 0.0, + 'cj_hue': 0.0, + }, + }, + 'color_jitter_contrast02': { + 'type': 'color_jitter', + 'params': { + 'cj_brightness': 0.0, + 'cj_contrast': 0.2, + 'cj_saturation': 0.0, + 'cj_hue': 0.0, + }, + }, +} + +ROBUSTNESS_PARAM_DEFAULTS = { + 'jpeg_quality': 75, + 'gaussian_blur_sigma': 1.0, + 'gaussian_noise_std': 0.1, + 'downsample_scale': 0.5, + 'cj_brightness': 0.0, + 'cj_contrast': 0.0, + 'cj_saturation': 0.0, + 'cj_hue': 0.0, +} + + +def _coerce_robustness_params(raw_params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + raw = dict(raw_params or {}) + return { + 'jpeg_quality': int(raw.get('jpeg_quality', ROBUSTNESS_PARAM_DEFAULTS['jpeg_quality']) or ROBUSTNESS_PARAM_DEFAULTS['jpeg_quality']), + 'gaussian_blur_sigma': float(raw.get('gaussian_blur_sigma', ROBUSTNESS_PARAM_DEFAULTS['gaussian_blur_sigma']) or ROBUSTNESS_PARAM_DEFAULTS['gaussian_blur_sigma']), + 'gaussian_noise_std': float(raw.get('gaussian_noise_std', ROBUSTNESS_PARAM_DEFAULTS['gaussian_noise_std']) or ROBUSTNESS_PARAM_DEFAULTS['gaussian_noise_std']), + 'downsample_scale': float(raw.get('downsample_scale', ROBUSTNESS_PARAM_DEFAULTS['downsample_scale']) or ROBUSTNESS_PARAM_DEFAULTS['downsample_scale']), + 'cj_brightness': float(raw.get('cj_brightness', ROBUSTNESS_PARAM_DEFAULTS['cj_brightness']) or ROBUSTNESS_PARAM_DEFAULTS['cj_brightness']), + 'cj_contrast': float(raw.get('cj_contrast', ROBUSTNESS_PARAM_DEFAULTS['cj_contrast']) or ROBUSTNESS_PARAM_DEFAULTS['cj_contrast']), + 'cj_saturation': float(raw.get('cj_saturation', ROBUSTNESS_PARAM_DEFAULTS['cj_saturation']) or ROBUSTNESS_PARAM_DEFAULTS['cj_saturation']), + 'cj_hue': float(raw.get('cj_hue', ROBUSTNESS_PARAM_DEFAULTS['cj_hue']) or ROBUSTNESS_PARAM_DEFAULTS['cj_hue']), + } + + +def _resolve_robustness_entry(entry: Optional[Dict[str, Any]]) -> Dict[str, Any]: + item = dict(entry or {}) + preset = str(item.get('preset', '') or '').strip().lower() + robustness_type = str(item.get('type', '') or '').strip().lower() + params = _coerce_robustness_params(item) + + if preset: + preset_cfg = ROBUSTNESS_PRESETS.get(preset) + if preset_cfg is None: + valid = ', '.join(sorted(ROBUSTNESS_PRESETS.keys())) + raise ValueError(f"Unknown testing.robustness.preset='{preset}'. Valid presets: {valid}") + robustness_type = preset_cfg['type'] + params.update(preset_cfg['params']) + + return { + 'preset': preset, + 'type': robustness_type, + 'params': params, + } + + +class ConfigLoader: + """ + Configuration loader that handles YAML configuration files. + """ + + def __init__(self, config_path: Optional[str] = None): + """ + Initialize the configuration loader. + + Args: + config_path: Path to the YAML configuration file + """ + self.config_path = config_path + self.config = {} + + if config_path: + self.load_config(config_path) + + def load_config(self, config_path: str) -> Dict[str, Any]: + """ + Load configuration from a YAML file. + + Args: + config_path: Path to the YAML configuration file + + Returns: + Dictionary containing the configuration + """ + if not os.path.exists(config_path): + raise FileNotFoundError(f"Configuration file not found: {config_path}") + + with open(config_path, 'r', encoding='utf-8') as f: + self.config = yaml.safe_load(f) + + return self.config + + def get(self, key: str, default: Any = None) -> Any: + """ + Get a configuration value using dot notation. + + Args: + key: Key in dot notation (e.g., 'data.train_dataroot') + default: Default value if key not found + + Returns: + Configuration value + """ + keys = key.split('.') + value = self.config + + for k in keys: + if isinstance(value, dict) and k in value: + value = value[k] + else: + return default + + return value + + def set(self, key: str, value: Any): + """ + Set a configuration value using dot notation. + + Args: + key: Key in dot notation (e.g., 'data.train_dataroot') + value: Value to set + """ + keys = key.split('.') + config = self.config + + for k in keys[:-1]: + if k not in config: + config[k] = {} + config = config[k] + + config[keys[-1]] = value + + def update_from_args(self, args: argparse.Namespace): + """ + Update configuration with command line arguments. + + Args: + args: Parsed command line arguments + """ + # Update paths if provided + if hasattr(args, 'train_dataroot') and args.train_dataroot: + self.set('data.train_dataroot', args.train_dataroot) + if hasattr(args, 'test_dataroot') and args.test_dataroot: + self.set('data.test_dataroot', args.test_dataroot) + if hasattr(args, 'checkpoints_dir') and args.checkpoints_dir: + self.set('models.checkpoints_dir', args.checkpoints_dir) + + # Update training parameters if provided + if hasattr(args, 'lr') and args.lr: + self.set('training.lr', args.lr) + if hasattr(args, 'batch_size') and args.batch_size: + self.set('training.batch_size', args.batch_size) + if hasattr(args, 'niter') and args.niter: + self.set('training.niter', args.niter) + if hasattr(args, 'gpu_ids') and args.gpu_ids: + self.set('training.gpu_ids', args.gpu_ids) + if hasattr(args, 'name') and args.name: + self.set('training.name', args.name) + + def get_testing_robustness(self) -> Dict[str, Any]: + """ + Resolve test-time robustness preprocessing from config. + + Supports either: + 1) `testing.robustness.preset` for one-click selection, or + 2) `testing.robustness.type` + explicit params, or + 3) `testing.robustness.chain` for sequential perturbations. + """ + robustness_cfg = self.get('testing.robustness', {}) or {} + if not isinstance(robustness_cfg, dict): + robustness_cfg = {} + chain_cfg = robustness_cfg.get('chain', self.get('testing.robustness_chain', [])) or [] + if not isinstance(chain_cfg, list): + raise ValueError("testing.robustness.chain must be a list of robustness entries.") + + resolved_chain = [] + for idx, entry in enumerate(chain_cfg): + if not isinstance(entry, dict): + raise ValueError(f"testing.robustness.chain[{idx}] must be a mapping.") + resolved = _resolve_robustness_entry(entry) + if not resolved['type']: + raise ValueError(f"testing.robustness.chain[{idx}] must define preset or type.") + resolved_chain.append(resolved) + + single_entry = _resolve_robustness_entry({ + 'preset': robustness_cfg.get('preset', self.get('testing.robustness_preset', '')), + 'type': robustness_cfg.get('type', self.get('testing.robustness_type', '')), + 'jpeg_quality': robustness_cfg.get('jpeg_quality', self.get('testing.robustness_jpeg_quality', ROBUSTNESS_PARAM_DEFAULTS['jpeg_quality'])), + 'gaussian_blur_sigma': robustness_cfg.get('gaussian_blur_sigma', self.get('testing.robustness_gaussian_blur_sigma', ROBUSTNESS_PARAM_DEFAULTS['gaussian_blur_sigma'])), + 'gaussian_noise_std': robustness_cfg.get('gaussian_noise_std', self.get('testing.robustness_gaussian_noise_std', ROBUSTNESS_PARAM_DEFAULTS['gaussian_noise_std'])), + 'downsample_scale': robustness_cfg.get('downsample_scale', self.get('testing.robustness_downsample_scale', ROBUSTNESS_PARAM_DEFAULTS['downsample_scale'])), + 'cj_brightness': robustness_cfg.get('cj_brightness', self.get('testing.robustness_cj_brightness', ROBUSTNESS_PARAM_DEFAULTS['cj_brightness'])), + 'cj_contrast': robustness_cfg.get('cj_contrast', self.get('testing.robustness_cj_contrast', ROBUSTNESS_PARAM_DEFAULTS['cj_contrast'])), + 'cj_saturation': robustness_cfg.get('cj_saturation', self.get('testing.robustness_cj_saturation', ROBUSTNESS_PARAM_DEFAULTS['cj_saturation'])), + 'cj_hue': robustness_cfg.get('cj_hue', self.get('testing.robustness_cj_hue', ROBUSTNESS_PARAM_DEFAULTS['cj_hue'])), + }) + + if resolved_chain: + primary = resolved_chain[0] + else: + primary = single_entry + + return { + 'preset': primary['preset'], + 'type': primary['type'], + 'params': primary['params'], + 'chain': resolved_chain, + } + + def create_directories(self): + """ + Create necessary directories based on configuration. + """ + # Create output directories + dirs_to_create = [self.get('models.checkpoints_dir')] + + for dir_path in dirs_to_create: + if dir_path: + os.makedirs(dir_path, exist_ok=True) + + def to_namespace(self, is_train: bool = True) -> argparse.Namespace: + """ + Convert configuration to argparse Namespace for compatibility. + + Returns: + Namespace containing all configuration parameters + """ + namespace = argparse.Namespace() + + # Set common parameters for compatibility with existing code + namespace.dataroot = self.get('data.train_dataroot') + extra_train_roots = self.get('data.extra_train_roots', []) + if isinstance(extra_train_roots, str): + extra_train_roots = [p.strip() for p in extra_train_roots.split(',') if p.strip()] + if extra_train_roots is None: + extra_train_roots = [] + namespace.extra_train_roots = list(extra_train_roots) + namespace.test_dataroot = self.get('data.test_dataroot') + namespace.train_split = self.get('data.train_split', 'train') + namespace.val_split = self.get('data.val_split', 'val') + namespace.checkpoints_dir = self.get('models.checkpoints_dir') + namespace.arch = self.get('training.arch', 'res50') + namespace.trainmode = self.get('training.trainmode', 'lora') + namespace.modelname = self.get('training.modelname', 'CLIP:ViT-L/14@336px') + namespace.lr = self.get('training.lr', 0.0001) + namespace.lr_decay_factor = self.get('training.lr_decay_factor', 0.9) + namespace.lr_min = self.get('training.lr_min', 1e-6) + namespace.weight_decay = self.get('training.weight_decay', 0.0) + namespace.max_grad_norm = self.get('training.max_grad_norm', 0.0) + namespace.lr_plateau_patience = self.get('training.lr_plateau_patience', 0) + namespace.lr_plateau_delta = self.get('training.lr_plateau_delta', 0.0) + namespace.lr_plateau_warmup = self.get('training.lr_plateau_warmup', 0) + namespace.batch_size = self.get('training.batch_size', 16) + namespace.niter = self.get('training.niter', 1000) + namespace.delr_freq = self.get('training.delr_freq', 20) + namespace.loss_freq = self.get('training.loss_freq', 400) + namespace.data_aug = self.get('training.data_aug', True) + namespace.use_testshift_like_aug = self.get('training.use_testshift_like_aug', False) + namespace.use_testshift_like_aug_eval = self.get('testing.use_testshift_like_aug_eval', False) + namespace.testshift_like_apply_prob = self.get('training.testshift_like_apply_prob', 1.0) + namespace.testshift_like_max_groups = self.get('training.testshift_like_max_groups', 3) + namespace.use_aug_utils_train = self.get('training.use_aug_utils_train', False) + namespace.aug_utils_prob = self.get('training.aug_utils_prob', 1.0) + namespace.aug_utils_max_distortions = self.get('training.aug_utils_max_distortions', 3) + namespace.aug_utils_num_levels = self.get('training.aug_utils_num_levels', 5) + namespace.augmix_js_enable = self.get('training.augmix_js_enable', False) + namespace.augmix_js_weight = self.get('training.augmix_js_weight', 12.0) + namespace.augmix_width = self.get('training.augmix_width', 3) + namespace.augmix_depth = self.get('training.augmix_depth', -1) + namespace.augmix_alpha = self.get('training.augmix_alpha', 1.0) + namespace.augmix_num_views = self.get('training.augmix_num_views', 2) + namespace.augmix_js_eps = self.get('training.augmix_js_eps', 1.0e-7) + namespace.loadSize = self.get('training.loadSize', 224) + namespace.cropSize = self.get('training.cropSize', 224) + namespace.gpu_ids = self.get('training.gpu_ids', '0') + namespace.name = self.get('training.name', 'AIGC_Detection') + namespace.resume_name = self.get('training.resume_name', None) + + namespace.freeze_backbone = self.get('training.freeze_backbone', True) + namespace.trainable_blocks = self.get('training.trainable_blocks', 0) + namespace.head_hidden_dim = self.get('training.head_hidden_dim', None) + namespace.head_dropout = self.get('training.head_dropout', 0.1) + namespace.use_lora = self.get('training.use_lora', False) + namespace.lora_rank = self.get('training.lora_rank', 4) + namespace.lora_alpha = self.get('training.lora_alpha', 8) + namespace.lora_dropout = self.get('training.lora_dropout', 0.0) + namespace.lora_bias = self.get('training.lora_bias', 'none') + target_modules = self.get('training.lora_target_modules', None) + if isinstance(target_modules, str): + target_modules = [m.strip() for m in target_modules.split(',') if m.strip()] + namespace.lora_target_modules = target_modules + namespace.lora_target_last_n = self.get('training.lora_target_last_n', None) + + namespace.dinov3_variant = self.get('training.dinov3_variant', 'vitl16') + namespace.dinov3_backend = self.get('training.dinov3_backend', 'official') + namespace.dinov3_repo_path = self.get('training.dinov3_repo_path', None) + namespace.dinov3_max_blocks = self.get('training.dinov3_max_blocks', None) + namespace.dinov3_weights = self.get('training.dinov3_weights', None) + namespace.dinov3_disable_rope_train_jitter = self.get( + 'training.dinov3_disable_rope_train_jitter', + False, + ) + namespace.dinov3_accel_backend = self.get('training.dinov3_accel_backend', 'none') + namespace.dinov3_accel_compile = self.get('training.dinov3_accel_compile', False) + namespace.dinov3_accel_checkpointing = self.get('training.dinov3_accel_checkpointing', True) + namespace.dinov3_accel_checkpointing_full = self.get('training.dinov3_accel_checkpointing_full', False) + namespace.dinov3_accel_cudagraphs = self.get('training.dinov3_accel_cudagraphs', False) + namespace.dinov3_accel_preserve_loaded_weights = self.get( + 'training.dinov3_accel_preserve_loaded_weights', + True, + ) + namespace.dinov3_accel_param_dtype = self.get('training.dinov3_accel_param_dtype', None) + namespace.dinov3_accel_reduce_dtype = self.get('training.dinov3_accel_reduce_dtype', None) + namespace.deepspeed_config_path = self.get('training.deepspeed_config_path', None) + namespace.deepspeed_zero_stage = self.get('training.deepspeed_zero_stage', 2) + namespace.deepspeed_grad_accum_steps = self.get('training.deepspeed_grad_accum_steps', None) + namespace.deepspeed_offload_optimizer_device = self.get( + 'training.deepspeed_offload_optimizer_device', 'none' + ) + namespace.deepspeed_offload_param_device = self.get('training.deepspeed_offload_param_device', 'none') + namespace.full_finetune_enable = self.get('training.full_finetune_enable', False) + namespace.full_finetune_precision = self.get('training.full_finetune_precision', 'fp32') + namespace.full_finetune_grad_accum_steps = self.get('training.full_finetune_grad_accum_steps', 1) + namespace.full_finetune_gradient_checkpointing = self.get( + 'training.full_finetune_gradient_checkpointing', + False, + ) + namespace.dinov3_use_concept_head = self.get('training.dinov3_use_concept_head', False) + namespace.dinov3_concept_matrix_path = self.get('training.dinov3_concept_matrix_path', None) + namespace.dinov3_concept_mapping_trainable = self.get('training.dinov3_concept_mapping_trainable', False) + namespace.dinov3_concept_mapping_bias = self.get('training.dinov3_concept_mapping_bias', False) + namespace.dinov3_concept_head_hidden_dim = self.get('training.dinov3_concept_head_hidden_dim', None) + namespace.dinov3_concept_head_dropout = self.get('training.dinov3_concept_head_dropout', None) + namespace.dinov3_concept_sparsity_ratio = self.get('training.dinov3_concept_sparsity_ratio', 0.0) + concept_eval = self.get('training.dinov3_concept_eval_sparsity', None) + if isinstance(concept_eval, str): + items = [item.strip() for item in concept_eval.split(',') if item.strip()] + concept_eval = [float(item) for item in items] + namespace.dinov3_concept_eval_sparsity = concept_eval + namespace.dinov3_concept_eval_log_path = self.get('training.dinov3_concept_eval_log_path', None) + # CLIP options (CLS + codebook top-k head) + namespace.clip_use_main_head = self.get('training.clip_use_main_head', True) + namespace.clip_codebook_path = self.get('training.clip_codebook_path', None) + namespace.clip_use_codebook_inject = self.get('training.clip_use_codebook_inject', True) + namespace.clip_codebook_dim = self.get('training.clip_codebook_dim', 1280) + namespace.clip_num_concepts = self.get('training.clip_num_concepts', 200) + namespace.clip_tau = self.get('training.clip_tau', 0.1) + namespace.clip_codebook_l2 = self.get('training.clip_codebook_l2', True) + namespace.clip_freeze_codebook = self.get('training.clip_freeze_codebook', True) + namespace.clip_override_codebook = self.get('training.clip_override_codebook', False) + namespace.clip_num_patches = self.get('training.clip_num_patches', None) + namespace.clip_cb_topk = self.get('training.clip_cb_topk', 20) + namespace.clip_cb_topr = self.get('training.clip_cb_topr', 8) + namespace.clip_cb_tau_w = self.get('training.clip_cb_tau_w', 0.1) + namespace.clip_cb_weight_mode = self.get('training.clip_cb_weight_mode', 'score') + namespace.clip_cb_mlp_hidden = self.get('training.clip_cb_mlp_hidden', None) + namespace.clip_cb_detach_tokens = self.get('training.clip_cb_detach_tokens', False) + namespace.clip_train_lora = self.get('training.clip_train_lora', True) + namespace.clip_train_fc = self.get('training.clip_train_fc', True) + namespace.clip_load_init_weights = self.get('training.clip_load_init_weights', True) + namespace.clip_cb_loss_weight = self.get('training.clip_cb_loss_weight', 1.0) + concept_loss = self.get('training.dinov3_concept_loss_weight', 1.0) + namespace.dinov3_concept_loss_weight = concept_loss + namespace.initial_eval = self.get('training.initial_eval', False) + namespace.clip_lora_rank = self.get('training.clip_lora_rank', 4) + namespace.clip_lora_alpha = self.get('training.clip_lora_alpha', 8) + namespace.clip_freeze_backbone = self.get('training.clip_freeze_backbone', True) + namespace.clip_model_path = self.get('models.pretrained.clip_model', None) + namespace.num_threads = self.get('system.num_threads', 8) + namespace.classes = "" + namespace.isTrain = bool(is_train) + namespace.pos_weight = self.get('training.pos_weight', None) + namespace.num_classes = self.get('training.num_classes', 1) + namespace.reverse = self.get('training.reverse', False) + namespace.save_backbone = self.get('training.save_backbone', False) + + # Add missing parameters from base_options.py + namespace.mode = self.get('training.mode', 'binary') + namespace.class_bal = self.get('training.class_bal', False) + namespace.class_bal_strategy = self.get('training.class_bal_strategy', 'auto') + namespace.class_bal_strict = self.get('training.class_bal_strict', False) + namespace.serial_batches = self.get('training.serial_batches', False) + namespace.resize_or_crop = self.get('training.resize_or_crop', 'scale_and_crop') + namespace.no_flip = self.get('training.no_flip', False) + namespace.init_type = self.get('training.init_type', 'normal') + namespace.init_gain = self.get('training.init_gain', 0.02) + namespace.suffix = self.get('training.suffix', '') + namespace.epoch = self.get('training.epoch', 'latest') + + # Data augmentation parameters + namespace.rz_interp = self.get('training.rz_interp', 'bilinear') + namespace.blur_prob = self.get('training.blur_prob', 0.0) + namespace.blur_sig = self.get('training.blur_sig', '0.5') + namespace.jpg_prob = self.get('training.jpg_prob', 0.0) + namespace.jpg_method = self.get('training.jpg_method', 'cv2') + namespace.jpg_qual = self.get('training.jpg_qual', '75') + # ๅ…ผๅฎน legacy ้ข„ๅค„็†๏ผˆๅฏน้ฝ NPR๏ผšresize -> crop -> ImageNet ๅฝ’ไธ€ๅŒ–๏ผ‰ + namespace.legacy_preprocess = self.get('training.legacy_preprocess', False) + + # Testing parameters from test_options.py + namespace.model_path = self.get('testing.model_path', '') + namespace.no_resize = self.get('training.no_resize', False) + namespace.no_crop = self.get('testing.no_crop', False) + namespace.eval = self.get('testing.eval', False) + namespace.earlystop_epoch = self.get('training.earlystop_epoch', 15) + # Optional: dump codebook top-k patch coords during testing + namespace.codebook_coords_path = self.get('testing.codebook_coords_path', None) + namespace.codebook_coords_limit = self.get('testing.codebook_coords_limit', None) + robustness_cfg = self.get_testing_robustness() + namespace.robustness_preset = robustness_cfg['preset'] + namespace.robustness_type = robustness_cfg['type'] + namespace.robustness_chain = robustness_cfg['chain'] + namespace.robustness_jpeg_quality = robustness_cfg['params']['jpeg_quality'] + namespace.robustness_gaussian_blur_sigma = robustness_cfg['params']['gaussian_blur_sigma'] + namespace.robustness_gaussian_noise_std = robustness_cfg['params']['gaussian_noise_std'] + namespace.robustness_downsample_scale = robustness_cfg['params']['downsample_scale'] + namespace.robustness_cj_brightness = robustness_cfg['params']['cj_brightness'] + namespace.robustness_cj_contrast = robustness_cfg['params']['cj_contrast'] + namespace.robustness_cj_saturation = robustness_cfg['params']['cj_saturation'] + namespace.robustness_cj_hue = robustness_cfg['params']['cj_hue'] + + # Training parameters from train_options.py + namespace.optim = self.get('training.optim', 'adam') + namespace.new_optim = self.get('training.new_optim', False) + namespace.save_latest_freq = self.get('training.save_latest_freq', 2000) + namespace.save_epoch_freq = self.get('training.save_epoch_freq', 20) + namespace.continue_train = self.get('training.continue_train', False) + namespace.epoch_count = self.get('training.epoch_count', 1) + namespace.last_epoch = self.get('training.last_epoch', -1) + namespace.beta1 = self.get('training.beta1', 0.9) + + def flatten_config(config, parent_key=''): + items = [] + for k, v in config.items(): + new_key = f"{parent_key}_{k}" if parent_key else k + if isinstance(v, dict): + items.extend(flatten_config(v, new_key).items()) + else: + items.append((new_key, v)) + return dict(items) + + flat_config = flatten_config(self.config) + + # Add all flattened config items + for k, v in flat_config.items(): + setattr(namespace, k, v) + + return namespace + + def save_config(self, output_path: str): + """ + Save current configuration to a YAML file. + + Args: + output_path: Path to save the configuration file + """ + with open(output_path, 'w', encoding='utf-8') as f: + yaml.dump(self.config, f, default_flow_style=False, allow_unicode=True) + + def print_config(self): + """ + Print the current configuration in a formatted way. + """ + print("=" * 80) + print("Configuration:") + print("=" * 80) + + def print_dict(d, indent=0): + for k, v in d.items(): + if isinstance(v, dict): + print(" " * indent + f"{k}:") + print_dict(v, indent + 1) + else: + print(" " * indent + f"{k}: {v}") + + print_dict(self.config) + print("=" * 80) + + +def create_argument_parser(): + """ + Create argument parser for command line interface. + + Returns: + ArgumentParser object + """ + parser = argparse.ArgumentParser( + description="AIGC Detection Training with Configuration File Support", + formatter_class=argparse.ArgumentDefaultsHelpFormatter + ) + + # Configuration file + parser.add_argument( + '--config', + type=str, + default='config.yaml', + help='Path to configuration file' + ) + + # Override options + parser.add_argument( + '--train_dataroot', + type=str, + help='Training data directory (overrides config)' + ) + parser.add_argument( + '--test_dataroot', + type=str, + help='Test data directory (overrides config)' + ) + parser.add_argument( + '--checkpoints_dir', + type=str, + help='Checkpoints directory (overrides config)' + ) + parser.add_argument( + '--lr', + type=float, + help='Learning rate (overrides config)' + ) + parser.add_argument( + '--batch_size', + type=int, + help='Batch size (overrides config)' + ) + parser.add_argument( + '--niter', + type=int, + help='Number of iterations (overrides config)' + ) + parser.add_argument( + '--gpu_ids', + type=str, + help='GPU IDs (overrides config)' + ) + parser.add_argument( + '--name', + type=str, + help='Experiment name (overrides config)' + ) + + return parser + + +def load_config_from_args(args: argparse.Namespace) -> ConfigLoader: + """ + Load configuration from command line arguments. + + Args: + args: Parsed command line arguments + + Returns: + ConfigLoader instance + """ + config_loader = ConfigLoader(args.config) + config_loader.update_from_args(args) + config_loader.create_directories() + + return config_loader + + +if __name__ == "__main__": + # Test the configuration loader + parser = create_argument_parser() + args = parser.parse_args() + + config_loader = load_config_from_args(args) + config_loader.print_config() diff --git a/detectors/ForensicConcept/upstream/configs/clip_codebook.yaml b/detectors/ForensicConcept/upstream/configs/clip_codebook.yaml new file mode 100644 index 0000000000000000000000000000000000000000..92de3dcea779a9385c20a95ad4e3809618aaf77e --- /dev/null +++ b/detectors/ForensicConcept/upstream/configs/clip_codebook.yaml @@ -0,0 +1,85 @@ +# Stage 2: initialize from the stage-1 CLIP-LoRA detector and train the +# patch-token codebook branch. The released raw centers are L2-normalized at load time. +data: + train_dataroot: "./datasets" + train_split: "train" + test_dataroot: "./datasets/test" + val_split: "val" + +models: + checkpoints_dir: "./checkpoints" + pretrained: + clip_model: "./weights/backbones/ViT-L-14.pt" + +training: + trainmode: "lora" + modelname: "CLIP:ViT-L/14" + clip_use_main_head: true + clip_train_fc: true + clip_train_lora: false + clip_lora_rank: 4 + clip_lora_alpha: 8 + clip_freeze_backbone: true + clip_load_init_weights: true + + clip_use_codebook_inject: true + clip_codebook_path: "./assets/codebooks/cleandift_codebook.npy" + clip_codebook_dim: 1280 + clip_num_concepts: 200 + clip_tau: 0.1 + clip_codebook_l2: true + clip_freeze_codebook: true + clip_cb_loss_weight: 1.0 + clip_num_patches: 256 + clip_cb_topk: 20 + clip_cb_topr: 8 + clip_cb_tau_w: 0.05 + clip_cb_weight_mode: "score" + clip_cb_mlp_hidden: 768 + clip_cb_detach_tokens: true + + num_classes: 1 + legacy_preprocess: true + optim: "adam" + beta1: 0.9 + weight_decay: 0.0 + lr: 0.00002 + lr_decay_factor: 0.9 + lr_min: 0.000001 + batch_size: 32 + niter: 2 + delr_freq: 5 + loss_freq: 100 + + data_aug: true + loadSize: 224 + cropSize: 224 + class_bal: false + serial_batches: false + + seed: 100 + gpu_ids: "0" + name: "clip_vitl14_codebook_stage2" + initial_eval: false + continue_train: true + epoch: "./weights/detectors/clip_vitl14_lora_stage1.pth" + new_optim: true + save_last_checkpoint: true + +testing: + batch_size: 64 + data_aug: false + no_resize: false + no_crop: false + groups: + - name: "example_test" + path: "./datasets/test/example" + mode: "single" + +logging: + tensorboard: true + log_file: "training.log" + print_options: true + +system: + num_threads: 8 diff --git a/detectors/ForensicConcept/upstream/configs/clip_lora.yaml b/detectors/ForensicConcept/upstream/configs/clip_lora.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0303c2eb6d345d158f597e3518ac5babef4514ff --- /dev/null +++ b/detectors/ForensicConcept/upstream/configs/clip_lora.yaml @@ -0,0 +1,68 @@ +# Stage 1: train the CLIP ViT-L/14 classifier and visual qkv LoRA adapters. +data: + train_dataroot: "./datasets" + train_split: "train" + test_dataroot: "./datasets/test" + val_split: "val" + +models: + checkpoints_dir: "./checkpoints" + pretrained: + clip_model: "./weights/backbones/ViT-L-14.pt" + +training: + trainmode: "lora" + modelname: "CLIP:ViT-L/14" + clip_use_main_head: true + clip_train_fc: true + clip_train_lora: true + clip_lora_rank: 4 + clip_lora_alpha: 8 + clip_freeze_backbone: true + clip_load_init_weights: true + clip_use_codebook_inject: false + + num_classes: 1 + legacy_preprocess: true + optim: "adam" + beta1: 0.9 + weight_decay: 0.0 + lr: 0.00002 + lr_decay_factor: 0.9 + lr_min: 0.000001 + batch_size: 32 + niter: 98 + delr_freq: 10 + loss_freq: 100 + + data_aug: true + loadSize: 224 + cropSize: 224 + class_bal: false + serial_batches: false + + seed: 100 + gpu_ids: "0" + name: "clip_vitl14_lora_stage1" + initial_eval: true + continue_train: false + epoch: "latest" + save_last_checkpoint: true + +testing: + batch_size: 64 + data_aug: false + no_resize: false + no_crop: false + groups: + - name: "example_test" + path: "./datasets/test/example" + mode: "single" + +logging: + tensorboard: true + log_file: "training.log" + print_options: true + +system: + num_threads: 8 diff --git a/detectors/ForensicConcept/upstream/configs/dinov3_concept.yaml b/detectors/ForensicConcept/upstream/configs/dinov3_concept.yaml new file mode 100644 index 0000000000000000000000000000000000000000..969a982c1012b569489a8b425b3247f74af5d24a --- /dev/null +++ b/detectors/ForensicConcept/upstream/configs/dinov3_concept.yaml @@ -0,0 +1,88 @@ +# DINOv3 LoRA with the concept head used by the core method. +# Replace dataset, backbone weight, and concept matrix paths before running. +data: + train_dataroot: "./datasets" + train_split: "train" + test_dataroot: "./datasets/test" + val_split: "val" + +models: + checkpoints_dir: "./checkpoints" + +training: + trainmode: "dinov3" + dinov3_variant: "vitl16" + dinov3_backend: "official" + dinov3_repo_path: "./external/dinov3" + dinov3_weights: "./weights/backbones/dinov3-vitl16/model.safetensors" + dinov3_accel_backend: "none" + + freeze_backbone: true + trainable_blocks: 0 + head_hidden_dim: 512 + head_dropout: 0.2 + use_lora: true + lora_rank: 4 + lora_alpha: 8 + lora_dropout: 0.0 + lora_bias: "none" + lora_target_modules: [] + lora_target_last_n: + + dinov3_use_concept_head: true + dinov3_concept_matrix_path: "./weights/concepts/dinov3_concept_matrix.npy" + dinov3_concept_mapping_trainable: true + dinov3_concept_mapping_bias: false + dinov3_concept_head_hidden_dim: + dinov3_concept_head_dropout: 0.0 + dinov3_concept_sparsity_ratio: 0.0 + dinov3_concept_loss_weight: 1.0 + dinov3_concept_eval_sparsity: [0.1, 0.3, 0.5, 0.7, 0.9] + + num_classes: 1 + optim: "adam" + beta1: 0.9 + weight_decay: 0.0 + lr: 0.00002 + lr_decay_factor: 0.9 + lr_min: 0.000001 + batch_size: 32 + niter: 5 + delr_freq: 5 + loss_freq: 100 + + data_aug: true + no_resize: false + no_flip: false + loadSize: 224 + cropSize: 224 + class_bal: false + serial_batches: false + + seed: 100 + gpu_ids: "0" + name: "dinov3_vitl16_concept_stage2" + initial_eval: false + continue_train: true + epoch: "./weights/detectors/dinov3_vitl16_lora_stage1.pth" + new_optim: true + save_last_checkpoint: true + +testing: + batch_size: 64 + data_aug: false + no_resize: false + no_crop: false + groups: + - name: "example_test" + path: "./datasets/test/example" + mode: "single" + +logging: + tensorboard: true + log_file: "training.log" + print_options: true + +system: + num_threads: 8 + ddp_timeout_minutes: 180 diff --git a/detectors/ForensicConcept/upstream/configs/dinov3_lora.yaml b/detectors/ForensicConcept/upstream/configs/dinov3_lora.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd9014a81239bb2bd7f347c36fbcb216f41323ae --- /dev/null +++ b/detectors/ForensicConcept/upstream/configs/dinov3_lora.yaml @@ -0,0 +1,76 @@ +# Reproduction template. Replace dataset and weight paths before running. +data: + train_dataroot: "./datasets" + train_split: "train" + test_dataroot: "./datasets/test" + val_split: "val" + +models: + checkpoints_dir: "./checkpoints" + +training: + trainmode: "dinov3" + dinov3_variant: "vitl16" + dinov3_backend: "official" + dinov3_repo_path: "./external/dinov3" + dinov3_weights: "./weights/backbones/dinov3-vitl16/model.safetensors" + dinov3_accel_backend: "none" + + freeze_backbone: true + trainable_blocks: 0 + head_hidden_dim: 512 + head_dropout: 0.2 + use_lora: true + lora_rank: 4 + lora_alpha: 8 + lora_dropout: 0.0 + lora_bias: "none" + lora_target_modules: [] + lora_target_last_n: + + num_classes: 1 + optim: "adam" + beta1: 0.9 + weight_decay: 0.0 + lr: 0.0001 + lr_decay_factor: 0.9 + lr_min: 0.000001 + batch_size: 32 + niter: 10 + delr_freq: 5 + loss_freq: 100 + + data_aug: true + no_resize: false + no_flip: false + loadSize: 224 + cropSize: 224 + class_bal: false + serial_batches: false + + seed: 100 + gpu_ids: "0" + name: "dinov3_vitl16_lora_stage1" + initial_eval: false + continue_train: false + epoch: "latest" + save_last_checkpoint: true + +testing: + batch_size: 64 + data_aug: false + no_resize: false + no_crop: false + groups: + - name: "example_test" + path: "./datasets/test/example" + mode: "single" + +logging: + tensorboard: true + log_file: "training.log" + print_options: true + +system: + num_threads: 8 + ddp_timeout_minutes: 180 diff --git a/detectors/ForensicConcept/upstream/data/__init__.py b/detectors/ForensicConcept/upstream/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d318495fb7c453d8c6e084c09973091a396f0ba2 --- /dev/null +++ b/detectors/ForensicConcept/upstream/data/__init__.py @@ -0,0 +1,580 @@ +import torch +import numpy as np +from torch.utils.data.sampler import WeightedRandomSampler +from torch.utils.data import Sampler +import math + +from .datasets import dataset_folder, infer_single_label_from_root, is_dfdc_train_faces_root + +''' +def get_dataset(opt): + dset_lst = [] + for cls in opt.classes: + root = opt.dataroot + '/' + cls + dset = dataset_folder(opt, root) + dset_lst.append(dset) + return torch.utils.data.ConcatDataset(dset_lst) +''' + +def _build_dataset_from_root(opt, root): + import os + if not root or not os.path.exists(root): + raise FileNotFoundError(f"Training dataroot not found: {root}") + + if infer_single_label_from_root(root) is not None: + return dataset_folder(opt, root) + if is_dfdc_train_faces_root(root, opt): + return dataset_folder(opt, root) + + if len(opt.classes) == 0: + classes = [ + cls for cls in os.listdir(root) + if not cls.startswith('.') and os.path.isdir(os.path.join(root, cls)) + ] + else: + classes = opt.classes + + class_set = set(classes) + has_standard_binary = {'0_real', '1_fake'}.issubset(class_set) + has_reversed_binary = {'0_fake', '1_real'}.issubset(class_set) + has_raw_synthesis = {'raw', 'synthesis'}.issubset(class_set) + has_real_fake = {'real', 'fake'}.issubset(class_set) + + if not (has_standard_binary or has_reversed_binary or has_raw_synthesis or has_real_fake): + dset_lst = [] + for cls in classes: + sub_root = os.path.join(root, cls) + if not os.path.isdir(sub_root): + continue + dset = dataset_folder(opt, sub_root) + dset_lst.append(dset) + if not dset_lst: + # Fallback for flat-labeled folders or alternative binary aliases + # handled inside data/datasets.py binary_dataset. + return dataset_folder(opt, root) + return torch.utils.data.ConcatDataset(dset_lst) + return dataset_folder(opt, root) + + +def _coerce_bool(value, default=False): + if value is None: + return bool(default) + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return bool(value) + if isinstance(value, str): + v = value.strip().lower() + if v in {"1", "true", "yes", "y", "on"}: + return True + if v in {"0", "false", "no", "n", "off"}: + return False + return bool(value) + + +def _get_first_opt(opt, names, default=None): + for name in names: + if hasattr(opt, name): + value = getattr(opt, name) + if value is not None: + return value + return default + + +class DynamicExtraSamplingDataset(torch.utils.data.Dataset): + """ + Dataset wrapper for: main dataset + per-epoch sampled subset from external pools. + + Typical use: + - main: training_data_final + - extra: FFPP/CelebDF/DFDC pools + - each epoch: sample len(main) items from extra (optionally 1:1 real/fake) + """ + + def __init__( + self, + main_dataset, + extra_dataset, + *, + match_main_count=True, + balance_binary=True, + seed=0, + log_first_n_epochs=0, + ): + self.main_dataset = main_dataset + self.extra_dataset = extra_dataset + self.main_len = int(len(main_dataset)) + self.extra_len = int(len(extra_dataset)) + self.match_main_count = bool(match_main_count) + self.balance_binary = bool(balance_binary) + self.seed = int(seed) + self.log_first_n_epochs = max(0, int(log_first_n_epochs)) + self.current_epoch = 0 + + self.sample_extra_count = self.main_len if self.match_main_count else self.extra_len + self._all_extra_indices = torch.arange(self.extra_len, dtype=torch.long) + self._sampled_extra_indices = torch.empty(0, dtype=torch.long) + self._sampled_extra_targets = [] + + try: + self._main_targets = [int(t) for t in _collect_targets(self.main_dataset)] + except Exception: + self._main_targets = None + try: + self._extra_targets = [int(t) for t in _collect_targets(self.extra_dataset)] + except Exception: + self._extra_targets = None + + self._extra_has_binary_targets = False + self._extra_real_pool = torch.empty(0, dtype=torch.long) + self._extra_fake_pool = torch.empty(0, dtype=torch.long) + if self._extra_targets is not None and len(self._extra_targets) == self.extra_len: + real_idx = [i for i, t in enumerate(self._extra_targets) if int(t) == 0] + fake_idx = [i for i, t in enumerate(self._extra_targets) if int(t) == 1] + if real_idx and fake_idx: + self._extra_has_binary_targets = True + self._extra_real_pool = torch.as_tensor(real_idx, dtype=torch.long) + self._extra_fake_pool = torch.as_tensor(fake_idx, dtype=torch.long) + + self.set_epoch(0) + + @staticmethod + def _sample_pool(pool, n, generator): + if n <= 0: + return torch.empty(0, dtype=torch.long) + m = int(pool.numel()) + if m <= 0: + return torch.empty(0, dtype=torch.long) + if m >= n: + perm = torch.randperm(m, generator=generator)[:n] + return pool[perm] + choice = torch.randint(low=0, high=m, size=(n,), generator=generator) + return pool[choice] + + def _sample_extra_indices_for_epoch(self, epoch): + if self.extra_len <= 0 or self.sample_extra_count <= 0: + return torch.empty(0, dtype=torch.long) + + g = torch.Generator() + g.manual_seed(self.seed + int(epoch)) + n = int(self.sample_extra_count) + + if self.balance_binary and self._extra_has_binary_targets: + n_real = n // 2 + n_fake = n - n_real + real_pick = self._sample_pool(self._extra_real_pool, n_real, g) + fake_pick = self._sample_pool(self._extra_fake_pool, n_fake, g) + sampled = torch.cat([real_pick, fake_pick], dim=0) + if sampled.numel() > 1: + order = torch.randperm(sampled.numel(), generator=g) + sampled = sampled[order] + return sampled + + if self.extra_len >= n: + perm = torch.randperm(self.extra_len, generator=g)[:n] + return self._all_extra_indices[perm] + choice = torch.randint(low=0, high=self.extra_len, size=(n,), generator=g) + return self._all_extra_indices[choice] + + def set_epoch(self, epoch): + self.current_epoch = int(epoch) + self._sampled_extra_indices = self._sample_extra_indices_for_epoch(self.current_epoch) + + if self._extra_targets is not None and len(self._extra_targets) == self.extra_len: + self._sampled_extra_targets = [ + int(self._extra_targets[int(i)]) for i in self._sampled_extra_indices.tolist() + ] + else: + self._sampled_extra_targets = [] + + if self.log_first_n_epochs > 0 and self.current_epoch < self.log_first_n_epochs: + n_main = self.main_len + n_extra = int(self._sampled_extra_indices.numel()) + if self._sampled_extra_targets: + extra_real = sum(1 for t in self._sampled_extra_targets if t == 0) + extra_fake = n_extra - extra_real + print( + f"[DataMix] epoch={self.current_epoch} main={n_main}, " + f"sampled_extra={n_extra} (real={extra_real}, fake={extra_fake})" + ) + else: + print( + f"[DataMix] epoch={self.current_epoch} main={n_main}, " + f"sampled_extra={n_extra}" + ) + + @property + def targets(self): + if self._main_targets is None or self._extra_targets is None: + raise AttributeError("DynamicExtraSamplingDataset has no stable targets metadata") + return list(self._main_targets) + list(self._sampled_extra_targets) + + def __len__(self): + return self.main_len + int(self._sampled_extra_indices.numel()) + + def __getitem__(self, index): + idx = int(index) + if idx < self.main_len: + return self.main_dataset[idx] + extra_idx = int(self._sampled_extra_indices[idx - self.main_len].item()) + return self.extra_dataset[extra_idx] + + +def get_dataset(opt): + import os + + extra_roots = getattr(opt, "extra_train_roots", None) or [] + if isinstance(extra_roots, str): + extra_roots = [p.strip() for p in extra_roots.split(",") if p.strip()] + + dynamic_sampling_enabled = _coerce_bool( + _get_first_opt( + opt, + [ + "dynamic_extra_sampling_enable", + "data_dynamic_extra_sampling_enable", + ], + False, + ), + default=False, + ) + dynamic_match_main_count = _coerce_bool( + _get_first_opt( + opt, + [ + "dynamic_extra_sampling_match_main_count", + "data_dynamic_extra_sampling_match_main_count", + ], + True, + ), + default=True, + ) + dynamic_balance_binary = _coerce_bool( + _get_first_opt( + opt, + [ + "dynamic_extra_sampling_balance_binary", + "data_dynamic_extra_sampling_balance_binary", + ], + True, + ), + default=True, + ) + dynamic_seed = int( + _get_first_opt( + opt, + [ + "dynamic_extra_sampling_seed", + "data_dynamic_extra_sampling_seed", + "seed", + ], + 0, + ) + ) + dynamic_log_first_n_epochs = int( + _get_first_opt( + opt, + [ + "dynamic_extra_sampling_log_first_n_epochs", + "data_dynamic_extra_sampling_log_first_n_epochs", + ], + 0, + ) + ) + + if bool(getattr(opt, "isTrain", False)) and dynamic_sampling_enabled and extra_roots: + main_root = os.path.abspath(opt.dataroot) + main_dataset = _build_dataset_from_root(opt, main_root) + + unique_extra_roots = [] + seen_extra = set() + for r in extra_roots: + if not r: + continue + r_abs = os.path.abspath(r) + if r_abs == main_root: + continue + if r_abs in seen_extra: + continue + seen_extra.add(r_abs) + unique_extra_roots.append(r_abs) + + extra_datasets = [_build_dataset_from_root(opt, root) for root in unique_extra_roots] + if not extra_datasets: + return main_dataset + + extra_dataset = extra_datasets[0] + if len(extra_datasets) > 1: + extra_dataset = torch.utils.data.ConcatDataset(extra_datasets) + + mixed_dataset = DynamicExtraSamplingDataset( + main_dataset, + extra_dataset, + match_main_count=dynamic_match_main_count, + balance_binary=dynamic_balance_binary, + seed=dynamic_seed, + log_first_n_epochs=dynamic_log_first_n_epochs, + ) + return mixed_dataset + + roots = [opt.dataroot] + roots.extend(extra_roots) + + unique_roots = [] + seen = set() + for r in roots: + if not r: + continue + r_abs = os.path.abspath(r) + if r_abs in seen: + continue + seen.add(r_abs) + unique_roots.append(r_abs) + + datasets_all = [] + for root in unique_roots: + dset = _build_dataset_from_root(opt, root) + datasets_all.append(dset) + + if len(datasets_all) == 1: + return datasets_all[0] + return torch.utils.data.ConcatDataset(datasets_all) + +def _collect_targets(dataset): + targets = getattr(dataset, 'targets', None) + if targets is not None: + return [int(t) for t in targets] + if hasattr(dataset, 'datasets'): + merged = [] + for d in dataset.datasets: + merged.extend(_collect_targets(d)) + return merged + raise AttributeError('Cannot build balanced sampler: dataset has no targets attribute') + + +class DistributedWeightedSampler(Sampler): + """DDP-friendly class-balanced sampler using weighted multinomial sampling.""" + def __init__(self, sample_weights, num_samples, num_replicas, rank, seed=0): + self.weights = torch.as_tensor(sample_weights, dtype=torch.double) + self.num_samples = int(num_samples) + self.num_replicas = int(num_replicas) + self.rank = int(rank) + self.seed = int(seed) + self.epoch = 0 + self.total_size = self.num_samples * self.num_replicas + + def __iter__(self): + g = torch.Generator() + g.manual_seed(self.seed + self.epoch) + sampled = torch.multinomial( + self.weights, + self.total_size, + replacement=True, + generator=g, + ) + rank_samples = sampled[self.rank:self.total_size:self.num_replicas] + return iter(rank_samples.tolist()) + + def __len__(self): + return self.num_samples + + def set_epoch(self, epoch): + self.epoch = int(epoch) + + +class ClassUniformSampler(Sampler): + """Class-uniform sampler: each epoch enforces near-equal samples per class.""" + def __init__(self, class_to_indices, num_samples, seed=0): + if not class_to_indices: + raise ValueError("class_to_indices must not be empty") + self.class_to_indices = { + int(k): torch.as_tensor(v, dtype=torch.long) + for k, v in class_to_indices.items() + if len(v) > 0 + } + if not self.class_to_indices: + raise ValueError("class_to_indices has no non-empty classes") + self.classes = sorted(self.class_to_indices.keys()) + self.num_samples = int(num_samples) + self.seed = int(seed) + self.epoch = 0 + + @staticmethod + def _draw(pool, n, generator): + if n <= 0: + return torch.empty(0, dtype=torch.long) + m = int(pool.numel()) + if m <= 0: + raise ValueError("Cannot draw from an empty class pool") + if m >= n: + perm = torch.randperm(m, generator=generator)[:n] + return pool[perm] + idx = torch.randint(low=0, high=m, size=(n,), generator=generator) + return pool[idx] + + def __iter__(self): + g = torch.Generator() + g.manual_seed(self.seed + self.epoch) + num_classes = len(self.classes) + base = self.num_samples // num_classes + rem = self.num_samples % num_classes + + chunks = [] + for i, cls in enumerate(self.classes): + need = base + (1 if i < rem else 0) + chunks.append(self._draw(self.class_to_indices[cls], need, g)) + sampled = torch.cat(chunks, dim=0) + order = torch.randperm(sampled.numel(), generator=g) + sampled = sampled[order] + return iter(sampled.tolist()) + + def __len__(self): + return self.num_samples + + def set_epoch(self, epoch): + self.epoch = int(epoch) + + +class DistributedClassUniformSampler(Sampler): + """DDP-friendly class-uniform sampler with rank-wise sharding.""" + def __init__(self, class_to_indices, num_samples, num_replicas, rank, seed=0): + if not class_to_indices: + raise ValueError("class_to_indices must not be empty") + self.class_to_indices = { + int(k): torch.as_tensor(v, dtype=torch.long) + for k, v in class_to_indices.items() + if len(v) > 0 + } + if not self.class_to_indices: + raise ValueError("class_to_indices has no non-empty classes") + self.classes = sorted(self.class_to_indices.keys()) + self.num_samples = int(num_samples) + self.num_replicas = int(num_replicas) + self.rank = int(rank) + self.seed = int(seed) + self.epoch = 0 + self.total_size = self.num_samples * self.num_replicas + + @staticmethod + def _draw(pool, n, generator): + if n <= 0: + return torch.empty(0, dtype=torch.long) + m = int(pool.numel()) + if m <= 0: + raise ValueError("Cannot draw from an empty class pool") + if m >= n: + perm = torch.randperm(m, generator=generator)[:n] + return pool[perm] + idx = torch.randint(low=0, high=m, size=(n,), generator=generator) + return pool[idx] + + def __iter__(self): + g = torch.Generator() + g.manual_seed(self.seed + self.epoch) + num_classes = len(self.classes) + base = self.total_size // num_classes + rem = self.total_size % num_classes + + chunks = [] + for i, cls in enumerate(self.classes): + need = base + (1 if i < rem else 0) + chunks.append(self._draw(self.class_to_indices[cls], need, g)) + sampled = torch.cat(chunks, dim=0) + order = torch.randperm(sampled.numel(), generator=g) + sampled = sampled[order] + + rank_samples = sampled[self.rank:self.total_size:self.num_replicas] + return iter(rank_samples.tolist()) + + def __len__(self): + return self.num_samples + + def set_epoch(self, epoch): + self.epoch = int(epoch) + + +def _collect_class_to_indices(targets): + class_to_indices = {} + for idx, t in enumerate(targets): + cls = int(t) + class_to_indices.setdefault(cls, []).append(idx) + return class_to_indices + + +def get_bal_sampler(dataset, *, distributed=False, num_replicas=1, rank=0, seed=0, strategy="auto"): + targets = _collect_targets(dataset) + if len(targets) == 0: + raise ValueError('Cannot build balanced sampler: empty targets') + + strategy = str(strategy or "auto").strip().lower() + class_to_indices = _collect_class_to_indices(targets) + + if strategy == "auto": + # For binary deepfake labels (0=real, 1=fake), enforce strict near-1:1 + # class balance per epoch by default. + if len(class_to_indices) == 2 and set(class_to_indices.keys()) == {0, 1}: + strategy = "uniform" + else: + strategy = "weighted" + + if strategy in {"uniform", "strict", "strict_binary", "exact"}: + if distributed: + num_samples = int(math.ceil(len(targets) / float(max(1, num_replicas)))) + return DistributedClassUniformSampler( + class_to_indices=class_to_indices, + num_samples=num_samples, + num_replicas=max(1, num_replicas), + rank=rank, + seed=seed, + ) + return ClassUniformSampler( + class_to_indices=class_to_indices, + num_samples=len(targets), + seed=seed, + ) + + ratio = np.bincount(targets) + w = 1. / torch.tensor(ratio, dtype=torch.float) + sample_weights = w[targets] + if distributed: + num_samples = int(math.ceil(len(sample_weights) / float(max(1, num_replicas)))) + return DistributedWeightedSampler( + sample_weights=sample_weights, + num_samples=num_samples, + num_replicas=max(1, num_replicas), + rank=rank, + seed=seed, + ) + return WeightedRandomSampler( + weights=sample_weights, + num_samples=len(sample_weights), + replacement=True, + ) + + +def create_dataloader(opt): + shuffle = not opt.serial_batches if (opt.isTrain and not opt.class_bal) else False + dataset = get_dataset(opt) + distributed = bool(getattr(opt, 'distributed', False)) + if opt.class_bal: + strategy = str(getattr(opt, 'class_bal_strategy', 'auto') or 'auto') + if bool(getattr(opt, 'class_bal_strict', False)) and strategy.lower() in {'weighted', 'auto'}: + strategy = 'uniform' + sampler = get_bal_sampler( + dataset, + distributed=distributed, + num_replicas=int(getattr(opt, 'world_size', 1)), + rank=int(getattr(opt, 'rank', 0)), + seed=int(getattr(opt, 'seed', 0)), + strategy=strategy, + ) + shuffle = False + else: + sampler = None + + data_loader = torch.utils.data.DataLoader(dataset, + batch_size=opt.batch_size, + shuffle=shuffle, + sampler=sampler, + num_workers=int(opt.num_threads)) + return data_loader diff --git a/detectors/ForensicConcept/upstream/data/datasets.py b/detectors/ForensicConcept/upstream/data/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..9577966917f2e07855d9b66d56f977b6257b898c --- /dev/null +++ b/detectors/ForensicConcept/upstream/data/datasets.py @@ -0,0 +1,967 @@ +import cv2 +import numpy as np +import inspect +import re +import os + +os.environ.setdefault("NO_ALBUMENTATIONS_UPDATE", "1") + +import albumentations as A +from albumentations import Downscale, Compose, ImageCompression, GaussNoise, MotionBlur, GaussianBlur +from torchvision import transforms, datasets +import torchvision.transforms.functional as TF +from random import random, choice +from io import BytesIO +from PIL import Image +from PIL import ImageFile +from PIL import ImageFilter +from PIL import ImageOps +from PIL import UnidentifiedImageError +from scipy.ndimage import gaussian_filter +from torchvision.transforms import InterpolationMode +import torch + +ImageFile.LOAD_TRUNCATED_IMAGES = True + + +CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073] +CLIP_STD = [0.26862954, 0.26130258, 0.27577711] +IMAGENET_MEAN = [0.485, 0.456, 0.406] +IMAGENET_STD = [0.229, 0.224, 0.225] + + +def _supports_albu_arg(cls, arg_name): + try: + return arg_name in inspect.signature(cls.__init__).parameters + except Exception: + return False + + +def _build_downscale_aug(): + """Build Downscale across the Albumentations 1.x and 2.x APIs.""" + if _supports_albu_arg(Downscale, "scale_range"): + return Downscale( + scale_range=(0.25, 0.75), + interpolation_pair={ + "downscale": cv2.INTER_LINEAR, + "upscale": cv2.INTER_LINEAR, + }, + p=0.5, + ) + return Downscale( + scale_min=0.25, + scale_max=0.75, + interpolation=cv2.INTER_LINEAR, + p=0.5, + ) + + +def _build_testshift_like_aug(p_apply=1.0, max_groups=3): + # group 1) blur + blur_group = A.OneOf([ + A.GaussianBlur(sigma_limit=(0.1, 5.0), p=1.0), + A.Defocus(radius=(1, 8), alias_blur=(0.1, 0.5), p=1.0), + ], p=1.0) + + # group 2) color distortion + color_group = A.OneOf([ + A.ChromaticAberration( + primary_distortion_limit=(0.01, 0.08), + secondary_distortion_limit=(0.01, 0.12), + p=1.0, + ), + A.ColorJitter(brightness=0.0, contrast=0.0, saturation=1.0, hue=0.0, p=1.0), + ], p=1.0) + + # group 3) jpeg + if _supports_albu_arg(A.ImageCompression, "quality_range"): + jpeg_group = A.ImageCompression(compression_type="jpeg", quality_range=(4, 43), p=1.0) + else: + jpeg_group = A.ImageCompression(quality_lower=4, quality_upper=43, p=1.0) + + # group 4) noise + if _supports_albu_arg(A.GaussNoise, "std_range"): + gauss_noise = A.GaussNoise(std_range=(0.032, 0.100), mean_range=(0.0, 0.0), per_channel=True, p=1.0) + else: + gauss_noise = A.GaussNoise(var_limit=(0.032 ** 2, 0.100 ** 2), mean=0.0, per_channel=True, p=1.0) + if hasattr(A, "SaltAndPepper"): + impulse_noise = A.SaltAndPepper(amount=(0.001, 0.03), salt_vs_pepper=(0.45, 0.55), p=1.0) + else: + impulse_noise = A.ISONoise(color_shift=(0.01, 0.05), intensity=(0.1, 0.5), p=1.0) + noise_group = A.OneOf([ + gauss_noise, + impulse_noise, + ], p=1.0) + + # group 5) brightness + brightness_group = A.RandomBrightnessContrast( + brightness_limit=(-0.8, 0.8), + contrast_limit=(0.0, 0.0), + brightness_by_max=True, + p=1.0, + ) + + # group 6) spatial distortion + spatial_group = A.OneOf([ + A.GridDistortion( + num_steps=5, + distort_limit=(0.05, 0.5), + interpolation=cv2.INTER_LINEAR, + border_mode=cv2.BORDER_REFLECT_101, + p=1.0, + ), + A.Sequential([ + A.ToGray(num_output_channels=3, p=1.0), + A.Posterize(num_bits=(3, 5), p=1.0), + ], p=1.0), + ], p=1.0) + + # group 7) sharpness / contrast + sharp_contrast_group = A.RandomToneCurve(scale=0.2, p=1.0) + + groups = [ + blur_group, + color_group, + jpeg_group, + noise_group, + brightness_group, + spatial_group, + sharp_contrast_group, + ] + + max_groups = max(1, min(int(max_groups), len(groups))) + choices = [A.SomeOf(groups, n=n, replace=False, p=1.0) for n in range(1, max_groups + 1)] + + return A.Compose([ + A.OneOf(choices, p=1.0), + ], p=float(p_apply)) + +def dataset_folder(opt, root): + if opt.mode == 'binary': + return binary_dataset(opt, root) + if opt.mode == 'filename': + return FileNameDataset(opt, root) + raise ValueError('opt.mode needs to be binary or filename.') + + +def _apply_single_robustness(img, robustness_type, params=None): + params = dict(params or {}) + robustness_type = str(robustness_type or "").strip().lower() + if not robustness_type: + return img + + if robustness_type == "jpeg": + quality = int(params.get("jpeg_quality", 75) or 75) + out = BytesIO() + img.save(out, format="JPEG", quality=quality) + out.seek(0) + with Image.open(out) as aug_img: + return aug_img.convert("RGB") + + if robustness_type == "gaussian_blur": + sigma = float(params.get("gaussian_blur_sigma", 1.0) or 1.0) + return img.filter(ImageFilter.GaussianBlur(radius=sigma)) + + if robustness_type == "gaussian_noise": + std = float(params.get("gaussian_noise_std", 0.1) or 0.1) + img_np = np.asarray(img).astype(np.float32) / 255.0 + noise = np.random.normal(loc=0.0, scale=std, size=img_np.shape).astype(np.float32) + img_np = np.clip(img_np + noise, 0.0, 1.0) + img_np = (img_np * 255.0).round().astype(np.uint8) + return Image.fromarray(img_np) + + if robustness_type == "downsample": + scale = float(params.get("downsample_scale", 0.5) or 0.5) + width, height = img.size + down_w = max(1, int(round(width * scale))) + down_h = max(1, int(round(height * scale))) + down = img.resize((down_w, down_h), resample=Image.BILINEAR) + return down.resize((width, height), resample=Image.BILINEAR) + + if robustness_type == "color_jitter": + brightness = float(params.get("cj_brightness", 0.0) or 0.0) + contrast = float(params.get("cj_contrast", 0.0) or 0.0) + saturation = float(params.get("cj_saturation", 0.0) or 0.0) + hue = float(params.get("cj_hue", 0.0) or 0.0) + + out = img + if brightness != 0.0: + out = TF.adjust_brightness(out, 1.0 + brightness) + if contrast != 0.0: + out = TF.adjust_contrast(out, 1.0 + contrast) + if saturation != 0.0: + out = TF.adjust_saturation(out, 1.0 + saturation) + if hue != 0.0: + hue = max(-0.5, min(0.5, hue)) + out = TF.adjust_hue(out, hue) + return out + + raise ValueError(f"Unsupported robustness_type: {robustness_type}") + + +def _apply_explicit_robustness(img, opt): + robustness_chain = getattr(opt, "robustness_chain", None) or [] + if robustness_chain: + out = img + for idx, entry in enumerate(robustness_chain): + if not isinstance(entry, dict): + raise ValueError(f"robustness_chain[{idx}] must be a dict, got {type(entry).__name__}") + out = _apply_single_robustness( + out, + entry.get("type", ""), + entry.get("params", {}), + ) + return out + + return _apply_single_robustness( + img, + getattr(opt, "robustness_type", ""), + { + "jpeg_quality": getattr(opt, "robustness_jpeg_quality", 75), + "gaussian_blur_sigma": getattr(opt, "robustness_gaussian_blur_sigma", 1.0), + "gaussian_noise_std": getattr(opt, "robustness_gaussian_noise_std", 0.1), + "downsample_scale": getattr(opt, "robustness_downsample_scale", 0.5), + "cj_brightness": getattr(opt, "robustness_cj_brightness", 0.0), + "cj_contrast": getattr(opt, "robustness_cj_contrast", 0.0), + "cj_saturation": getattr(opt, "robustness_cj_saturation", 0.0), + "cj_hue": getattr(opt, "robustness_cj_hue", 0.0), + }, + ) + + +import base64 +from io import BytesIO +from PIL import Image +import numpy as np +import torchvision.transforms +from scipy.ndimage import gaussian_filter + + +class ImageProcessor: + def __init__(self, opt): + self.opt = opt + + def data_augment(self, img): + noise_type = getattr(self.opt, "noise_type", None) + noise_ratio = getattr(self.opt, "noise_ratio", None) + + if noise_type == 'jpg': + img_processed = self.pil_jpg_new(img, noise_ratio) + elif noise_type == 'resize': + width, height = img.size + img_processed = torchvision.transforms.Resize((int(height / noise_ratio), int(width / noise_ratio)))(img) + elif noise_type == 'blur': + img = np.array(img) + self.gaussian_blur(img, noise_ratio) + img_processed = Image.fromarray(img) + elif noise_type is None: + img_processed = img + + return img_processed + + def pil_jpg_new(self, img, compress_val): + out = BytesIO() + img.save(out, format='jpeg', quality=compress_val) + img = Image.open(out) + # load from memory before ByteIO closes + img = np.array(img) + img = Image.fromarray(img) + out.close() + return img + + def gaussian_blur(self, img, sigma): + # Check if the image has a third dimension + if img.ndim == 3: + # Check the number of channels in the image + channels = img.shape[2] + # if channels == 0: + # # If there are no channels, return the image as is + # return img + if channels == 1: + # If there is one channel, apply the filter to the single channel + gaussian_filter(img[:, :, 0], output=img[:, :, 0], sigma=sigma) + elif channels == 2: + # If there are two channels, apply the filter to both channels + gaussian_filter(img[:, :, 0], output=img[:, :, 0], sigma=sigma) + gaussian_filter(img[:, :, 1], output=img[:, :, 1], sigma=sigma) + elif channels == 3: + # If there are three channels, apply the filter to all three channels + gaussian_filter(img[:, :, 0], output=img[:, :, 0], sigma=sigma) + gaussian_filter(img[:, :, 1], output=img[:, :, 1], sigma=sigma) + gaussian_filter(img[:, :, 2], output=img[:, :, 2], sigma=sigma) + else: + # If the image does not have a third dimension, apply the filter to the 2D image + gaussian_filter(img, output=img, sigma=sigma) + + # return img + + +def encode_image(image_path, processor=None): + with open(image_path, "rb") as image_file: + img = Image.open(image_file) + + # Apply data augmentation if processor is provided + if processor is not None: + # print(processor.opt) + img = processor.data_augment(img) + + # Convert image to Base64 + buffered = BytesIO() + img.save(buffered, format="PNG") + img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8') + + return img, img_base64 + +class Options: + def __init__(self, noise_type=None, noise_ratio=None): + """ + ๅˆๅง‹ๅŒ–ๆ•ฐๆฎๅขžๅผบ็š„้…็ฝฎๅ‚ๆ•ฐใ€‚ + + :param noise_type: ๅ™ชๅฃฐ็ฑปๅž‹๏ผŒๅฏ้€‰ๅ€ผไธบ 'jpg', 'resize', 'blur' ๆˆ– None + :param noise_ratio: ๅ™ชๅฃฐๅผบๅบฆๆˆ–ๆฏ”ไพ‹๏ผŒๅ…ทไฝ“ๅซไน‰ๅ–ๅ†ณไบŽ noise_type + """ + self.noise_type = noise_type + self.noise_ratio = noise_ratio + def __str__(self): + """่ฟ”ๅ›žๅฏน่ฑก็š„ๅญ—็ฌฆไธฒ่กจ็คบ๏ผŒไพฟไบŽ่ฐƒ่ฏ•""" + return (f"Options(noise_type={self.noise_type}, noise_ratio={self.noise_ratio}") + + +# Robust ImageFolder: skip unreadable/corrupted files instead of crashing workers. +class SafeImageFolder(datasets.ImageFolder): + def __init__(self, *args, skip_broken=True, skip_log_limit=0, **kwargs): + super().__init__(*args, **kwargs) + self.skip_broken = bool(skip_broken) + self.skip_log_limit = max(0, int(skip_log_limit)) + self._skip_log_count = 0 + + @staticmethod + def _is_image_decode_error(exc): + return isinstance(exc, (UnidentifiedImageError, OSError, ValueError)) + + def __getitem__(self, index): + if not self.skip_broken: + return super().__getitem__(index) + + total = len(self.samples) + if total == 0: + raise IndexError("SafeImageFolder is empty") + + idx = int(index) % total + for _ in range(total): + try: + return super().__getitem__(idx) + except Exception as exc: + if not self._is_image_decode_error(exc): + raise + + bad_path = self.samples[idx][0] + if self._skip_log_count < self.skip_log_limit: + print( + f"[Data] Skipping unreadable image: {bad_path} " + f"({type(exc).__name__}: {exc})" + ) + self._skip_log_count += 1 + idx = (idx + 1) % total + + raise RuntimeError( + "Unable to fetch a readable image from dataset. " + "All candidates appear unreadable." + ) + + +class FlatLabeledImageDataset(torch.utils.data.Dataset): + """Fallback dataset for flat folders: labels parsed from filename suffix (_real/_fake).""" + + def __init__(self, samples, transform=None, skip_broken=True, skip_log_limit=0): + self.samples = list(samples) + self.transform = transform + self.skip_broken = bool(skip_broken) + self.skip_log_limit = max(0, int(skip_log_limit)) + self._skip_log_count = 0 + self.targets = [int(t) for _, t in self.samples] + self.class_to_idx = {'0_real': 0, '1_fake': 1} + self.classes = ['0_real', '1_fake'] + self.imgs = self.samples + + @staticmethod + def _is_image_decode_error(exc): + return isinstance(exc, (UnidentifiedImageError, OSError, ValueError)) + + def __len__(self): + return len(self.samples) + + def __getitem__(self, index): + total = len(self.samples) + if total == 0: + raise IndexError("FlatLabeledImageDataset is empty") + + idx = int(index) % total + for _ in range(total): + path, target = self.samples[idx] + try: + with Image.open(path) as img: + img = img.convert("RGB") + if self.transform is not None: + img = self.transform(img) + return img, int(target) + except Exception as exc: + if (not self.skip_broken) or (not self._is_image_decode_error(exc)): + raise + if self._skip_log_count < self.skip_log_limit: + print( + f"[Data] Skipping unreadable image: {path} " + f"({type(exc).__name__}: {exc})" + ) + self._skip_log_count += 1 + idx = (idx + 1) % total + + raise RuntimeError("Unable to fetch a readable image from flat dataset.") + + +# Example usage: +# opt = SomeOptionsClass() # Replace with your actual options class +# print(opt_class) + + +def _find_binary_roots(root): + """Yield directories whose immediate children contain 0_real and 1_fake.""" + binary_roots = [] + valid_pairs = ( + {'0_real', '1_fake'}, + {'0_fake', '1_real'}, + {'raw', 'synthesis'}, # deepfake datasets + {'real', 'fake'}, + ) + for current_root, dirs, _ in os.walk(root): + present = set(dirs) + if any(pair.issubset(present) for pair in valid_pairs): + binary_roots.append(current_root) + # ensure deterministic ordering so label mapping is stable + binary_roots.sort() + return binary_roots + + +def infer_single_label_from_root(root): + """Infer fixed binary label from directory name for one-class dataset roots.""" + # Canonical deepfake aliases used by Celeb-DF/FF++ style trees. + alias_to_label = { + # real + "0_real": 0, + "1_real": 0, + "real": 0, + "raw": 0, + "original_sequences": 0, + "celeb-real-mtcnn": 0, + "youtube-real-mtcnn": 0, + # fake + "1_fake": 1, + "0_fake": 1, + "fake": 1, + "synthesis": 1, + "manipulated_sequences": 1, + "celeb-synthesis-mtcnn": 1, + } + base = os.path.basename(os.path.abspath(root)).strip().lower() + return alias_to_label.get(base) + + +def _collect_recursive_image_samples(root, label): + exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"} + samples = [] + for current_root, _, files in os.walk(root): + for fname in files: + if os.path.splitext(fname)[1].lower() in exts: + samples.append((os.path.join(current_root, fname), int(label))) + samples.sort(key=lambda x: x[0]) + return samples + + +def _resolve_dfdc_labels_path(root, opt): + root_abs = os.path.abspath(root) + explicit_candidates = [ + getattr(opt, "dfdc_labels_npy", None), + getattr(opt, "data_dfdc_labels_npy", None), + ] + candidates = [c for c in explicit_candidates if c] + candidates.extend( + [ + os.path.join(os.path.dirname(root_abs), "labels.npy"), + os.path.join(os.path.dirname(os.path.dirname(root_abs)), "labels.npy"), + os.path.join(root_abs, "labels.npy"), + ] + ) + seen = set() + for candidate in candidates: + p = os.path.abspath(os.path.expanduser(str(candidate))) + if p in seen: + continue + seen.add(p) + if os.path.isfile(p): + return p + return None + + +def is_dfdc_train_faces_root(root, opt=None): + root_abs = os.path.abspath(root) + if os.path.basename(root_abs).strip().lower() != "train_faces": + return False + opt_obj = opt if opt is not None else object() + return _resolve_dfdc_labels_path(root_abs, opt_obj) is not None + + +def _build_dfdc_train_faces_dataset(opt, root, transform): + root_abs = os.path.abspath(root) + if not is_dfdc_train_faces_root(root_abs, opt): + return None + + labels_path = _resolve_dfdc_labels_path(root_abs, opt) + if labels_path is None: + return None + + try: + labels_raw = np.load(labels_path, allow_pickle=True).item() + except Exception as exc: + raise RuntimeError(f"Failed to load DFDC labels file: {labels_path} ({exc})") from exc + + if not isinstance(labels_raw, dict): + raise RuntimeError(f"DFDC labels file is not a dict: {labels_path}") + + video_to_label = {} + for k, v in labels_raw.items(): + key = str(k) + if key.endswith(".mp4"): + key = key[:-4] + try: + iv = int(v) + except (TypeError, ValueError): + continue + if iv in (0, 1): + video_to_label[key] = iv + + if not video_to_label: + raise RuntimeError(f"No valid binary labels parsed from: {labels_path}") + + exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"} + samples = [] + total_video_dirs = 0 + missing_label_video_dirs = 0 + missing_label_examples = [] + + for part_name in sorted(os.listdir(root_abs)): + part_dir = os.path.join(root_abs, part_name) + if not os.path.isdir(part_dir): + continue + for video_name in sorted(os.listdir(part_dir)): + video_dir = os.path.join(part_dir, video_name) + if not os.path.isdir(video_dir): + continue + total_video_dirs += 1 + label = video_to_label.get(video_name) + if label is None: + missing_label_video_dirs += 1 + if len(missing_label_examples) < 5: + missing_label_examples.append(video_dir) + continue + for fname in sorted(os.listdir(video_dir)): + if os.path.splitext(fname)[1].lower() in exts: + samples.append((os.path.join(video_dir, fname), int(label))) + + if not samples: + raise RuntimeError( + f"Detected DFDC train_faces root but no labeled image files were collected under {root_abs}" + ) + + if missing_label_video_dirs > 0: + print( + f"[DFDC] Warning: {missing_label_video_dirs}/{total_video_dirs} video folders in {root_abs} " + f"missing labels from {labels_path}. Examples: {missing_label_examples}" + ) + + real_count = sum(1 for _, t in samples if int(t) == 0) + fake_count = len(samples) - real_count + print( + f"[DFDC] Loaded train_faces with labels from {labels_path}: " + f"samples={len(samples)} real={real_count} fake={fake_count}" + ) + + skip_broken_images = bool(getattr(opt, "skip_broken_images", True)) + skip_log_limit = int(getattr(opt, "skip_broken_images_log_limit", 0)) + return FlatLabeledImageDataset( + samples=samples, + transform=transform, + skip_broken=skip_broken_images, + skip_log_limit=skip_log_limit, + ) + + +def _build_binary_datasets(opt, root, transform): + """Create ImageFolder datasets for every binary directory discovered under root.""" + binary_roots = _find_binary_roots(root) + if not binary_roots: + dfdc_dataset = _build_dfdc_train_faces_dataset(opt, root, transform) + if dfdc_dataset is not None: + return dfdc_dataset + + # Fallback: flat folder with filename labels like xxx_real.png / xxx_fake.png + exts = {'.jpg', '.jpeg', '.png', '.bmp', '.webp', '.tif', '.tiff'} + suffix_re = re.compile(r'(?:^|[_-])(real|fake)$', flags=re.IGNORECASE) + flat_samples = [] + root_path = os.path.abspath(root) + for p in sorted(os.listdir(root_path)): + abs_p = os.path.join(root_path, p) + if not os.path.isfile(abs_p): + continue + ext = os.path.splitext(p)[1].lower() + if ext not in exts: + continue + stem = os.path.splitext(p)[0] + m = suffix_re.search(stem) + if not m: + continue + label = 0 if m.group(1).lower() == 'real' else 1 + flat_samples.append((abs_p, label)) + + skip_broken_images = bool(getattr(opt, "skip_broken_images", True)) + skip_log_limit = int(getattr(opt, "skip_broken_images_log_limit", 0)) + if flat_samples: + return FlatLabeledImageDataset( + samples=flat_samples, + transform=transform, + skip_broken=skip_broken_images, + skip_log_limit=skip_log_limit, + ) + + forced_label = infer_single_label_from_root(root) + if forced_label is not None: + recursive_samples = _collect_recursive_image_samples(root, forced_label) + if not recursive_samples: + raise RuntimeError( + f"Single-label root inferred for {root}, but no image files were found recursively." + ) + return FlatLabeledImageDataset( + samples=recursive_samples, + transform=transform, + skip_broken=skip_broken_images, + skip_log_limit=skip_log_limit, + ) + + raise RuntimeError( + f"Could not locate binary folders (0_real/1_fake, raw/synthesis, real/fake), " + f"flat *_real/*_fake files, or a known single-label root alias under {root}" + ) + + datasets_list = [] + skip_broken_images = bool(getattr(opt, "skip_broken_images", True)) + skip_log_limit = int(getattr(opt, "skip_broken_images_log_limit", 0)) + for binary_root in binary_roots: + dset = SafeImageFolder( + binary_root, + transform=transform, + skip_broken=skip_broken_images, + skip_log_limit=skip_log_limit, + ) + idx_to_class = {idx: cls_name for cls_name, idx in dset.class_to_idx.items()} + class_names = set(idx_to_class.values()) + + if class_names == {'0_real', '1_fake'}: + desired_order = {'0_real': 0, '1_fake': 1} + elif class_names == {'0_fake', '1_real'}: + # reverse-labelled datasets: map back to canonical ordering + desired_order = {'1_real': 0, '0_fake': 1} + elif class_names == {'raw', 'synthesis'}: + desired_order = {'raw': 0, 'synthesis': 1} + elif class_names == {'real', 'fake'}: + desired_order = {'real': 0, 'fake': 1} + else: + raise RuntimeError( + f"Unsupported class names {class_names} under {binary_root}; " + "expected 0_real/1_fake, 0_fake/1_real, raw/synthesis, or real/fake" + ) + + remapped = [] + for path, target in dset.samples: + cls_name = idx_to_class[target] + if cls_name not in desired_order: + raise RuntimeError( + f"Encountered unexpected class '{cls_name}' in {binary_root}; expected one of {list(desired_order.keys())}" + ) + remapped.append((path, desired_order[cls_name])) + + if remapped != dset.samples: + dset.samples = remapped + dset.imgs = remapped + dset.targets = [t for _, t in remapped] + + # Normalise metadata to canonical labels for downstream consumers + dset.class_to_idx = {'0_real': 0, '1_fake': 1} + dset.classes = ['0_real', '1_fake'] + datasets_list.append(dset) + + if len(datasets_list) == 1: + return datasets_list[0] + return torch.utils.data.ConcatDataset(datasets_list) + + +def _pad_to_min_size(img, target_h, target_w): + """Pad image with zeros so that height/width are at least target sizes.""" + width, height = img.size + pad_w = max(target_w - width, 0) + pad_h = max(target_h - height, 0) + if pad_w == 0 and pad_h == 0: + return img + + left = pad_w // 2 + right = pad_w - left + top = pad_h // 2 + bottom = pad_h - top + return ImageOps.expand(img, border=(left, top, right, bottom), fill=0) + + +def binary_dataset(opt, root): + # Allow switching to a simplified (legacy) preprocessing pipeline to match the NPR script. + legacy_preprocess = getattr(opt, "legacy_preprocess", False) + + if opt.isTrain: + crop_func = transforms.RandomCrop(opt.cropSize) + elif opt.no_crop: + crop_func = transforms.Lambda(lambda img: img) + else: + crop_func = transforms.CenterCrop(opt.cropSize) + + if opt.isTrain and not opt.no_flip: + flip_func = transforms.RandomHorizontalFlip() + else: + flip_func = transforms.Lambda(lambda img: img) + if opt.no_resize: + rz_func = transforms.Lambda(lambda img: img) + else: + # rz_func = transforms.Lambda(lambda img: custom_resize(img, opt)) + rz_func = transforms.Resize((opt.loadSize, opt.loadSize)) + # rz_func = transforms.Resize(opt.loadSize) + if legacy_preprocess: + # Match the older flow: resize -> basic augment -> crop -> flip -> IMAGENET normalize. + normalize_transform = transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD) + # normalize_transform = transforms.Normalize(mean=CLIP_MEAN, std=CLIP_STD) + transform = transforms.Compose([ + transforms.Lambda(lambda img: _apply_explicit_robustness(img, opt)), + rz_func, + transforms.Lambda(lambda img: data_augment(img, opt)), + crop_func, + flip_func, + transforms.ToTensor(), + normalize_transform, + ]) + return _build_binary_datasets(opt, root, transform) + + NOISE_TYPE = getattr(opt, "noise_type", None) + NOISE_RATIO = getattr(opt, "noise_ratio", None) + + opt_class = Options(noise_type=NOISE_TYPE, noise_ratio=NOISE_RATIO) + processor = ImageProcessor(opt_class) + + # ๅฎšไน‰Albumentationsๅขžๅผบ๏ผˆๅ…ผๅฎนไธๅŒ็‰ˆๆœฌ็š„ ImageCompression ๅ‚ๆ•ฐ๏ผ‰ + def _build_image_compression(): + try: + return ImageCompression(quality_range=(60, 100), p=0.5) + except TypeError: + return ImageCompression(quality_lower=60, quality_upper=100, p=0.5) + + aug = Compose([ + _build_image_compression(), + GaussNoise(p=0.2), + MotionBlur(p=0.2), + GaussianBlur(blur_limit=3, p=0.5), + _build_downscale_aug(), + ]) + + # ่‡ชๅฎšไน‰่ฝฌๆขๅ‡ฝๆ•ฐ๏ผšๅฐ†PILๅ›พๅƒ่ฝฌๆขไธบNumPyๆ•ฐ็ป„๏ผŒๅบ”็”จAlbumentationsๅขžๅผบ๏ผŒๅ†่ฝฌๅ›žPIL + def albumentations_aug(img): + # ๅฐ†PILๅ›พๅƒ่ฝฌๆขไธบNumPyๆ•ฐ็ป„ (H, W, C) RGBๆ ผๅผ + img_np = np.array(img) + # ๅบ”็”จAlbumentationsๅขžๅผบ + augmented = aug(image=img_np) + # ไปŽๅญ—ๅ…ธไธญๆๅ–ๅขžๅผบๅŽ็š„ๅ›พๅƒ + img_aug = augmented['image'] + # ๅฐ†NumPyๆ•ฐ็ป„่ฝฌๅ›žPILๅ›พๅƒ + return Image.fromarray(img_aug) + + DATA_AUG = getattr(opt, "data_aug", False) + USE_TESTSHIFT_LIKE_AUG_TRAIN = bool(getattr(opt, "use_testshift_like_aug", False)) and bool(opt.isTrain) + USE_TESTSHIFT_LIKE_AUG_EVAL = bool(getattr(opt, "use_testshift_like_aug_eval", False)) and (not bool(opt.isTrain)) + USE_TESTSHIFT_LIKE_AUG = USE_TESTSHIFT_LIKE_AUG_TRAIN or USE_TESTSHIFT_LIKE_AUG_EVAL + TESTSHIFT_LIKE_APPLY_PROB = float(getattr(opt, "testshift_like_apply_prob", 1.0)) + TESTSHIFT_LIKE_MAX_GROUPS = int(getattr(opt, "testshift_like_max_groups", 3)) + USE_AUG_UTILS_EVAL = bool(getattr(opt, "use_aug_utils_eval", False)) and (not bool(opt.isTrain)) + USE_AUG_UTILS_TRAIN = bool(getattr(opt, "use_aug_utils_train", False)) and ( + bool(opt.isTrain) or USE_AUG_UTILS_EVAL + ) + AUG_UTILS_PROB = float(getattr(opt, "aug_utils_prob", 1.0)) + AUG_UTILS_MAX_DISTORTIONS = int(getattr(opt, "aug_utils_max_distortions", 3)) + AUG_UTILS_NUM_LEVELS = int(getattr(opt, "aug_utils_num_levels", 5)) + # ๅˆ›ๅปบๆ•ฐๆฎๅขžๅผบๅ˜ๆข๏ผˆdeepfakeไธ“็”จ TestShift-like ไธŽๅŽŸๆœ‰ๅขžๅผบไบ’ๆ–ฅ๏ผŒ้ฟๅ…ๅ ๅŠ ๅ็งป๏ผ‰ + if USE_TESTSHIFT_LIKE_AUG: + testshift_aug = _build_testshift_like_aug( + p_apply=TESTSHIFT_LIKE_APPLY_PROB, + max_groups=TESTSHIFT_LIKE_MAX_GROUPS, + ) + + def _testshift_like_aug(img): + img_np = np.array(img) + out = testshift_aug(image=img_np)["image"] + return Image.fromarray(out) + + data_aug = transforms.Lambda(_testshift_like_aug) + print( + f"[Aug] Using testshift-like aug (prob={TESTSHIFT_LIKE_APPLY_PROB}, " + f"max_groups={TESTSHIFT_LIKE_MAX_GROUPS})" + ) + elif DATA_AUG: + data_aug = transforms.Lambda(albumentations_aug) + else: + data_aug = transforms.Lambda(lambda img: img) + + if isinstance(opt.cropSize, (tuple, list)): + target_h = opt.cropSize[0] + target_w = opt.cropSize[1] if len(opt.cropSize) > 1 else opt.cropSize[0] + else: + target_h = target_w = opt.cropSize + + apply_padding = opt.no_resize and (opt.isTrain or not opt.no_crop) + pad_func = transforms.Lambda(lambda img: _pad_to_min_size(img, target_h, target_w)) if apply_padding else transforms.Lambda(lambda img: img) + + trainmode = str(getattr(opt, 'trainmode', '')).lower() + modelname = str(getattr(opt, 'modelname', '')) + if trainmode == 'lora' and modelname.startswith('CLIP:'): + normalize_transform = transforms.Normalize(mean=CLIP_MEAN, std=CLIP_STD) + else: + normalize_transform = transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD) + + # Optional: apply augmentations from aug_utils_train on tensor in [0, 1]. + aug_utils_transform = transforms.Lambda(lambda tens: tens) + if USE_AUG_UTILS_TRAIN: + try: + from aug_utils_train.utils_data import distort_images as aug_utils_distort_images + + def _apply_aug_utils_train(tens): + if random() > AUG_UTILS_PROB: + return tens + distorted, _, _ = aug_utils_distort_images( + tens, + max_distortions=AUG_UTILS_MAX_DISTORTIONS, + num_levels=AUG_UTILS_NUM_LEVELS, + ) + return distorted + + aug_utils_transform = transforms.Lambda(_apply_aug_utils_train) + stage = "train" if bool(opt.isTrain) else "eval" + print( + f"[Aug] Using aug_utils_train@{stage} (prob={AUG_UTILS_PROB}, " + f"max_distortions={AUG_UTILS_MAX_DISTORTIONS}, num_levels={AUG_UTILS_NUM_LEVELS})" + ) + except Exception as exc: + print(f"[Aug] Failed to enable aug_utils_train, fallback to default aug only: {exc}") + + transform = transforms.Compose([ + transforms.Lambda(lambda img: processor.data_augment(img)), + transforms.Lambda(lambda img: _apply_explicit_robustness(img, opt)), + # ไฝฟ็”จ่‡ชๅฎšไน‰ๅ‡ฝๆ•ฐๆ›ฟๆขๅŽŸprocessor.data_augment + data_aug, + rz_func, # ๅŽ็ปญPyTorchๅ˜ๆข (ๅฆ‚่ฐƒๆ•ดๅคงๅฐ) + pad_func, # ๅฝ“็ฆ็”จresizeไธ”ๅ›พๅƒไธ่ถณ่ฃๅ‰ชๅฐบๅฏธๆ—ถ่กฅ้›ถ + crop_func, # ่ฃๅ‰ช + flip_func, # ็ฟป่ฝฌ + transforms.ToTensor(), + aug_utils_transform, + normalize_transform, + ]) + + return _build_binary_datasets(opt, root, transform) + + +class FileNameDataset(datasets.ImageFolder): + def name(self): + return 'FileNameDataset' + + def __init__(self, opt, root): + self.opt = opt + super().__init__(root) + + def __getitem__(self, index): + # Loading sample + path, target = self.samples[index] + return path + + +def data_augment(img, opt): + img = np.array(img) + + if random() < opt.blur_prob: + sig = sample_continuous(opt.blur_sig) + gaussian_blur(img, sig) + + if random() < opt.jpg_prob: + method = sample_discrete(opt.jpg_method) + qual = sample_discrete(opt.jpg_qual) + img = jpeg_from_key(img, qual, method) + + return Image.fromarray(img) + + +def sample_continuous(s): + if len(s) == 1: + return s[0] + if len(s) == 2: + rg = s[1] - s[0] + return random() * rg + s[0] + raise ValueError("Length of iterable s should be 1 or 2.") + + +def sample_discrete(s): + if len(s) == 1: + return s[0] + return choice(s) + + +def gaussian_blur(img, sigma): + gaussian_filter(img[:,:,0], output=img[:,:,0], sigma=sigma) + gaussian_filter(img[:,:,1], output=img[:,:,1], sigma=sigma) + gaussian_filter(img[:,:,2], output=img[:,:,2], sigma=sigma) + + +def cv2_jpg(img, compress_val): + img_cv2 = img[:,:,::-1] + encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), compress_val] + result, encimg = cv2.imencode('.jpg', img_cv2, encode_param) + decimg = cv2.imdecode(encimg, 1) + return decimg[:,:,::-1] + + +def pil_jpg(img, compress_val): + out = BytesIO() + img = Image.fromarray(img) + img.save(out, format='jpeg', quality=compress_val) + img = Image.open(out) + # load from memory before ByteIO closes + img = np.array(img) + out.close() + return img + + +jpeg_dict = {'cv2': cv2_jpg, 'pil': pil_jpg} +def jpeg_from_key(img, compress_val, key): + method = jpeg_dict[key] + return method(img, compress_val) + + +# rz_dict = {'bilinear': Image.BILINEAR, + # 'bicubic': Image.BICUBIC, + # 'lanczos': Image.LANCZOS, + # 'nearest': Image.NEAREST} +rz_dict = {'bilinear': InterpolationMode.BILINEAR, + 'bicubic': InterpolationMode.BICUBIC, + 'lanczos': InterpolationMode.LANCZOS, + 'nearest': InterpolationMode.NEAREST} +def custom_resize(img, opt): + interp = sample_discrete(opt.rz_interp) + return TF.resize(img, (opt.loadSize,opt.loadSize), interpolation=rz_dict[interp]) diff --git a/detectors/ForensicConcept/upstream/models/__init__.py b/detectors/ForensicConcept/upstream/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..116d8eb3724f965c2857f30f817325c2e33e48ac --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/__init__.py @@ -0,0 +1,23 @@ +from .clip_models import CLIPModel + + +VALID_NAMES = [ + "CLIP:ViT-L/14", +] + + + + + +def get_model(name, opt=None): + if name not in VALID_NAMES: + # Allow custom CLIP identifiers when explicit checkpoint path is provided. + custom_clip_ok = ( + name.startswith("CLIP:") + and opt is not None + and bool(getattr(opt, "clip_model_path", None)) + ) + assert custom_clip_ok, f"Unsupported model name: {name}" + if name.startswith("CLIP:"): + return CLIPModel(name[5:], 1, opt) + raise ValueError(f"Unsupported model name: {name}") diff --git a/detectors/ForensicConcept/upstream/models/clip/__init__.py b/detectors/ForensicConcept/upstream/models/clip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f777f26074a28055e3ca7e11e7852bb27362c9 --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/clip/__init__.py @@ -0,0 +1,2 @@ +from .clip import * +from .model import set_lora_config diff --git a/detectors/ForensicConcept/upstream/models/clip/bpe_simple_vocab_16e6.txt.gz b/detectors/ForensicConcept/upstream/models/clip/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/clip/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917 diff --git a/detectors/ForensicConcept/upstream/models/clip/clip.py b/detectors/ForensicConcept/upstream/models/clip/clip.py new file mode 100644 index 0000000000000000000000000000000000000000..8cb45152be90528d2e068bcfe3fd1dd7744fb9e2 --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/clip/clip.py @@ -0,0 +1,248 @@ +import hashlib +import os +import urllib +import warnings +from typing import Any, Union, List +from packaging import version + +import torch +from PIL import Image +from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize +from tqdm import tqdm + +from .model import build_model, build_pe_model +from .simple_tokenizer import SimpleTokenizer as _Tokenizer + +try: + from torchvision.transforms import InterpolationMode + BICUBIC = InterpolationMode.BICUBIC +except ImportError: + BICUBIC = Image.BICUBIC + + +if version.parse(torch.__version__) < version.parse("1.7.1"): + warnings.warn("PyTorch version 1.7.1 or higher is recommended") + + +__all__ = ["available_models", "load", "tokenize"] +_tokenizer = _Tokenizer() + +_MODELS = { + "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt", + "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt", + "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt", + "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt", + "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt", + "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt", + "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt", + "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt", + "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt", +} + + +def _download(url: str, root: str): + os.makedirs(root, exist_ok=True) + filename = os.path.basename(url) + + expected_sha256 = url.split("/")[-2] + download_target = os.path.join(root, filename) + + if os.path.exists(download_target) and not os.path.isfile(download_target): + raise RuntimeError(f"{download_target} exists and is not a regular file") + + if os.path.isfile(download_target): + if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: + return download_target + else: + warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") + + with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: + with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop: + while True: + buffer = source.read(8192) + if not buffer: + break + + output.write(buffer) + loop.update(len(buffer)) + + if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256: + raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match") + + return download_target + + +def _convert_image_to_rgb(image): + return image.convert("RGB") + + +def _transform(n_px): + return Compose([ + Resize(n_px, interpolation=BICUBIC), + CenterCrop(n_px), + _convert_image_to_rgb, + ToTensor(), + Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), + ]) + + +def available_models() -> List[str]: + """Returns the names of available CLIP models""" + return list(_MODELS.keys()) + + +def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None): + """Load a CLIP model + + Parameters + ---------- + name : str + A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict + + device : Union[str, torch.device] + The device to put the loaded model + + jit : bool + Whether to load the optimized JIT model or more hackable non-JIT model (default). + + download_root: str + path to download the model files; by default, it uses "./.cache/clip" + + Returns + ------- + model : torch.nn.Module + The CLIP model + + preprocess : Callable[[PIL.Image], torch.Tensor] + A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input + """ + if name in _MODELS: + model_path = _download(_MODELS[name], download_root or os.path.abspath("./.cache/clip")) + elif os.path.isfile(name): + model_path = name + else: + raise RuntimeError(f"Model {name} not found; available models = {available_models()}") + + with open(model_path, 'rb') as opened_file: + try: + # loading JIT archive + model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval() + state_dict = None + except RuntimeError: + # loading saved state dict + if jit: + warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead") + jit = False + opened_file.seek(0) + state_dict = torch.load(opened_file, map_location="cpu") + + if not jit: + loaded_state = state_dict or model.state_dict() + # PE-Lang / PE-Core checkpoints are vision-only and do not include CLIP text keys. + is_pe_state = ( + isinstance(loaded_state, dict) + and "conv1.weight" in loaded_state + and "positional_embedding" in loaded_state + and any(k.startswith("transformer.resblocks.") for k in loaded_state.keys()) + and not any(k.startswith("visual.") for k in loaded_state.keys()) + ) + model = (build_pe_model(loaded_state) if is_pe_state else build_model(loaded_state)).to(device) + if str(device) == "cpu": + model.float() + input_res = getattr(getattr(model, "visual", model), "input_resolution", 224) + return model, _transform(input_res) + + # patch the device names + device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[]) + device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1] + + def patch_device(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("prim::Constant"): + if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): + node.copyAttributes(device_node) + + model.apply(patch_device) + patch_device(model.encode_image) + patch_device(model.encode_text) + + # patch dtype to float32 on CPU + if str(device) == "cpu": + float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[]) + float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] + float_node = float_input.node() + + def patch_float(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("aten::to"): + inputs = list(node.inputs()) + for i in [1, 2]: # dtype can be the second or third argument to aten::to() + if inputs[i].node()["value"] == 5: + inputs[i].node().copyAttributes(float_node) + + model.apply(patch_float) + patch_float(model.encode_image) + patch_float(model.encode_text) + + model.float() + + return model, _transform(model.input_resolution.item()) + + +def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]: + """ + Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + + context_length : int + The context length to use; all CLIP models use 77 as the context length + + truncate: bool + Whether to truncate the text in case its encoding is longer than the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]. + We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long. + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder["<|startoftext|>"] + eot_token = _tokenizer.encoder["<|endoftext|>"] + all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] + if version.parse(torch.__version__) < version.parse("1.8.0"): + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + else: + result = torch.zeros(len(all_tokens), context_length, dtype=torch.int) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + if truncate: + tokens = tokens[:context_length] + tokens[-1] = eot_token + else: + raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") + result[i, :len(tokens)] = torch.tensor(tokens) + + return result diff --git a/detectors/ForensicConcept/upstream/models/clip/loratorch/__init__.py b/detectors/ForensicConcept/upstream/models/clip/loratorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7fd9ad25a3ec6359639dfe7fa786dcc2c3c3e080 --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/clip/loratorch/__init__.py @@ -0,0 +1,4 @@ +name = "lora" + +from .layers import * +from .utils import * \ No newline at end of file diff --git a/detectors/ForensicConcept/upstream/models/clip/loratorch/layers.py b/detectors/ForensicConcept/upstream/models/clip/loratorch/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..1cef15d57a230febaf2c4d643244c3eb8b7d8493 --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/clip/loratorch/layers.py @@ -0,0 +1,584 @@ +# ------------------------------------------------------------------------------------------ +# This code is reconstructed based on loralib (https://github.com/microsoft/LoRA) by Baijiong Lin. +# ------------------------------------------------------------------------------------------ +import torch +import torch.nn as nn +import torch.nn.functional as F + +import math +from typing import Optional, List + +def set_param(curr_mod, name, param=None, mode='update'): + r"""Refer to https://github.com/Baijiong-Lin/MOML/blob/main/MTL/utils.py""" + if '.' in name: + n = name.split('.') + module_name = n[0] + rest = '.'.join(n[1:]) + for name, mod in curr_mod.named_children(): + if module_name == name: + return set_param(mod, rest, param, mode=mode) + else: + if mode == 'update': + delattr(curr_mod, name) + setattr(curr_mod, name, param) + elif mode == 'get': + if hasattr(curr_mod, name): + p = getattr(curr_mod, name) + return p + +class LoRALayer(): + def __init__( + self, + r: int, + lora_alpha: int, + fan_in_fan_out: bool = False, + ): + self.r = r + self.lora_alpha = lora_alpha + if self.r > 0: + self.scaling = self.lora_alpha / self.r + # Mark the weight as unmerged + self.merged = False + # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + self.fan_in_fan_out = fan_in_fan_out + # define params that require LoRA {'param_name': 'lora_name'} + self.params_with_lora = {} + + def register_lora_param(self): + r"""Register LoRA matrix""" + for param_name, lora_name in self.params_with_lora.items(): + assert len(eval(f'self.{param_name}').size()) == 2 + self.register_parameter(f'{lora_name}_lora_A', + nn.Parameter(eval(f'self.{param_name}').new_zeros((self.r, eval(f'self.{param_name}').size()[1]))) + ) + self.register_parameter(f'{lora_name}_lora_B', + nn.Parameter(eval(f'self.{param_name}').new_zeros((eval(f'self.{param_name}').size()[0], self.r))) + ) + eval(f'self.{param_name}').requires_grad = False + + def init_lora_param(self): + for param_name, lora_name in self.params_with_lora.items(): + if hasattr(self, f'{lora_name}_lora_A'): + # initialize A the same way as the default for nn.Linear and B to zero + nn.init.kaiming_uniform_(eval(f'self.{lora_name}_lora_A'), a=math.sqrt(5)) + nn.init.zeros_(eval(f'self.{lora_name}_lora_B')) + + def transpose(self, w: torch.Tensor): + return w.transpose(0, 1) if self.fan_in_fan_out else w + + def merge_BA(self, param_name: str): + lora_name = self.params_with_lora[param_name] + return self.transpose((eval(f'self.{lora_name}_lora_B') @ eval(f'self.{lora_name}_lora_A')).view(eval(f'self.{param_name}').shape)) + + def merge_lora_param(self): + r"""p_new = p + scaling * B @ A and keep differentiable to A and B""" + for param_name, lora_name in self.params_with_lora.items(): + p = set_param(self, param_name, mode='get') + # detach() is very important here + p_new = p.detach() + self.merge_BA(param_name) * self.scaling + set_param(self, param_name, param=p_new, mode='update') + + def add_lora_data(self): + r"""NOT differentiable""" + for param_name, lora_name in self.params_with_lora.items(): + eval(f'self.{param_name}').data += self.merge_BA(param_name) * self.scaling + + def sub_lora_data(self): + r"""NOT differentiable""" + for param_name, lora_name in self.params_with_lora.items(): + eval(f'self.{param_name}').data -= self.merge_BA(param_name) * self.scaling + + def lora_train(self, mode: bool = True): + if mode: + if self.merged and self.r > 0: + # Make sure that the weights are not merged + self.sub_lora_data() + self.merged = False + else: + if not self.merged and self.r > 0: + # Merge the weights and mark it + self.add_lora_data() + self.merged = True + +class LoRAMOELayer(): + def __init__( + self, + r: int, + lora_alpha: int, + fan_in_fan_out: bool = False, + ): + self.r = r + self.lora_alpha = lora_alpha + if self.r > 0: + self.scaling = self.lora_alpha / self.r + # Mark the weight as unmerged + self.merged = False + # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + self.fan_in_fan_out = fan_in_fan_out + # define params that require LoRA {'param_name': 'lora_name'} + self.params_with_lora = {} + + def register_lora_param(self): + r"""Register LoRA matrix""" + for param_name, lora_name in self.params_with_lora.items(): + assert len(eval(f'self.{param_name}').size()) == 2 + self.register_parameter(f'{lora_name}_lora_A', + nn.Parameter(eval(f'self.{param_name}').new_zeros((self.r, eval(f'self.{param_name}').size()[1]))) + ) + self.register_parameter(f'{lora_name}_lora_B', + nn.Parameter(eval(f'self.{param_name}').new_zeros((eval(f'self.{param_name}').size()[0], self.r))) + ) + eval(f'self.{param_name}').requires_grad = False + + def init_lora_param(self): + for param_name, lora_name in self.params_with_lora.items(): + if hasattr(self, f'{lora_name}_lora_A'): + # initialize A the same way as the default for nn.Linear and B to zero + nn.init.kaiming_uniform_(eval(f'self.{lora_name}_lora_A'), a=math.sqrt(5)) + nn.init.zeros_(eval(f'self.{lora_name}_lora_B')) + + def transpose(self, w: torch.Tensor): + return w.transpose(0, 1) if self.fan_in_fan_out else w + + def merge_BA(self, param_name: str): + lora_name = self.params_with_lora[param_name] + return self.transpose((eval(f'self.{lora_name}_lora_B') @ eval(f'self.{lora_name}_lora_A')).view(eval(f'self.{param_name}').shape)) + + def merge_lora_param(self): + r"""p_new = p + scaling * B @ A and keep differentiable to A and B""" + for param_name, lora_name in self.params_with_lora.items(): + p = set_param(self, param_name, mode='get') + # detach() is very important here + p_new = p.detach() + self.merge_BA(param_name) * self.scaling + set_param(self, param_name, param=p_new, mode='update') + + def add_lora_data(self): + r"""NOT differentiable""" + for param_name, lora_name in self.params_with_lora.items(): + eval(f'self.{param_name}').data += self.merge_BA(param_name) * self.scaling + + def sub_lora_data(self): + r"""NOT differentiable""" + for param_name, lora_name in self.params_with_lora.items(): + eval(f'self.{param_name}').data -= self.merge_BA(param_name) * self.scaling + + def lora_train(self, mode: bool = True): + if mode: + if self.merged and self.r > 0: + # Make sure that the weights are not merged + self.sub_lora_data() + self.merged = False + else: + if not self.merged and self.r > 0: + # Merge the weights and mark it + self.add_lora_data() + self.merged = True + +class Embedding(nn.Embedding, LoRALayer): + # LoRA implemented in a Embedding layer + def __init__( + self, + num_embeddings: int, + embedding_dim: int, + r: int = 0, + lora_alpha: int = 1, + **kwargs + ): + nn.Embedding.__init__(self, num_embeddings, embedding_dim, **kwargs) + LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha) + + self.params_with_lora = {'weight': 'w'} + if r > 0: + self.register_lora_param() + nn.Embedding.reset_parameters(self) + self.init_lora_param() + + def init_lora_param(self): + if hasattr(self, 'w_lora_A'): + # initialize A the same way as the default for nn.Linear and B to zero + nn.init.zeros_(self.w_lora_A) + nn.init.normal_(self.w_lora_B) + + def train(self, mode: bool = True): + nn.Embedding.train(self, mode) + self.lora_train(mode) + + def forward(self, x: torch.Tensor, **kwargs): + if self.r > 0 and not self.merged: + self.merge_lora_param() + result = nn.Embedding.forward(self, x, **kwargs) + self.sub_lora_data() + return result + else: + return nn.Embedding.forward(self, x, **kwargs) + +class Linear(nn.Linear, LoRALayer): + # LoRA implemented in a Linear layer + def __init__( + self, + in_features: int, + out_features: int, + r: int = 0, + lora_alpha: int = 1, + fan_in_fan_out: bool = False, + **kwargs + ): + nn.Linear.__init__(self, in_features, out_features, **kwargs) + LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha, fan_in_fan_out=fan_in_fan_out) + + # Actual trainable parameters + self.params_with_lora = {'weight': 'w'} + if r > 0: + self.register_lora_param() + nn.Linear.reset_parameters(self) + self.init_lora_param() + self.weight.data = self.transpose(self.weight.data) + + def train(self, mode: bool = True): + nn.Linear.train(self, mode) + self.lora_train(mode) + + def forward(self, x: torch.Tensor, **kwargs): + + if self.r > 0 and not self.merged: + self.merge_lora_param() + result = nn.Linear.forward(self, x, **kwargs) + self.sub_lora_data() + return result + else: + return nn.Linear.forward(self, x, **kwargs) + +class Conv1d(nn.Conv1d, LoRALayer): + # LoRA implemented in a Conv1d layer + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + r: int = 0, + lora_alpha: int = 1, + **kwargs + ): + nn.Conv1d.__init__(self, in_channels, out_channels, kernel_size, **kwargs) + LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha) + + assert type(kernel_size) is int + # Actual trainable parameters + self.params_with_lora = {'weight': 'w'} + if r > 0: + self.w_lora_A = nn.Parameter( + self.weight.new_zeros((r*kernel_size, in_channels*kernel_size)) + ) + self.w_lora_B = nn.Parameter( + self.weight.new_zeros((out_channels//self.groups*kernel_size, r*kernel_size)) + ) + # Freezing the pre-trained weight matrix + self.weight.requires_grad = False + nn.Conv1d.reset_parameters(self) + self.init_lora_param() + + def train(self, mode: bool = True): + nn.Conv1d.train(self, mode) + self.lora_train(mode) + + def forward(self, x: torch.Tensor, **kwargs): + + if self.r > 0 and not self.merged: + self.merge_lora_param() + result = nn.Conv1d.forward(self, x, **kwargs) + self.sub_lora_data() + return result + else: + return nn.Conv1d.forward(self, x, **kwargs) + +class Conv2d(nn.Conv2d, LoRALayer): + # LoRA implemented in a Conv2d layer + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + r: int = 0, + lora_alpha: int = 1, + **kwargs + ): + nn.Conv2d.__init__(self, in_channels, out_channels, kernel_size, **kwargs) + LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha) + + assert type(kernel_size) is int + # Actual trainable parameters + self.params_with_lora = {'weight': 'w'} + if r > 0: + self.w_lora_A = nn.Parameter( + self.weight.new_zeros((r*kernel_size, in_channels*kernel_size)) + ) + self.w_lora_B = nn.Parameter( + self.weight.new_zeros((out_channels//self.groups*kernel_size, r*kernel_size)) + ) + # Freezing the pre-trained weight matrix + self.weight.requires_grad = False + nn.Conv2d.reset_parameters(self) + self.init_lora_param() + + def train(self, mode: bool = True): + nn.Conv2d.train(self, mode) + self.lora_train(mode) + + def forward(self, x: torch.Tensor, **kwargs): + + if self.r > 0 and not self.merged: + self.merge_lora_param() + result = nn.Conv2d.forward(self, x, **kwargs) + self.sub_lora_data() + return result + else: + return nn.Conv2d.forward(self, x, **kwargs) + +class Conv3d(nn.Conv3d, LoRALayer): + # LoRA implemented in a Conv3d layer + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + r: int = 0, + lora_alpha: int = 1, + **kwargs + ): + nn.Conv3d.__init__(self, in_channels, out_channels, kernel_size, **kwargs) + LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha) + + assert type(kernel_size) is int + # Actual trainable parameters + self.params_with_lora = {'weight': 'w'} + if r > 0: + self.w_lora_A = nn.Parameter( + self.weight.new_zeros((r*kernel_size, in_channels*kernel_size)) + ) + self.w_lora_B = nn.Parameter( + self.weight.new_zeros((out_channels//self.groups*kernel_size, r*kernel_size)) + ) + # Freezing the pre-trained weight matrix + self.weight.requires_grad = False + nn.Conv3d.reset_parameters(self) + self.init_lora_param() + + def train(self, mode: bool = True): + nn.Conv3d.train(self, mode) + self.lora_train(mode) + + def forward(self, x: torch.Tensor, **kwargs): + + if self.r > 0 and not self.merged: + self.merge_lora_param() + result = nn.Conv3d.forward(self, x, **kwargs) + self.sub_lora_data() + return result + else: + return nn.Conv3d.forward(self, x, **kwargs) + +class LoRALayer(): + def __init__( + self, + r: int, + lora_alpha: int, + fan_in_fan_out: bool = False, + ): + self.r = r + self.lora_alpha = lora_alpha + if self.r > 0: + self.scaling = self.lora_alpha / self.r + # Mark the weight as unmerged + self.merged = False + # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + self.fan_in_fan_out = fan_in_fan_out + # define params that require LoRA {'param_name': 'lora_name'} + self.params_with_lora = {} + + def register_lora_param(self): + r"""Register LoRA matrix""" + for param_name, lora_name in self.params_with_lora.items(): + assert len(eval(f'self.{param_name}').size()) == 2 + self.register_parameter(f'{lora_name}_lora_A', + nn.Parameter(eval(f'self.{param_name}').new_zeros((self.r, eval(f'self.{param_name}').size()[1]))) + ) + self.register_parameter(f'{lora_name}_lora_B', + nn.Parameter(eval(f'self.{param_name}').new_zeros((eval(f'self.{param_name}').size()[0], self.r))) + ) + eval(f'self.{param_name}').requires_grad = False + + def init_lora_param(self): + for param_name, lora_name in self.params_with_lora.items(): + if hasattr(self, f'{lora_name}_lora_A'): + # initialize A the same way as the default for nn.Linear and B to zero + nn.init.kaiming_uniform_(eval(f'self.{lora_name}_lora_A'), a=math.sqrt(5)) + nn.init.zeros_(eval(f'self.{lora_name}_lora_B')) + + def transpose(self, w: torch.Tensor): + return w.transpose(0, 1) if self.fan_in_fan_out else w + + def merge_BA(self, param_name: str): + lora_name = self.params_with_lora[param_name] + return self.transpose((eval(f'self.{lora_name}_lora_B') @ eval(f'self.{lora_name}_lora_A')).view(eval(f'self.{param_name}').shape)) + + def merge_lora_param(self): + r"""p_new = p + scaling * B @ A and keep differentiable to A and B""" + for param_name, lora_name in self.params_with_lora.items(): + p = set_param(self, param_name, mode='get') + # detach() is very important here + p_new = p.detach() + self.merge_BA(param_name) * self.scaling + set_param(self, param_name, param=p_new, mode='update') + + def add_lora_data(self): + r"""NOT differentiable""" + for param_name, lora_name in self.params_with_lora.items(): + eval(f'self.{param_name}').data += self.merge_BA(param_name) * self.scaling + + def sub_lora_data(self): + r"""NOT differentiable""" + for param_name, lora_name in self.params_with_lora.items(): + eval(f'self.{param_name}').data -= self.merge_BA(param_name) * self.scaling + + def lora_train(self, mode: bool = True): + if mode: + if self.merged and self.r > 0: + # Make sure that the weights are not merged + self.sub_lora_data() + self.merged = False + else: + if not self.merged and self.r > 0: + # Merge the weights and mark it + self.add_lora_data() + self.merged = True + +class MultiheadAttention(nn.MultiheadAttention, LoRALayer): + # LoRA implemented in a MultiheadAttention layer + def __init__( + self, + embed_dim: int, + num_heads: int, + enable_lora: list = ['q', 'k', 'v', 'o'], + r: int = 0, + lora_alpha: int = 1, + **kwargs + ): + nn.MultiheadAttention.__init__(self, embed_dim, num_heads, **kwargs) + LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha) + + # Actual trainable parameters + if self.r > 0: + if 'o' in enable_lora: + self.params_with_lora.update({'out_proj.weight': 'o'}) + + if not self._qkv_same_embed_dim: + for n in ['q', 'k', 'v']: + if n in enable_lora: + self.params_with_lora.update({f'{n}_proj_weight': n}) + self.register_lora_param() + nn.MultiheadAttention._reset_parameters(self) + self.init_lora_param() + else: + lora_name, enable_lora_bool = '', [] + for n in ['q', 'k', 'v']: + if n in enable_lora: + lora_name += n + enable_lora_bool.append(True) + else: + enable_lora_bool.append(False) + self.params_with_lora.update({'in_proj_weight': lora_name}) + self.register_lora_param() + nn.MultiheadAttention._reset_parameters(self) + self.init_lora_param_qkv(enable_lora_bool) + + def init_lora_param_qkv(self, enable_lora_bool): + lora_name = self.params_with_lora['in_proj_weight'] + nn.init.zeros_(eval(f'self.{lora_name}_lora_B')) + dim = int(self.in_proj_weight.size()[1] / 3) + for idx, enable in zip(range(3), enable_lora_bool): + if enable: + nn.init.kaiming_uniform_(eval(f'self.{lora_name}_lora_A')[:,idx*dim:(idx+1)*dim], a=math.sqrt(5)) + else: + nn.init.zeros_(eval(f'self.{lora_name}_lora_A')[:,idx*dim:(idx+1)*dim]) + + def train(self, mode: bool = True): + nn.MultiheadAttention.train(self, mode) + self.lora_train(mode) + + def forward(self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + **kwargs): + if self.r > 0 and not self.merged: + self.merge_lora_param() + result = nn.MultiheadAttention.forward(self, query, key, value, **kwargs) + self.sub_lora_data() + return result + else: + return nn.MultiheadAttention.forward(self, query, key, value, **kwargs) + +class MergedLinear(nn.Linear, LoRALayer): + # LoRA implemented in a dense layer + def __init__( + self, + in_features: int, + out_features: int, + r: int = 0, + lora_alpha: int = 1, + enable_lora: List[bool] = [False], + fan_in_fan_out: bool = False, + **kwargs + ): + nn.Linear.__init__(self, in_features, out_features, **kwargs) + LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha) + + assert out_features % len(enable_lora) == 0, \ + 'The length of enable_lora must divide out_features' + self.enable_lora = enable_lora + # Actual trainable parameters + self.params_with_lora = {'weight': 'w'} + if r > 0 and any(enable_lora): + self.w_lora_A = nn.Parameter( + self.weight.new_zeros((r * sum(enable_lora), in_features))) + self.w_lora_B = nn.Parameter( + self.weight.new_zeros((out_features // len(enable_lora) * sum(enable_lora), r)) + ) # weights for Conv1D with groups=sum(enable_lora) + # Freezing the pre-trained weight matrix + self.weight.requires_grad = False + # Compute the indices + self.lora_ind = self.weight.new_zeros( + (out_features, ), dtype=torch.bool + ).view(len(enable_lora), -1) + self.lora_ind[enable_lora, :] = True + self.lora_ind = self.lora_ind.view(-1) + nn.Linear.reset_parameters(self) + self.init_lora_param() + self.weight.data = self.transpose(self.weight.data) + + def zero_pad(self, x): + result = x.new_zeros((len(self.lora_ind), *x.shape[1:])) + result[self.lora_ind] = x + return result + + def merge_BA(self, param_name: str): + lora_name = self.params_with_lora[param_name] + delta_w = F.conv1d( + eval(f'self.{lora_name}_lora_A').unsqueeze(0), + eval(f'self.{lora_name}_lora_B').unsqueeze(-1), + groups=sum(self.enable_lora) + ).squeeze(0) + return self.transpose(self.zero_pad(delta_w)) + + def train(self, mode: bool = True): + nn.Linear.train(self, mode) + self.lora_train(mode) + + def forward(self, x: torch.Tensor, **kwargs): + + if self.r > 0 and not self.merged: + self.merge_lora_param() + result = nn.Linear.forward(self, x, **kwargs) + self.sub_lora_data() + return result + else: + return nn.Linear.forward(self, x, **kwargs) diff --git a/detectors/ForensicConcept/upstream/models/clip/loratorch/utils.py b/detectors/ForensicConcept/upstream/models/clip/loratorch/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d78dfb2e7bd132c942b33eeb1f5efab15c5716e8 --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/clip/loratorch/utils.py @@ -0,0 +1,60 @@ +# ------------------------------------------------------------------------------------------ +# This code is reconstructed based on loralib (https://github.com/microsoft/LoRA) by Baijiong Lin. +# ------------------------------------------------------------------------------------------ +import torch +import torch.nn as nn + +from typing import Dict + +from .layers import LoRALayer + +def print_trainable_parameters(model): + r"""Prints the number of trainable parameters in the model.""" + trainable_params = 0 + all_param = 0 + for _, param in model.named_parameters(): + all_param += param.numel() + if param.requires_grad: + trainable_params += param.numel() + print( + f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param:.2f}" + ) + +def mark_only_lora_as_trainable(model: nn.Module, bias: str = 'none') -> None: + for n, p in model.named_parameters(): + if 'lora_' not in n: + p.requires_grad = False + if bias == 'none': + return + elif bias == 'all': + for n, p in model.named_parameters(): + if 'bias' in n: + p.requires_grad = True + elif bias == 'lora_only': + for m in model.modules(): + if isinstance(m, LoRALayer) and \ + hasattr(m, 'bias') and \ + m.bias is not None: + m.bias.requires_grad = True + else: + raise NotImplementedError + print_trainable_parameters(model) + + +def lora_state_dict(model: nn.Module, bias: str = 'none') -> Dict[str, torch.Tensor]: + my_state_dict = model.state_dict() + if bias == 'none': + return {k: my_state_dict[k] for k in my_state_dict if 'lora_' in k} + elif bias == 'all': + return {k: my_state_dict[k] for k in my_state_dict if 'lora_' in k or 'bias' in k} + elif bias == 'lora_only': + to_return = {} + for k in my_state_dict: + if 'lora_' in k: + to_return[k] = my_state_dict[k] + bias_name = k.split('lora_')[0]+'bias' + if bias_name in my_state_dict: + to_return[bias_name] = my_state_dict[bias_name] + return to_return + else: + raise NotImplementedError diff --git a/detectors/ForensicConcept/upstream/models/clip/model.py b/detectors/ForensicConcept/upstream/models/clip/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c494e1080b401274add8716ff892aa0042fb9314 --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/clip/model.py @@ -0,0 +1,775 @@ +from collections import OrderedDict +from typing import Optional, Tuple, Union +import os + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from . import loratorch +import math + + +DEFAULT_LORA_RANK = 4 +DEFAULT_LORA_ALPHA = 8 + + +def set_lora_config(rank: Optional[int] = None, alpha: Optional[int] = None): + global DEFAULT_LORA_RANK, DEFAULT_LORA_ALPHA + if rank is not None: + DEFAULT_LORA_RANK = max(0, rank) + if alpha is not None: + DEFAULT_LORA_ALPHA = max(1, alpha) + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1): + super().__init__() + + # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 + self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.relu1 = nn.ReLU(inplace=True) + + self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.relu2 = nn.ReLU(inplace=True) + + self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() + + self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.relu3 = nn.ReLU(inplace=True) + + self.downsample = None + self.stride = stride + + if stride > 1 or inplanes != planes * Bottleneck.expansion: + # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 + self.downsample = nn.Sequential(OrderedDict([ + ("-1", nn.AvgPool2d(stride)), + ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), + ("1", nn.BatchNorm2d(planes * self.expansion)) + ])) + + def forward(self, x: torch.Tensor): + identity = x + + out = self.relu1(self.bn1(self.conv1(x))) + out = self.relu2(self.bn2(self.conv2(out))) + out = self.avgpool(out) + out = self.bn3(self.conv3(out)) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu3(out) + return out + + +class AttentionPool2d(nn.Module): + def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): + super().__init__() + self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) + self.k_proj = nn.Linear(embed_dim, embed_dim) + self.q_proj = nn.Linear(embed_dim, embed_dim) + self.v_proj = nn.Linear(embed_dim, embed_dim) + self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) + self.num_heads = num_heads + + def forward(self, x): + x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC + x, _ = F.multi_head_attention_forward( + query=x[:1], key=x, value=x, + embed_dim_to_check=x.shape[-1], + num_heads=self.num_heads, + q_proj_weight=self.q_proj.weight, + k_proj_weight=self.k_proj.weight, + v_proj_weight=self.v_proj.weight, + in_proj_weight=None, + in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), + bias_k=None, + bias_v=None, + add_zero_attn=False, + dropout_p=0, + out_proj_weight=self.c_proj.weight, + out_proj_bias=self.c_proj.bias, + use_separate_proj_weight=True, + training=self.training, + need_weights=False + ) + return x.squeeze(0) + + +class ModifiedResNet(nn.Module): + """ + A ResNet class that is similar to torchvision's but contains the following changes: + - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. + - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 + - The final pooling layer is a QKV attention instead of an average pool + """ + + def __init__(self, layers, output_dim, heads, input_resolution=224, width=64): + super().__init__() + self.output_dim = output_dim + self.input_resolution = input_resolution + + # the 3-layer stem + self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(width // 2) + self.relu1 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(width // 2) + self.relu2 = nn.ReLU(inplace=True) + self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(width) + self.relu3 = nn.ReLU(inplace=True) + self.avgpool = nn.AvgPool2d(2) + + # residual layers + self._inplanes = width # this is a *mutable* variable used during construction + self.layer1 = self._make_layer(width, layers[0]) + self.layer2 = self._make_layer(width * 2, layers[1], stride=2) + self.layer3 = self._make_layer(width * 4, layers[2], stride=2) + self.layer4 = self._make_layer(width * 8, layers[3], stride=2) + + embed_dim = width * 32 # the ResNet feature dimension + self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim) + + def _make_layer(self, planes, blocks, stride=1): + layers = [Bottleneck(self._inplanes, planes, stride)] + + self._inplanes = planes * Bottleneck.expansion + for _ in range(1, blocks): + layers.append(Bottleneck(self._inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x): + def stem(x): + x = self.relu1(self.bn1(self.conv1(x))) + x = self.relu2(self.bn2(self.conv2(x))) + x = self.relu3(self.bn3(self.conv3(x))) + x = self.avgpool(x) + return x + + x = x.type(self.conv1.weight.dtype) + x = stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.attnpool(x) + + return x + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16.""" + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + ret = super().forward(x.type(torch.float32)) + return ret.type(orig_type) + + +class QuickGELU(nn.Module): + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class LayerScale(nn.Module): + def __init__(self, dim: int, init_value: float = 1.0): + super().__init__() + self.gamma = nn.Parameter(torch.ones(dim) * init_value) + + def forward(self, x: torch.Tensor): + return x * self.gamma + + +class Convpass(nn.Module): + def __init__(self, dim=8, xavier_init=False): + super().__init__() + + self.adapter_conv = nn.Conv2d(dim, dim, 3, 1, 1) + if xavier_init: + nn.init.xavier_uniform_(self.adapter_conv.weight) + else: + nn.init.zeros_(self.adapter_conv.weight) + self.adapter_conv.weight.data[:, :, 1, 1] += torch.eye(8, dtype=torch.float) + nn.init.zeros_(self.adapter_conv.bias) + + self.adapter_down = nn.Linear(1024, dim) # equivalent to 1 * 1 Conv + # self.adapter_down = nn.Linear(768, dim) # equivalent to 1 * 1 Conv + # self.adapter_up = nn.Linear(dim, 768) # equivalent to 1 * 1 Conv + self.adapter_up = nn.Linear(dim, 1024) # equivalent to 1 * 1 Conv + nn.init.xavier_uniform_(self.adapter_down.weight) + nn.init.zeros_(self.adapter_down.bias) + nn.init.zeros_(self.adapter_up.weight) + nn.init.zeros_(self.adapter_up.bias) + + self.act = QuickGELU() + self.dropout = nn.Dropout(0.1) + self.dim = dim + + def forward(self, x): + N, B, C = x.shape + + x_down = self.adapter_down(x) # equivalent to 1 * 1 Conv + x_down = self.act(x_down) + + x_patch = x_down[1:, :].reshape(B, 16, 16, self.dim).permute(0, 3, 1, 2) + x_patch = self.adapter_conv(x_patch) + x_patch = x_patch.permute(0, 2, 3, 1).reshape(B, 16 * 16, self.dim) + + x_cls = x_down[:1, :].reshape(B, 1, 1, self.dim).permute(0, 3, 1, 2) + x_cls = self.adapter_conv(x_cls) + x_cls = x_cls.permute(0, 2, 3, 1).reshape(B, 1, self.dim) + + x_down = torch.cat([x_cls, x_patch], dim=1) + + x_down = self.act(x_down) + x_down = self.dropout(x_down) + x_up = self.adapter_up(x_down) # equivalent to 1 * 1 Conv + + x_up = x_up.permute(1, 0, 2) + + return x_up + +class ResidualAttentionBlock(nn.Module): + def __init__( + self, + d_model: int, + n_head: int, + attn_mask: torch.Tensor = None, + mlp_hidden_dim: Optional[int] = None, + ): + super().__init__() + + if DEFAULT_LORA_RANK > 0: + self.attn = loratorch.MultiheadAttention( + d_model, + n_head, + r=DEFAULT_LORA_RANK, + lora_alpha=DEFAULT_LORA_ALPHA, + enable_lora=['q', 'k', 'v'], # ไป…ๅฏน qkv ๅŠ  LoRA๏ผŒๅ…ณ้—ญ out_proj LoRA + ) + else: + self.attn = nn.MultiheadAttention(d_model, n_head) + self.ln_1 = LayerNorm(d_model) + hidden_dim = int(mlp_hidden_dim) if mlp_hidden_dim is not None else d_model * 4 + self.mlp = nn.Sequential(OrderedDict([ + ("c_fc", nn.Linear(d_model, hidden_dim)), + ("gelu", QuickGELU()), + ("c_proj", nn.Linear(hidden_dim, d_model)) + ])) + self.ls_1 = LayerScale(d_model, init_value=1.0) + self.ls_2 = LayerScale(d_model, init_value=1.0) + self.ln_2 = LayerNorm(d_model) + self.attn_mask = attn_mask + # self.adapter_mlp = Convpass() + self.s = 1. + self.store_attn = False + self.track_attn_grad = False + self.attn_storage = [] + + def attention(self, x: torch.Tensor): + self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None + if self.store_attn: + out, attn_weights = self.attn( + x, x, x, need_weights=True, attn_mask=self.attn_mask, average_attn_weights=False + ) + if self.track_attn_grad: + attn_weights.retain_grad() + self.attn_storage.append(attn_weights) + return out + return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] + + def forward(self, x: torch.Tensor): + x = x + self.ls_1(self.attention(self.ln_1(x))) + x = x + self.ls_2(self.mlp(self.ln_2(x))) + # x = x + self.mlp(self.ln_2(x)) + (self.adapter_mlp(self.ln_2(x))) * self.s + return x + + +class Transformer(nn.Module): + def __init__( + self, + width: int, + layers: int, + heads: int, + attn_mask: torch.Tensor = None, + mlp_hidden_dim: Optional[int] = None, + ): + super().__init__() + self.width = width + self.layers = layers + self.resblocks = nn.Sequential( + *[ + ResidualAttentionBlock( + width, + heads, + attn_mask, + mlp_hidden_dim=mlp_hidden_dim, + ) + for _ in range(layers) + ] + ) + # Load pre-saved initialization from NPR if available. + # NOTE: removed custom resblocks init load to avoid shape mismatch; base CLIP weights are used as-is. + + def enable_attention_tracking(self, track_grad: bool = False): + for block in self.resblocks: + block.store_attn = True + block.track_attn_grad = bool(track_grad) + block.attn_storage = [] + + def clear_attention_storage(self): + for block in self.resblocks: + block.attn_storage = [] + + def forward(self, x: torch.Tensor): + out = {} + for idx, layer in enumerate(self.resblocks.children()): + x = layer(x) + out['layer'+str(idx)] = x[0] # shape:LND. choose cls token feature + return out, x + + # return self.resblocks(x) # This is the original code + + +class VisionTransformer(nn.Module): + def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int): + super().__init__() + self.input_resolution = input_resolution + self.output_dim = output_dim + self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) + self.grid_size = input_resolution // patch_size + + scale = width ** -0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) + self.ln_pre = LayerNorm(width) + + self.transformer = Transformer(width, layers, heads) + + self.ln_post = LayerNorm(width) + self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) + + + + def _encode_tokens(self, x: torch.Tensor): + x = self.conv1(x) # shape = [*, width, grid_h, grid_w] + grid_h, grid_w = x.shape[-2], x.shape[-1] + + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + + class_embed = self.class_embedding.to(x.dtype) + class_embed = class_embed + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device) + x = torch.cat([class_embed, x], dim=1) # shape = [*, grid ** 2 + 1, width] + + if grid_h != self.grid_size or grid_w != self.grid_size: + patch_pos = self.positional_embedding[1:] + patch_pos = patch_pos.reshape(1, self.grid_size, self.grid_size, -1).permute(0, 3, 1, 2) + patch_pos = F.interpolate(patch_pos, size=(grid_h, grid_w), mode='bicubic', align_corners=False) + patch_pos = patch_pos.permute(0, 2, 3, 1).reshape(grid_h * grid_w, -1) + pos_embed = torch.cat([self.positional_embedding[:1], patch_pos], dim=0) + else: + pos_embed = self.positional_embedding + + x = x + pos_embed.to(x.dtype) + x = self.ln_pre(x) + + x = x.permute(1, 0, 2) # NLD -> LND + out, x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_post(x) + out['before_projection'] = x + if self.proj is not None: + x = x @ self.proj + out['after_projection'] = x + + cls = x[:, 0, :] + return cls, x + + def forward(self, x: torch.Tensor): + cls, _ = self._encode_tokens(x) + return cls + + def forward_with_tokens(self, x: torch.Tensor): + return self._encode_tokens(x) + + # Return both intermediate features and final clip feature + # return out + + # This only returns CLIP features + return x + + def enable_attention_tracking(self, track_grad: bool = False): + self.transformer.enable_attention_tracking(track_grad=track_grad) + + def clear_attention_storage(self): + self.transformer.clear_attention_storage() + + +class PerceptionVisionTransformer(nn.Module): + """ + Vision-only transformer used by Perception Encoder checkpoints. + Unlike OpenAI CLIP ViT, this backbone has no class token/projection heads. + """ + + def __init__( + self, + input_resolution: int, + patch_size: int, + width: int, + layers: int, + heads: int, + num_pos_tokens: int, + mlp_hidden_dim: Optional[int] = None, + ): + super().__init__() + self.input_resolution = int(input_resolution) + self.patch_size = int(patch_size) + self.output_dim = int(width) + self.grid_size = self.input_resolution // self.patch_size + self.num_pos_tokens = int(num_pos_tokens) + + self.conv1 = nn.Conv2d( + in_channels=3, + out_channels=width, + kernel_size=self.patch_size, + stride=self.patch_size, + bias=False, + ) + scale = width ** -0.5 + self.positional_embedding = nn.Parameter(scale * torch.randn(self.num_pos_tokens, width)) + self.ln_pre = LayerNorm(width) + self.transformer = Transformer(width, layers, heads, mlp_hidden_dim=mlp_hidden_dim) + + def _resize_positional_embedding(self, grid_h: int, grid_w: int, dtype: torch.dtype) -> torch.Tensor: + if self.positional_embedding.shape[0] == grid_h * grid_w: + return self.positional_embedding.to(dtype) + + base_grid = round(self.positional_embedding.shape[0] ** 0.5) + if base_grid * base_grid != self.positional_embedding.shape[0]: + raise ValueError( + f"Invalid positional embedding length {self.positional_embedding.shape[0]} " + f"for PE backbone (expected perfect square)." + ) + + patch_pos = self.positional_embedding.reshape(base_grid, base_grid, -1).permute(2, 0, 1).unsqueeze(0) + patch_pos = F.interpolate(patch_pos, size=(grid_h, grid_w), mode="bicubic", align_corners=False) + patch_pos = patch_pos.squeeze(0).permute(1, 2, 0).reshape(grid_h * grid_w, -1) + return patch_pos.to(dtype) + + def _encode_tokens(self, x: torch.Tensor): + x = self.conv1(x) # [B,C,H',W'] + grid_h, grid_w = x.shape[-2], x.shape[-1] + x = x.reshape(x.shape[0], x.shape[1], -1).permute(0, 2, 1) # [B,N,C] + + pos_embed = self._resize_positional_embedding(grid_h, grid_w, x.dtype) + x = x + pos_embed + x = self.ln_pre(x) + + x = x.permute(1, 0, 2) # NLD -> LND + _, x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + + pooled = x.mean(dim=1) + # Keep CLIP-compatible output shape expected by downstream wrapper: + # prepend pooled token so callers can strip [:, 1:, :] as patch tokens. + tokens_with_pooled = torch.cat([pooled.unsqueeze(1), x], dim=1) + return pooled, tokens_with_pooled + + def forward(self, x: torch.Tensor): + pooled, _ = self._encode_tokens(x) + return pooled + + def forward_with_tokens(self, x: torch.Tensor): + return self._encode_tokens(x) + + def enable_attention_tracking(self, track_grad: bool = False): + self.transformer.enable_attention_tracking(track_grad=track_grad) + + def clear_attention_storage(self): + self.transformer.clear_attention_storage() + + +class PerceptionCLIPWrapper(nn.Module): + """ + Minimal CLIP-like wrapper around PE visual backbone. + Exposes encode_image / encode_image_with_tokens used by CLIPModel. + """ + + def __init__(self, visual: PerceptionVisionTransformer): + super().__init__() + self.visual = visual + + @property + def dtype(self): + return self.visual.conv1.weight.dtype + + def encode_image(self, image: torch.Tensor): + return self.visual(image.type(self.dtype)) + + def encode_image_with_tokens(self, image: torch.Tensor): + return self.visual.forward_with_tokens(image.type(self.dtype)) + + +class CLIP(nn.Module): + def __init__(self, + embed_dim: int, + # vision + image_resolution: int, + vision_layers: Union[Tuple[int, int, int, int], int], + vision_width: int, + vision_patch_size: int, + # text + context_length: int, + vocab_size: int, + transformer_width: int, + transformer_heads: int, + transformer_layers: int + ): + super().__init__() + self.context_length = context_length + + if isinstance(vision_layers, (tuple, list)): + vision_heads = vision_width * 32 // 64 + self.visual = ModifiedResNet( + layers=vision_layers, + output_dim=embed_dim, + heads=vision_heads, + input_resolution=image_resolution, + width=vision_width + ) + else: + vision_heads = vision_width // 64 + self.visual = VisionTransformer( + input_resolution=image_resolution, + patch_size=vision_patch_size, + width=vision_width, + layers=vision_layers, + heads=vision_heads, + output_dim=embed_dim + ) + + # ๆ–‡ๆœฌไพงไธ็”จ LoRA๏ผŒไธดๆ—ถๅฐ† LoRA ้…็ฝฎ็ฝฎ้›ถๅŽๅ†ๆขๅค๏ผŒ้ฟๅ…ไฟฎๆ”นๆŽฅๅฃๆˆ–ๅฝฑๅ“่ง†่ง‰ไพง + _old_rank, _old_alpha = DEFAULT_LORA_RANK, DEFAULT_LORA_ALPHA + try: + set_lora_config(rank=0, alpha=_old_alpha) + self.transformer = Transformer( + width=transformer_width, + layers=transformer_layers, + heads=transformer_heads, + attn_mask=self.build_attention_mask() + ) + finally: + set_lora_config(rank=_old_rank, alpha=_old_alpha) + + self.vocab_size = vocab_size + self.token_embedding = nn.Embedding(vocab_size, transformer_width) + self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) + self.ln_final = LayerNorm(transformer_width) + + self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + self.initialize_parameters() + + def initialize_parameters(self): + nn.init.normal_(self.token_embedding.weight, std=0.02) + nn.init.normal_(self.positional_embedding, std=0.01) + + if isinstance(self.visual, ModifiedResNet): + if self.visual.attnpool is not None: + std = self.visual.attnpool.c_proj.in_features ** -0.5 + nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std) + nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std) + nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std) + nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std) + + for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]: + for name, param in resnet_block.named_parameters(): + if name.endswith("bn3.weight"): + nn.init.zeros_(param) + + proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) + attn_std = self.transformer.width ** -0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.context_length, self.context_length) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + @property + def dtype(self): + return self.visual.conv1.weight.dtype + + def encode_image(self, image): + return self.visual(image.type(self.dtype)) + + def encode_image_with_tokens(self, image): + if not hasattr(self.visual, "forward_with_tokens"): + raise RuntimeError("Visual backbone does not support token outputs.") + return self.visual.forward_with_tokens(image.type(self.dtype)) + + def encode_text(self, text): + x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding.type(self.dtype) + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x).type(self.dtype) + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + + return x + + def forward(self, image, text): + image_features = self.encode_image(image) + text_features = self.encode_text(text) + + # normalized features + image_features = image_features / image_features.norm(dim=1, keepdim=True) + text_features = text_features / text_features.norm(dim=1, keepdim=True) + + # cosine similarity as logits + logit_scale = self.logit_scale.exp() + logits_per_image = logit_scale * image_features @ text_features.t() + logits_per_text = logits_per_image.t() + + # shape = [global_batch_size, global_batch_size] + return logits_per_image, logits_per_text + + +def convert_weights(model: nn.Module): + """Convert applicable model parameters to fp16""" + + def _convert_weights_to_fp16(l): + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): + l.weight.data = l.weight.data.half() + if l.bias is not None: + l.bias.data = l.bias.data.half() + + if isinstance(l, nn.MultiheadAttention): + for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: + tensor = getattr(l, attr) + if tensor is not None: + tensor.data = tensor.data.half() + + for name in ["text_projection", "proj"]: + if hasattr(l, name): + attr = getattr(l, name) + if attr is not None: + attr.data = attr.data.half() + + model.apply(_convert_weights_to_fp16) + + +def build_pe_model(state_dict: dict): + required_keys = ["conv1.weight", "ln_pre.weight", "ln_pre.bias", "positional_embedding"] + for key in required_keys: + if key not in state_dict: + raise KeyError(f"Missing key `{key}` in PE checkpoint") + + vision_width = state_dict["conv1.weight"].shape[0] + vision_patch_size = state_dict["conv1.weight"].shape[-1] + num_pos_tokens = state_dict["positional_embedding"].shape[0] + grid_size = round(num_pos_tokens ** 0.5) + if grid_size * grid_size != num_pos_tokens: + raise ValueError( + f"PE positional_embedding length {num_pos_tokens} is not a perfect square." + ) + image_resolution = vision_patch_size * grid_size + vision_layers = len( + [ + k + for k in state_dict.keys() + if k.startswith("transformer.resblocks.") and k.endswith(".attn.in_proj_weight") + ] + ) + mlp_hidden_dim = int(state_dict["transformer.resblocks.0.mlp.c_fc.weight"].shape[0]) + vision_heads = max(1, vision_width // 64) + + visual = PerceptionVisionTransformer( + input_resolution=image_resolution, + patch_size=vision_patch_size, + width=vision_width, + layers=vision_layers, + heads=vision_heads, + num_pos_tokens=num_pos_tokens, + mlp_hidden_dim=mlp_hidden_dim, + ) + + missing, unexpected = visual.load_state_dict(state_dict, strict=False) + missing_non_lora = [k for k in missing if "lora_" not in k] + if unexpected: + print(f"[PE] Unexpected checkpoint keys (showing up to 8): {unexpected[:8]}") + if missing_non_lora: + print(f"[PE] Missing checkpoint keys (showing up to 8): {missing_non_lora[:8]}") + + return PerceptionCLIPWrapper(visual).eval() + + +def build_model(state_dict: dict): + vit = "visual.proj" in state_dict + + if vit: + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) + image_resolution = vision_patch_size * grid_size + else: + counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]] + vision_layers = tuple(counts) + vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] + output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) + vision_patch_size = None + assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] + image_resolution = output_width * 32 + + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks"))) + + model = CLIP( + embed_dim, + image_resolution, vision_layers, vision_width, vision_patch_size, + context_length, vocab_size, transformer_width, transformer_heads, transformer_layers + ) + + for key in ["input_resolution", "context_length", "vocab_size"]: + if key in state_dict: + del state_dict[key] + + convert_weights(model) + model.load_state_dict(state_dict, strict=False) + + return model.eval() diff --git a/detectors/ForensicConcept/upstream/models/clip/simple_tokenizer.py b/detectors/ForensicConcept/upstream/models/clip/simple_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..0a66286b7d5019c6e221932a813768038f839c91 --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/clip/simple_tokenizer.py @@ -0,0 +1,132 @@ +import gzip +import html +import os +from functools import lru_cache + +import ftfy +import regex as re + + +@lru_cache() +def default_bpe(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz") + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = list(range(ord("!"), ord("~")+1))+list(range(ord("ยก"), ord("ยฌ")+1))+list(range(ord("ยฎ"), ord("รฟ")+1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8+n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe()): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') + merges = merges[1:49152-256-2+1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v+'' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + vocab.extend(['<|startoftext|>', '<|endoftext|>']) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'} + self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + ( token[-1] + '',) + pairs = get_pairs(word) + + if not pairs: + return token+'' + + while True: + bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word)-1 and word[i+1] == second: + new_word.append(first+second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ') + return text diff --git a/detectors/ForensicConcept/upstream/models/clip_models.py b/detectors/ForensicConcept/upstream/models/clip_models.py new file mode 100644 index 0000000000000000000000000000000000000000..d8cef300e463b1401d6ba5ded9d36ed6bbab40d8 --- /dev/null +++ b/detectors/ForensicConcept/upstream/models/clip_models.py @@ -0,0 +1,276 @@ +import os + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .clip import clip, set_lora_config + + +CHANNELS = { + "RN50": 1024, + "ViT-L/14": 768, + "ViT-L/14@336px": 768, + "PE-Lang-L14-448": 1024, + "PE-Lang-G14-448": 1536, + "PE-Core-G14-448": 1536, +} + + +def _load_codebook(path: str) -> torch.Tensor: + """Load codebook from .npy or .pt/.pth""" + if path is None: + raise ValueError("codebook_path is None") + if path.endswith(".npy"): + arr = np.load(path) + cb = torch.from_numpy(arr).float() + else: + obj = torch.load(path, map_location="cpu") + if isinstance(obj, dict): + for k in ["codebook", "centroids", "C"]: + if k in obj: + obj = obj[k] + break + cb = obj.float() if torch.is_tensor(obj) else torch.tensor(obj, dtype=torch.float32) + if cb.ndim != 2: + raise ValueError(f"codebook must be 2D, got {tuple(cb.shape)} from {path}") + return cb + + +class CodebookTopKHead(nn.Module): + """ + Top-k patch pooling guided by codebook similarity. + tokens: [B,N,dim_x] + codebook: [K,dim_c] (assumed L2 normalized if clip_codebook_l2=True at load) + """ + + def __init__( + self, + dim_x: int, + dim_c: int, + num_concepts: int, + tau: float = 0.1, + tau_w: float = 0.1, + topk_m: int = 20, + top_r: int = 8, + weight_mode: str = "score", + l2_codebook: bool = True, + freeze_codebook: bool = True, + mlp_hidden: int = None, + ): + super().__init__() + self.dim_x = dim_x + self.dim_c = dim_c + self.num_concepts = num_concepts + self.tau = tau + self.tau_w = tau_w + self.topk_m = topk_m + self.top_r = top_r + self.weight_mode = (weight_mode or "score").lower() + self.l2_codebook = l2_codebook + self.freeze_codebook = freeze_codebook + + self.w_q = nn.Linear(dim_x, dim_c, bias=False) + self.register_buffer("codebook", torch.empty(num_concepts, dim_c), persistent=True) + + hidden = mlp_hidden if mlp_hidden is not None else dim_x + self.mlp = nn.Sequential( + nn.LayerNorm(dim_x), + nn.Linear(dim_x, hidden), + nn.GELU(), + nn.Linear(hidden, 1), + ) + + @torch.no_grad() + def set_codebook(self, codebook: torch.Tensor): + if codebook.shape != self.codebook.shape: + raise ValueError( + f"codebook shape mismatch: got {tuple(codebook.shape)} expected {tuple(self.codebook.shape)}" + ) + cb = codebook.float() + if self.l2_codebook: + cb = F.normalize(cb, dim=-1) + self.codebook.copy_(cb) + + def forward(self, tokens: torch.Tensor, return_feature: bool = False): + """ + returns: + logits_cb: [B,1] + score: [B,N] + idx: [B,m] + """ + bsz, num_patches, dim_x = tokens.shape + if dim_x != self.dim_x: + raise ValueError(f"tokens dim mismatch: {dim_x} vs {self.dim_x}") + + q_raw = self.w_q(tokens) + q = F.normalize(q_raw, dim=-1) + k = self.codebook.detach() if self.freeze_codebook else self.codebook + + s = torch.matmul(q, k.t()) / max(self.tau, 1e-8) + r = int(self.top_r) if self.top_r else 1 + r = min(r, s.shape[-1]) + top_vals, top_ids = s.topk(k=r, dim=-1) + score = top_vals.mean(dim=-1) + + m = int(self.topk_m) if self.topk_m else num_patches + m = min(m, num_patches) + score_sel, idx = torch.topk(score, k=m, dim=1) + top_ids_sel = top_ids.gather(1, idx.unsqueeze(-1).expand(-1, -1, top_ids.shape[-1])) + concept_id = s.argmax(dim=-1) + topk_concept = concept_id.gather(1, idx) + + x_sel = tokens.gather(1, idx.unsqueeze(-1).expand(-1, -1, dim_x)) + if self.weight_mode == "score": + patch_weight = score_sel + elif self.weight_mode == "concept": + s_sel = s.gather(1, idx.unsqueeze(-1).expand(-1, -1, s.shape[-1])) + concept_prob = F.softmax(s_sel, dim=-1) + patch_weight = concept_prob.max(dim=-1).values + else: + raise ValueError(f"Unsupported weight_mode: {self.weight_mode}") + + w = F.softmax(patch_weight / max(self.tau_w, 1e-8), dim=1) + g = (w.unsqueeze(-1) * x_sel).sum(dim=1) + + logits_cb = self.mlp(g) + if return_feature: + return logits_cb, score, idx, top_ids_sel, g + return logits_cb, score, idx, top_ids_sel + + +class CLIPModel(nn.Module): + """CLIP wrapper: CLS head + codebook top-k head.""" + + def __init__(self, name, num_classes=1, opt=None): + super().__init__() + + clip_rank = getattr(opt, "clip_lora_rank", 4) if opt is not None else 4 + clip_alpha = getattr(opt, "clip_lora_alpha", 8) if opt is not None else 8 + set_lora_config(rank=clip_rank, alpha=clip_alpha) + + load_init = True if opt is None else bool(getattr(opt, "clip_load_init_weights", True)) + os.environ["CLIP_USE_INIT"] = "1" if load_init else "0" + + weight_path = getattr(opt, "clip_model_path", None) + load_target = weight_path if weight_path else name + self.model, self.preprocess = clip.load(load_target, device="cpu") + + # If explicit checkpoint path is provided, trust loaded model metadata first. + in_features = None + if weight_path: + in_features = getattr(self.model.visual, "output_dim", None) + if in_features is None: + in_features = CHANNELS.get(name) + if in_features is None: + in_features = getattr(self.model.visual, "output_dim", None) + if in_features is None: + with torch.no_grad(): + res = getattr(self.model.visual, "input_resolution", 224) + dummy = torch.zeros(1, 3, res, res) + in_features = self.model.encode_image(dummy).shape[-1] + + self.dim_x = int(in_features) + self.opt = opt + self.use_main_head = bool(getattr(opt, "clip_use_main_head", True)) + if not self.use_main_head: + raise ValueError("clip_use_main_head must be True for this CLIP head.") + + num_patches = getattr(opt, "clip_num_patches", None) if opt is not None else None + if not num_patches: + patch_size = getattr(self.model.visual, "patch_size", None) + crop_size = getattr(opt, "cropSize", None) if opt is not None else None + if patch_size and crop_size: + grid = int(crop_size) // int(patch_size) + num_patches = grid * grid + if not num_patches: + raise ValueError("clip_num_patches is required (or provide cropSize to infer it).") + self.num_patches = int(num_patches) + + self.codebook_path = getattr(opt, "clip_codebook_path", None) if opt is not None else None + self.use_codebook_inject = bool(getattr(opt, "clip_use_codebook_inject", True)) if opt is not None else True + self.cb_detach_tokens = bool(getattr(opt, "clip_cb_detach_tokens", False)) if opt is not None else False + + self.dim_c = int(getattr(opt, "clip_codebook_dim", 1280)) if opt is not None else 1280 + self.num_concepts = int(getattr(opt, "clip_num_concepts", 200)) if opt is not None else 200 + + tau = float(getattr(opt, "clip_tau", 0.1)) if opt is not None else 0.1 + + l2_codebook = bool(getattr(opt, "clip_codebook_l2", True)) if opt is not None else True + freeze_codebook = bool(getattr(opt, "clip_freeze_codebook", True)) if opt is not None else True + + self.codebook_head = None + if self.use_codebook_inject: + if not self.codebook_path: + raise ValueError("clip_use_codebook_inject=True but clip_codebook_path is None") + + topk_m = int(getattr(opt, "clip_cb_topk", 20)) if opt is not None else 20 + top_r = int(getattr(opt, "clip_cb_topr", 8)) if opt is not None else 8 + tau_w = float(getattr(opt, "clip_cb_tau_w", 0.1)) if opt is not None else 0.1 + weight_mode = getattr(opt, "clip_cb_weight_mode", "score") if opt is not None else "score" + mlp_hidden = getattr(opt, "clip_cb_mlp_hidden", None) if opt is not None else None + + self.codebook_head = CodebookTopKHead( + dim_x=self.dim_x, + dim_c=self.dim_c, + num_concepts=self.num_concepts, + tau=tau, + tau_w=tau_w, + topk_m=topk_m, + top_r=top_r, + weight_mode=weight_mode, + l2_codebook=l2_codebook, + freeze_codebook=freeze_codebook, + mlp_hidden=mlp_hidden, + ) + + cb = _load_codebook(self.codebook_path) + if cb.shape[0] != self.num_concepts or cb.shape[1] != self.dim_c: + raise ValueError( + f"Loaded codebook shape {tuple(cb.shape)} != ({self.num_concepts},{self.dim_c})" + ) + self.codebook_head.set_codebook(cb) + + self.fc = nn.Linear(self.dim_x, num_classes) + + def forward(self, x, return_feature=False, return_debug=False): + """ + returns: + logits: [B,num_classes] + tokens: original patch tokens (CLS removed) + logits_cb: [B,1] (if enabled) + """ + cls, tokens = self.model.encode_image_with_tokens(x) + tokens = tokens[:, 1:, :] + if tokens.shape[1] != self.num_patches: + raise ValueError( + f"num_patches mismatch: tokens has {tokens.shape[1]} patches, expected {self.num_patches}" + ) + + logits_cls = self.fc(cls) + if self.use_codebook_inject: + if self.codebook_head is None: + raise RuntimeError("Codebook head is not initialized.") + cb_tokens = tokens.detach() if self.cb_detach_tokens else tokens + logits_cb, score, idx, topk_concept = self.codebook_head(cb_tokens) + else: + logits_cb, score, idx, topk_concept = None, None, None, None + + if return_feature: + return cls + + logits = logits_cls + + out = { + "logits": logits, + "cb_only": logits_cb, + "tokens": tokens, + } + if return_debug and score is not None: + out.update({ + "codebook_score": score, + "codebook_topk_idx": idx, + "codebook_topk_concept": topk_concept, + }) + return out diff --git a/detectors/ForensicConcept/upstream/networks/__init__.py b/detectors/ForensicConcept/upstream/networks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/detectors/ForensicConcept/upstream/networks/base_model.py b/detectors/ForensicConcept/upstream/networks/base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..f865025f13c5a078e0a5e9cf3a49a47232cf3663 --- /dev/null +++ b/detectors/ForensicConcept/upstream/networks/base_model.py @@ -0,0 +1,273 @@ +# from pix2pix +import os +import torch +import torch.nn as nn +from models.clip import loratorch + + +def _parse_primary_gpu_id(gpu_ids): + if gpu_ids is None: + return -1 + if isinstance(gpu_ids, (list, tuple)): + if not gpu_ids: + return -1 + try: + return int(gpu_ids[0]) + except (TypeError, ValueError): + return -1 + if isinstance(gpu_ids, str): + parts = [part.strip() for part in gpu_ids.split(',') if part.strip()] + if not parts: + return -1 + try: + return int(parts[0]) + except ValueError: + return -1 + try: + return int(gpu_ids) + except (TypeError, ValueError): + return -1 + + +class BaseModel(nn.Module): + def __init__(self, opt): + super(BaseModel, self).__init__() + self.opt = opt + self.total_steps = 0 + self.isTrain = opt.isTrain + self.lr = opt.lr + self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) + self.resume_name = getattr(opt, "resume_name", None) + self.load_dir = os.path.join(opt.checkpoints_dir, self.resume_name or opt.name) + os.makedirs(self.save_dir, exist_ok=True) + self.rank = int(getattr(opt, "rank", 0) or 0) + self.is_main_process = self.rank == 0 + local_rank = int(getattr(opt, "local_rank", -1) or -1) + if torch.cuda.is_available(): + if local_rank >= 0: + self.device = torch.device(f"cuda:{local_rank}") + else: + gpu_id = _parse_primary_gpu_id(getattr(opt, "gpu_ids", None)) + self.device = torch.device(f"cuda:{gpu_id}") if gpu_id >= 0 else torch.device("cpu") + else: + self.device = torch.device('cpu') + + def _unwrap_model(self): + return self.model.module if hasattr(self.model, "module") else self.model + + def save_networks(self, epoch): + if not self.is_main_process: + return + save_filename = 'model_epoch_%s.pth' % epoch + save_path = os.path.join(self.save_dir, save_filename) + model_ref = self._unwrap_model() + + if getattr(self.opt, "trainmode", None) == "lora": + state_dict = { + 'backbone': getattr(model_ref, "model", None).state_dict() if getattr(self.opt, "save_backbone", False) else None, + 'lora': loratorch.lora_state_dict(model_ref), + 'optimizer': self.optimizer.state_dict(), + 'total_steps': self.total_steps, + } + if hasattr(model_ref, "fc"): + state_dict['fc'] = model_ref.fc.state_dict() + if getattr(model_ref, "codebook_head", None) is not None: + state_dict['codebook_head'] = model_ref.codebook_head.state_dict() + torch.save(state_dict, save_path) + print(f'Saving model {save_path}') + elif getattr(self.opt, "trainmode", None) == "dinov3" and getattr(model_ref, "using_lora", False): + state_dict = { + 'head': model_ref.head.state_dict(), + 'backbone_lora': model_ref.get_lora_state_dict(), + 'optimizer': self.optimizer.state_dict(), + 'total_steps': self.total_steps, + } + if getattr(model_ref, "concept_head", None) is not None: + state_dict['concept_head'] = model_ref.concept_head.state_dict() + if getattr(model_ref, "concept_mapping", None) is not None: + state_dict['concept_mapping'] = model_ref.concept_mapping.state_dict() + torch.save(state_dict, save_path) + print(f'Saving DINOv3 LoRA model {save_path}') + elif getattr(self.opt, "trainmode", None) == "dinov3" and getattr(model_ref, "freeze_backbone", False) and getattr(model_ref, "trainable_blocks", 0) == 0: + # Save only the trainable classifier parameters to keep checkpoints small. + model_state = model_ref.state_dict() + trainable_names = [name for name, param in model_ref.named_parameters() if param.requires_grad] + trainable_state = {name: model_state[name].detach().cpu().clone() for name in trainable_names} + checkpoint = { + 'trainable_state': trainable_state, + 'trainable_parameter_names': trainable_names, + 'optimizer': self.optimizer.state_dict() if hasattr(self, 'optimizer') else None, + 'total_steps': self.total_steps, + } + torch.save(checkpoint, save_path) + print(f'Saving DINOv3 trainable parameters {save_path}') + else: + torch.save(model_ref.state_dict(), save_path) + print(f'Saving model {save_path}') + + # load models from the disk + def load_networks(self, epoch): + """Load model/optimizer state. + + Accepts either an epoch tag (e.g., '0.80_0.83') or a full path to a + checkpoint file. This makes explicit checkpoint paths work even when the + directory name differs from `self.load_dir`. + """ + if isinstance(epoch, (str, os.PathLike)) and os.path.isfile(str(epoch)): + load_path = str(epoch) + else: + load_filename = 'model_epoch_%s.pth' % epoch + load_path = os.path.join(self.load_dir, load_filename) + + print('loading the model from %s' % load_path) + state_dict = torch.load(load_path, map_location=self.device) + model_ref = self._unwrap_model() + if hasattr(state_dict, '_metadata'): + del state_dict._metadata + + if isinstance(state_dict, dict) and 'model' in state_dict: + model_ref.load_state_dict(state_dict['model']) + self.total_steps = state_dict.get('total_steps', 0) + if self.isTrain and not self.opt.new_optim and 'optimizer' in state_dict: + self.optimizer.load_state_dict(state_dict['optimizer']) + elif isinstance(state_dict, dict) and 'trainable_state' in state_dict: + current_state = model_ref.state_dict() + for name, tensor in state_dict['trainable_state'].items(): + if name in current_state: + current_state[name] = tensor + else: + print(f"[Checkpoint] Warning: skipped unknown parameter '{name}'") + model_ref.load_state_dict(current_state) + self.total_steps = state_dict.get('total_steps', 0) + if self.isTrain and not self.opt.new_optim and state_dict.get('optimizer'): + self.optimizer.load_state_dict(state_dict['optimizer']) + elif getattr(self.opt, "trainmode", None) == "lora" and isinstance(state_dict, dict): + if 'fc' in state_dict and hasattr(model_ref, "fc"): + model_ref.fc.load_state_dict(state_dict['fc']) + if 'codebook_head' in state_dict and getattr(model_ref, "codebook_head", None) is not None: + if getattr(self.opt, "clip_override_codebook", False): + # Load head weights but keep the codebook buffer from config. + ckpt_state = state_dict['codebook_head'] + current = model_ref.codebook_head.state_dict() + for k, v in ckpt_state.items(): + if k != 'codebook': + current[k] = v + model_ref.codebook_head.load_state_dict(current, strict=False) + else: + model_ref.codebook_head.load_state_dict(state_dict['codebook_head']) + # LoRA state dict may be saved from the wrapper (keys start with 'model.') + # or directly from the CLIP backbone (no prefix). Route to the matching object. + lora_state = state_dict.get('lora', {}) + if any(k.startswith("model.") for k in lora_state): + model_ref.load_state_dict(lora_state, strict=False) + else: + model_ref.model.load_state_dict(lora_state, strict=False) + backbone_state = state_dict.get('backbone') + if backbone_state: + # LoRA backbone state may omit frozen params; allow non-strict load. + model_ref.model.load_state_dict(backbone_state, strict=False) + + # ็กฎไฟ LoRA ๅฑ‚็š„ merged ๆ ‡่ฎฐ่ขซ้‡็ฝฎ๏ผŒ้ฟๅ…ๆŸไบ›ๆฃ€ๆŸฅ็‚นๅŠ ่ฝฝๅŽ merged=True + # ๅฏผ่‡ดๆŽจ็†/่ฎญ็ปƒ้˜ถๆฎต่ทณ่ฟ‡ LoRA ๆƒ้‡็š„ๅˆๅนถใ€‚ + def _reset_lora_merge_flag(module): + if getattr(module, "r", 0) > 0 and hasattr(module, "merged"): + module.merged = False + model_ref.apply(_reset_lora_merge_flag) + + if not self.isTrain: + def _merge_once(module): + if getattr(module, "r", 0) > 0 and hasattr(module, "lora_train"): + try: + module.merged = False # force a fresh merge + module.lora_train(False) + except Exception: + pass + model_ref.apply(_merge_once) + + self.total_steps = state_dict.get('total_steps', 0) + if self.isTrain and not self.opt.new_optim and 'optimizer' in state_dict: + self.optimizer.load_state_dict(state_dict['optimizer']) + elif getattr(self.opt, "trainmode", None) == "dinov3" and getattr(model_ref, "using_lora", False): + # Preferred LoRA checkpoint format (head + backbone_lora). + if isinstance(state_dict, dict) and 'head' in state_dict and 'backbone_lora' in state_dict: + model_ref.head.load_state_dict(state_dict['head']) + model_ref.load_lora_state_dict(state_dict['backbone_lora']) + if 'concept_head' in state_dict and getattr(model_ref, "concept_head", None) is not None: + model_ref.concept_head.load_state_dict(state_dict['concept_head']) + if 'concept_mapping' in state_dict and getattr(model_ref, "concept_mapping", None) is not None: + model_ref.concept_mapping.load_state_dict(state_dict['concept_mapping']) + self.total_steps = state_dict.get('total_steps', 0) + if self.isTrain and not self.opt.new_optim and 'optimizer' in state_dict: + self.optimizer.load_state_dict(state_dict['optimizer']) + else: + # Compatibility path: initialize LoRA run from a full-finetune/plain checkpoint. + loaded_any = False + if isinstance(state_dict, dict): + head_state = { + k[len("head."):]: v + for k, v in state_dict.items() + if isinstance(k, str) and k.startswith("head.") + } + if head_state: + missing, unexpected = model_ref.head.load_state_dict(head_state, strict=False) + print( + f"[Checkpoint] Loaded head from full checkpoint (missing={len(missing)}, " + f"unexpected={len(unexpected)})." + ) + loaded_any = True + + backbone_state = { + k[len("backbone."):]: v + for k, v in state_dict.items() + if isinstance(k, str) and k.startswith("backbone.") + } + if backbone_state: + target_backbone = model_ref.backbone + base_model = getattr(target_backbone, "base_model", None) + if base_model is not None and hasattr(base_model, "model"): + target_backbone = base_model.model + missing, unexpected = target_backbone.load_state_dict(backbone_state, strict=False) + print( + f"[Checkpoint] Loaded backbone base weights into LoRA model " + f"(missing={len(missing)}, unexpected={len(unexpected)})." + ) + loaded_any = True + + if 'concept_head' in state_dict and getattr(model_ref, "concept_head", None) is not None: + model_ref.concept_head.load_state_dict(state_dict['concept_head'], strict=False) + if 'concept_mapping' in state_dict and getattr(model_ref, "concept_mapping", None) is not None: + model_ref.concept_mapping.load_state_dict(state_dict['concept_mapping'], strict=False) + + if not loaded_any: + # Last resort for any custom checkpoint format. + missing, unexpected = model_ref.load_state_dict(state_dict, strict=False) + print( + f"[Checkpoint] Fallback non-strict load for LoRA model " + f"(missing={len(missing)}, unexpected={len(unexpected)})." + ) + self.total_steps = state_dict.get('total_steps', 0) if isinstance(state_dict, dict) else self.total_steps + if self.isTrain and not self.opt.new_optim and isinstance(state_dict, dict) and 'optimizer' in state_dict: + self.optimizer.load_state_dict(state_dict['optimizer']) + else: + model_ref.load_state_dict(state_dict) + self.total_steps = state_dict.get('total_steps', 0) if isinstance(state_dict, dict) else self.total_steps + + if self.isTrain and not self.opt.new_optim and hasattr(self, 'optimizer'): + # move optimizer state to GPU + for state in self.optimizer.state.values(): + for k, v in state.items(): + if torch.is_tensor(v): + state[k] = v.to(self.device) + + for g in self.optimizer.param_groups: + g['lr'] = self.opt.lr + + def eval(self): + self.model.eval() + + def train(self): + self.model.train() + + def test(self): + with torch.no_grad(): + self.forward() diff --git a/detectors/ForensicConcept/upstream/networks/dinov3_detector.py b/detectors/ForensicConcept/upstream/networks/dinov3_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..b1366c44b62ba2834a4d79c98361f6b3f3c9c532 --- /dev/null +++ b/detectors/ForensicConcept/upstream/networks/dinov3_detector.py @@ -0,0 +1,753 @@ +import json +import os +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Union + +import re +from urllib.parse import urlparse + +import numpy as np +import torch +import torch.nn as nn +from safetensors.torch import load_file, safe_open + +try: + from tqdm import tqdm # type: ignore + _TQDM_AVAILABLE = True +except ImportError: # pragma: no cover - fallback when tqdm missing + _TQDM_AVAILABLE = False + + def tqdm(iterable=None, **kwargs): # type: ignore + return iterable if iterable is not None else range(kwargs.get("total", 0)) + +_DINOV3_REPOSITORY_URL = "https://github.com/facebookresearch/dinov3" + + +@dataclass +class Dinov3Config: + variant: str = "vitl16" + backend: str = "official" # official | legacy-compatible external source + repo_path: Optional[str] = None + weights_path: Optional[str] = None + freeze_backbone: bool = True + trainable_blocks: int = 0 + max_blocks: Optional[int] = None + head_hidden_dim: Optional[int] = None + head_dropout: float = 0.1 + use_lora: bool = False + lora_rank: int = 4 + lora_alpha: int = 8 + lora_dropout: float = 0.0 + lora_bias: str = "none" + lora_target_modules: Optional[List[str]] = None + lora_target_last_n: Optional[int] = None + use_concept_head: bool = False + concept_matrix_path: Optional[str] = None + concept_mapping_trainable: bool = False + concept_mapping_bias: bool = False + concept_head_hidden_dim: Optional[int] = None + concept_head_dropout: Optional[float] = None + concept_sparsity_ratio: float = 0.0 + concept_loss_weight: float = 1.0 + concept_eval_sparsity: Optional[List[float]] = None + train_lora: bool = True + disable_rope_train_jitter: bool = False + gradient_checkpointing: bool = False + + +def _normalize_backend(backend: str) -> str: + value = str(backend or "").strip().lower() + if value in {"official", "legacy"}: + return value + raise ValueError(f"Unsupported DINOv3 backend: {backend}. Expected one of: official, legacy.") + + +def _candidate_dinov3_roots(config: Dinov3Config) -> List[Path]: + _normalize_backend(config.backend) + if not config.repo_path: + return [] + return [Path(config.repo_path).expanduser().resolve()] + + +def _ensure_dinov3_importable(config: Dinov3Config) -> Optional[Path]: + for root in _candidate_dinov3_roots(config): + if not (root / "dinov3").is_dir(): + continue + root_str = str(root) + if root_str in sys.path: + sys.path.remove(root_str) + sys.path.insert(0, root_str) + return root + + try: + import dinov3 as dinov3_pkg # type: ignore + + return Path(dinov3_pkg.__file__).resolve().parents[1] + except Exception as exc: # noqa: BLE001 + configured = _candidate_dinov3_roots(config) + checked = "\n".join(f" - {p}" for p in configured) if configured else " - no repository path configured" + raise ImportError( + "Could not import the official DINOv3 package.\n" + f"Clone {_DINOV3_REPOSITORY_URL} and set training.dinov3_repo_path, " + "or install DINOv3 in the active Python environment.\n" + f"Checked:\n{checked}" + ) from exc + + +def _resolve_weights_path(path: Optional[str]) -> Optional[str]: + if not path: + return None + if os.path.isfile(path): + return path + if os.path.isdir(path): + direct_file = os.path.join(path, "model.safetensors") + if os.path.isfile(direct_file): + return direct_file + index_file = os.path.join(path, "model.safetensors.index.json") + if os.path.isfile(index_file): + return index_file + raise FileNotFoundError(f"Could not resolve DINOv3 weights from: {path}") + + +def _is_pth_like(path: str) -> bool: + lower = str(path).lower() + return lower.endswith(".pth") or lower.endswith(".pt") + + +def _is_url(path: str) -> bool: + try: + parsed = urlparse(str(path)) + except Exception: + return False + return parsed.scheme in {"http", "https", "file"} + + +def _load_safetensors(path: str) -> Dict[str, torch.Tensor]: + if path.endswith(".index.json"): + with open(path, "r", encoding="utf-8") as f: + index = json.load(f) + directory = os.path.dirname(path) + state_dict: Dict[str, torch.Tensor] = {} + total_tensors = len(index["weight_map"]) + unique_shards = sorted(set(index["weight_map"].values())) + progress = tqdm(total=total_tensors, desc="Loading DINOv3 weights", unit="tensor") if _TQDM_AVAILABLE else None + for shard_file in unique_shards: + shard_path = os.path.join(directory, shard_file) + with safe_open(shard_path, framework="pt") as f: + for key in f.keys(): + state_dict[key] = f.get_tensor(key) + if progress is not None: + progress.update(1) + if progress is not None: + progress.close() + return state_dict + with safe_open(path, framework="pt") as f: + keys = list(f.keys()) + if _TQDM_AVAILABLE: + progress = tqdm(keys, desc="Loading DINOv3 weights", unit="tensor") + state_dict = {key: f.get_tensor(key) for key in progress} + progress.close() + return state_dict + return {key: f.get_tensor(key) for key in keys} + + +def _dinov3_constructors(config: Dinov3Config): + source_root = _ensure_dinov3_importable(config) + from dinov3.hub import backbones + + backend = _normalize_backend(config.backend) + if source_root is not None: + print(f"[DINOv3] backend={backend}, source={source_root}") + + return { + "vits16": backbones.dinov3_vits16, + "vits16plus": backbones.dinov3_vits16plus, + "vitb16": backbones.dinov3_vitb16, + "vitl16": backbones.dinov3_vitl16, + "vith16plus": backbones.dinov3_vith16plus, + "vit7b16": backbones.dinov3_vit7b16, + "convnext_tiny": backbones.dinov3_convnext_tiny, + "convnext_small": backbones.dinov3_convnext_small, + "convnext_base": backbones.dinov3_convnext_base, + "convnext_large": backbones.dinov3_convnext_large, + } + + +def _sparse_shrink( + x: torch.Tensor, ratio: float, return_mask: bool = False +) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + if ratio <= 0.0: + if return_mask: + mask = torch.ones_like(x, dtype=torch.bool) + return x, mask + return x + + width = x.shape[-1] + if width == 0: + if return_mask: + mask = torch.zeros_like(x, dtype=torch.bool) + return x, mask + return x + + keep = int(width * (1 - ratio)) + keep = max(1, min(width, keep)) + if keep >= width: + if return_mask: + mask = torch.ones_like(x, dtype=torch.bool) + return x, mask + return x + + # kthvalue returns the k-th smallest element, so convert to the keep-th largest + threshold_index = width - keep + 1 + threshold, _ = x.abs().kthvalue(threshold_index, dim=-1, keepdim=True) + mask = x.abs() >= threshold + shrunk = x * mask + if return_mask: + return shrunk, mask + return shrunk + + +def _map_hf_to_dinov3(backbone: nn.Module, hf_state: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: + mapped: Dict[str, torch.Tensor] = {} + if "embeddings.cls_token" in hf_state: + cls_token = hf_state["embeddings.cls_token"] + mapped["cls_token"] = cls_token if cls_token.ndim == 3 else cls_token.unsqueeze(1) + if "embeddings.mask_token" in hf_state: + mask_token = hf_state["embeddings.mask_token"] + if mask_token.ndim == 3: + mask_token = mask_token.squeeze(1) + mapped["mask_token"] = mask_token + if "embeddings.register_tokens" in hf_state and hasattr(backbone, "n_storage_tokens") and backbone.n_storage_tokens: + mapped["storage_tokens"] = hf_state["embeddings.register_tokens"] + if "embeddings.patch_embeddings.weight" in hf_state: + mapped["patch_embed.proj.weight"] = hf_state["embeddings.patch_embeddings.weight"] + if "embeddings.patch_embeddings.bias" in hf_state: + mapped["patch_embed.proj.bias"] = hf_state["embeddings.patch_embeddings.bias"] + + n_blocks = getattr(backbone, "n_blocks", 0) + ref_tensor = next(iter(hf_state.values())) + blocks = getattr(backbone, "blocks", None) + progress = None + iterator: Iterable[int] + if _TQDM_AVAILABLE and n_blocks > 0: + progress = tqdm(range(n_blocks), desc="Mapping DINOv3 blocks", unit="block") + iterator = progress + else: + iterator = range(n_blocks) + + for i in iterator: + prefix = f"layer.{i}." + block_prefix = f"blocks.{i}." + block = blocks[i] if blocks is not None else None + mapped[f"{block_prefix}norm1.weight"] = hf_state[f"{prefix}norm1.weight"] + mapped[f"{block_prefix}norm1.bias"] = hf_state[f"{prefix}norm1.bias"] + mapped[f"{block_prefix}norm2.weight"] = hf_state[f"{prefix}norm2.weight"] + mapped[f"{block_prefix}norm2.bias"] = hf_state[f"{prefix}norm2.bias"] + + q_w = hf_state[f"{prefix}attention.q_proj.weight"] + k_w = hf_state[f"{prefix}attention.k_proj.weight"] + v_w = hf_state[f"{prefix}attention.v_proj.weight"] + mapped[f"{block_prefix}attn.qkv.weight"] = torch.cat([q_w, k_w, v_w], dim=0) + + attn_qkv = getattr(block, "attn", None) + qkv_bias = getattr(attn_qkv, "qkv", None) + has_qkv_bias = bool(qkv_bias is not None and getattr(qkv_bias, "bias", None) is not None) + if has_qkv_bias: + dim = q_w.shape[0] + zeros = torch.zeros(dim, dtype=ref_tensor.dtype, device=ref_tensor.device) + q_b = hf_state.get(f"{prefix}attention.q_proj.bias", zeros) + k_b = hf_state.get(f"{prefix}attention.k_proj.bias", zeros) + v_b = hf_state.get(f"{prefix}attention.v_proj.bias", zeros) + mapped[f"{block_prefix}attn.qkv.bias"] = torch.cat([q_b, k_b, v_b], dim=0) + + mapped[f"{block_prefix}attn.proj.weight"] = hf_state[f"{prefix}attention.o_proj.weight"] + mapped[f"{block_prefix}attn.proj.bias"] = hf_state[f"{prefix}attention.o_proj.bias"] + + if hasattr(block, "mlp") and hasattr(block.mlp, "fc1"): + mapped[f"{block_prefix}mlp.fc1.weight"] = hf_state[f"{prefix}mlp.up_proj.weight"] + mapped[f"{block_prefix}mlp.fc1.bias"] = hf_state[f"{prefix}mlp.up_proj.bias"] + mapped[f"{block_prefix}mlp.fc2.weight"] = hf_state[f"{prefix}mlp.down_proj.weight"] + mapped[f"{block_prefix}mlp.fc2.bias"] = hf_state[f"{prefix}mlp.down_proj.bias"] + elif hasattr(block, "mlp") and all(hasattr(block.mlp, attr) for attr in ("w1", "w2", "w3")): + mapped[f"{block_prefix}mlp.w1.weight"] = hf_state[f"{prefix}mlp.gate_proj.weight"] + mapped[f"{block_prefix}mlp.w1.bias"] = hf_state[f"{prefix}mlp.gate_proj.bias"] + mapped[f"{block_prefix}mlp.w2.weight"] = hf_state[f"{prefix}mlp.up_proj.weight"] + mapped[f"{block_prefix}mlp.w2.bias"] = hf_state[f"{prefix}mlp.up_proj.bias"] + mapped[f"{block_prefix}mlp.w3.weight"] = hf_state[f"{prefix}mlp.down_proj.weight"] + mapped[f"{block_prefix}mlp.w3.bias"] = hf_state[f"{prefix}mlp.down_proj.bias"] + else: + raise RuntimeError( + f"Unsupported MLP structure for block {i}: {type(getattr(block, 'mlp', None))}" + ) + + if f"{prefix}layer_scale1.lambda1" in hf_state: + mapped[f"{block_prefix}ls1.gamma"] = hf_state[f"{prefix}layer_scale1.lambda1"] + if f"{prefix}layer_scale2.lambda1" in hf_state: + mapped[f"{block_prefix}ls2.gamma"] = hf_state[f"{prefix}layer_scale2.lambda1"] + + if progress is not None: + progress.close() + + if "norm.weight" in hf_state: + mapped["norm.weight"] = hf_state["norm.weight"] + if "norm.bias" in hf_state: + mapped["norm.bias"] = hf_state["norm.bias"] + + return mapped + + +def _load_backbone(config: Dinov3Config) -> nn.Module: + constructors = _dinov3_constructors(config) + if config.variant not in constructors: + raise ValueError(f"Unsupported DINOv3 variant: {config.variant}") + constructor = constructors[config.variant] + + raw_weights = config.weights_path + resolved_weights: Optional[str] = None + if raw_weights: + try: + resolved_weights = _resolve_weights_path(raw_weights) + except FileNotFoundError: + # Allow direct URL/file-like .pth path for official DINOv3 checkpoints. + if _is_url(raw_weights) and _is_pth_like(raw_weights): + resolved_weights = raw_weights + else: + raise + + if resolved_weights and _is_pth_like(resolved_weights): + return constructor(pretrained=True, weights=resolved_weights) + + backbone = constructor(pretrained=False) + if resolved_weights: + if not ( + resolved_weights.endswith(".safetensors") + or resolved_weights.endswith(".index.json") + ): + raise RuntimeError( + f"Unsupported DINOv3 weight format: {resolved_weights}. " + "Expected .safetensors/.index.json or .pth/.pt." + ) + hf_state = _load_safetensors(resolved_weights) + mapped_state = _map_hf_to_dinov3(backbone, hf_state) + missing, unexpected = backbone.load_state_dict(mapped_state, strict=False) + unexpected = [k for k in unexpected if not k.endswith("bias_mask")] + if unexpected: + raise RuntimeError(f"Unexpected keys when loading DINOv3 weights: {unexpected}") + if missing: + diff = [ + m + for m in missing + if not ( + m.startswith("rope_embed.") + or m.endswith("bias_mask") + or m.startswith("local_cls_norm.") + ) + ] + if diff: + raise RuntimeError(f"Missing keys when loading DINOv3 weights: {diff}") + return backbone + + +class Dinov3Detector(nn.Module): + def __init__(self, config: Dinov3Config, num_classes: int = 1): + super().__init__() + self.config = config + self.backbone = _load_backbone(config) + self._truncate_backbone_blocks_if_needed() + self._disable_rope_train_jitter_if_needed() + self.patch_size = getattr(self.backbone, "patch_size", None) + embed_dim = getattr(self.backbone, "embed_dim", None) + if embed_dim is None: + raise ValueError("Backbone does not expose embed_dim") + + hidden_dim = config.head_hidden_dim or embed_dim + layers = [] + if hidden_dim != embed_dim: + layers.extend([ + nn.LayerNorm(embed_dim), + nn.Linear(embed_dim, hidden_dim), + nn.GELU(), + nn.Dropout(config.head_dropout), + nn.Linear(hidden_dim, num_classes), + ]) + else: + layers.extend([ + nn.LayerNorm(embed_dim), + nn.Dropout(config.head_dropout), + nn.Linear(embed_dim, num_classes), + ]) + self.head = nn.Sequential(*layers) + + self.use_concept_head = bool(config.use_concept_head) + self.concept_mapping: Optional[nn.Linear] = None + self.concept_head: Optional[nn.Module] = None + if self.use_concept_head: + self._init_concept_modules(embed_dim, num_classes) + + self.freeze_backbone = config.freeze_backbone + self.trainable_blocks = max(0, config.trainable_blocks) + self.using_lora = bool(config.use_lora and config.lora_rank > 0) + self.train_lora = bool(config.train_lora) + self.lora_target_modules: List[str] = [] + if self.using_lora: + self._apply_lora_adapters() + self._configure_trainable_params() + self._enable_gradient_checkpointing_if_needed() + + def _truncate_backbone_blocks_if_needed(self) -> None: + max_blocks = self.config.max_blocks + if max_blocks is None: + return + + try: + max_blocks = int(max_blocks) + except (TypeError, ValueError) as exc: + raise ValueError(f"Invalid dinov3_max_blocks: {self.config.max_blocks}") from exc + + if max_blocks <= 0: + raise ValueError(f"dinov3_max_blocks must be > 0, got {max_blocks}.") + + blocks = getattr(self.backbone, "blocks", None) + if blocks is None: + print("[DINOv3] dinov3_max_blocks is set but backbone has no `blocks`; ignoring.") + return + + total_blocks = len(blocks) + if total_blocks <= 0: + return + keep_blocks = min(max_blocks, total_blocks) + + if keep_blocks < total_blocks: + self.backbone.blocks = nn.ModuleList(list(blocks)[:keep_blocks]) + if hasattr(self.backbone, "n_blocks"): + self.backbone.n_blocks = keep_blocks + print(f"[DINOv3] Truncated transformer blocks: keeping first {keep_blocks}/{total_blocks}.") + else: + print( + f"[DINOv3] dinov3_max_blocks={max_blocks} >= total_blocks={total_blocks}; " + "using all blocks." + ) + + def _enable_gradient_checkpointing_if_needed(self) -> None: + if not bool(self.config.gradient_checkpointing): + return + + def _try_enable(module) -> bool: + if module is None: + return False + for method_name in ("gradient_checkpointing_enable", "enable_gradient_checkpointing"): + method = getattr(module, method_name, None) + if callable(method): + method() + return True + setter = getattr(module, "set_gradient_checkpointing", None) + if callable(setter): + try: + setter(True) + return True + except TypeError: + return False + return False + + enabled = _try_enable(self.backbone) + if not enabled: + enabled = _try_enable(getattr(self.backbone, "base_model", None)) + if enabled: + print("[FullFinetune] DINOv3 gradient checkpointing enabled.") + else: + print("[FullFinetune] gradient_checkpointing requested, but backbone API does not expose it.") + + def _disable_rope_train_jitter_if_needed(self) -> None: + if not bool(getattr(self.config, "disable_rope_train_jitter", False)): + return + rope = getattr(self.backbone, "rope_embed", None) + if rope is None: + return + changed = [] + for attr in ("shift_coords", "jitter_coords", "rescale_coords"): + if getattr(rope, attr, None) is not None: + setattr(rope, attr, None) + changed.append(attr) + if changed: + print(f"[DINOv3] Disabled RoPE train-time coordinate jitter: {', '.join(changed)}.") + + def _init_concept_modules(self, embed_dim: int, num_classes: int) -> None: + if not self.config.concept_matrix_path: + raise ValueError("use_concept_head is True but concept_matrix_path is not provided.") + + matrix_path = Path(self.config.concept_matrix_path) + if not matrix_path.is_file(): + raise FileNotFoundError(f"Concept matrix file not found: {matrix_path}") + + concept_array = np.load(str(matrix_path), allow_pickle=False) + if concept_array.ndim != 2: + raise ValueError( + f"Concept matrix must be 2D, got shape {concept_array.shape} from {matrix_path}." + ) + + concept_array = concept_array.astype(np.float32, copy=False) + concept_tensor = torch.from_numpy(concept_array) + concept_dim, concept_embed_dim = concept_tensor.shape + + import logging + logger = logging.getLogger(__name__) + logger.info( + f"Loaded concept matrix of shape {concept_tensor.shape} " + f"(concept_dim={concept_dim}, embed_dim={concept_embed_dim}) from {matrix_path}" + ) + + if concept_embed_dim != embed_dim: + raise ValueError( + "Concept matrix embedding dimension does not match backbone output: " + f"expected {embed_dim}, got {concept_embed_dim}." + ) + + concept_mapping = nn.Linear( + embed_dim, + concept_dim, + bias=bool(self.config.concept_mapping_bias), + ) + with torch.no_grad(): + concept_mapping.weight.copy_(concept_tensor) + if concept_mapping.bias is not None: + concept_mapping.bias.zero_() + + if not self.config.concept_mapping_trainable: + concept_mapping.weight.requires_grad = False + if concept_mapping.bias is not None: + concept_mapping.bias.requires_grad = False + + concept_hidden_dim = self.config.concept_head_hidden_dim or concept_dim + concept_dropout = ( + self.config.concept_head_dropout + if self.config.concept_head_dropout is not None + else self.config.head_dropout + ) + + head_layers: List[nn.Module] = [] + if concept_hidden_dim != concept_dim: + head_layers.extend([ + nn.LayerNorm(concept_dim), + nn.Linear(concept_dim, concept_hidden_dim), + nn.GELU(), + nn.Dropout(concept_dropout), + nn.Linear(concept_hidden_dim, num_classes), + ]) + else: + head_layers.extend([ + nn.LayerNorm(concept_dim), + nn.Dropout(concept_dropout), + nn.Linear(concept_dim, num_classes), + ]) + + self.concept_mapping = concept_mapping + self.concept_head = nn.Sequential(*head_layers) + + def _apply_lora_adapters(self) -> None: + try: + from peft import LoraConfig, TaskType, get_peft_model + except ImportError as exc: + try: + from importlib.metadata import version as pkg_version + + peft_ver = pkg_version("peft") + except Exception: + peft_ver = "not-installed" + try: + from importlib.metadata import version as pkg_version + + transformers_ver = pkg_version("transformers") + except Exception: + transformers_ver = "not-installed" + raise ImportError( + "LoRA dependency import failed. This is usually a peft/transformers version mismatch. " + f"Current versions: peft={peft_ver}, transformers={transformers_ver}. " + "Reinstall the compatible ranges from requirements.txt: " + "`python3 -m pip install -U \"transformers>=4.56,<5\" \"peft>=0.17,<0.19\"`." + ) from exc + + target_modules = self.config.lora_target_modules + if not target_modules: + target_modules = self._collect_linear_module_names() + if not target_modules: + raise RuntimeError("Could not find any linear modules in DINOv3 backbone for LoRA.") + + lora_config = LoraConfig( + r=self.config.lora_rank, + lora_alpha=self.config.lora_alpha, + lora_dropout=self.config.lora_dropout, + bias=self.config.lora_bias, + target_modules=target_modules, + task_type=TaskType.FEATURE_EXTRACTION, + ) + + self.backbone = get_peft_model(self.backbone, lora_config) + self.lora_target_modules = target_modules + + def _collect_linear_module_names(self) -> List[str]: + names: List[str] = [] + last_n = self.config.lora_target_last_n + total_blocks = getattr(self.backbone, "n_blocks", None) + min_block_index = None + if last_n and total_blocks: + min_block_index = max(0, total_blocks - last_n) + + for name, module in self.backbone.named_modules(): + if isinstance(module, nn.Linear) and name: + if min_block_index is not None: + if "blocks." in name: + match = re.search(r"blocks\.(\d+)", name) + if match and int(match.group(1)) < min_block_index: + continue + else: + # Skip non-block modules when restricting to last N blocks + continue + names.append(name) + # Deduplicate while preserving order + seen = set() + ordered: List[str] = [] + for name in names: + if name not in seen: + ordered.append(name) + seen.add(name) + return ordered + + def _configure_trainable_params(self): + lora_trainable = self.train_lora if self.using_lora else False + if self.freeze_backbone: + for name, param in self.backbone.named_parameters(): + if self.using_lora and "lora_" in name: + param.requires_grad = lora_trainable + else: + param.requires_grad = False + if self.trainable_blocks > 0 and hasattr(self.backbone, "blocks"): + for block in self.backbone.blocks[-self.trainable_blocks:]: + for name, param in block.named_parameters(): + if self.using_lora and "lora_" in name: + param.requires_grad = lora_trainable + elif not self.using_lora: + param.requires_grad = True + if hasattr(self.backbone, "norm"): + for name, param in self.backbone.norm.named_parameters(): + if self.using_lora and "lora_" in name: + param.requires_grad = lora_trainable + elif not self.using_lora: + param.requires_grad = True + else: + for name, param in self.backbone.named_parameters(): + if self.using_lora and "lora_" in name and not lora_trainable: + param.requires_grad = False + else: + param.requires_grad = True + + def forward(self, x: torch.Tensor) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + # Use __call__/forward path first so FSDP hooks are triggered. + # Calling forward_features() directly can bypass composable-FSDP hooks. + features_dict = None + try: + # Use inference-style forward path for stability in supervised fine-tuning. + features_dict = self.backbone(x, is_training=False) + except TypeError: + # Fallback for backbones that do not expose is_training. + features_dict = self.backbone.forward_features(x) + if not isinstance(features_dict, dict) or "x_norm_clstoken" not in features_dict: + # Final fallback in case wrapper returns unexpected type. + features_dict = self.backbone.forward_features(x) + features = features_dict["x_norm_clstoken"] + logits = self.head(features) + if self.concept_mapping is None or self.concept_head is None: + return logits + + concept_features_raw = self.concept_mapping(features) + concept_features = concept_features_raw + if self.config.concept_sparsity_ratio > 0.0: + concept_features = _sparse_shrink(concept_features, self.config.concept_sparsity_ratio) + concept_logits = self.concept_head(concept_features) + return { + "logits": logits, + "concept_logits": concept_logits, + "concept_features": concept_features, + "concept_features_raw": concept_features_raw, + } + + def compute_concept_logits_with_ratio( + self, + concept_features_raw: torch.Tensor, + sparsity_ratio: float, + *, + return_mask: bool = False, + ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: + if self.concept_head is None: + raise RuntimeError("Concept head not initialized.") + concept_features = concept_features_raw + if return_mask: + concept_features, mask = _sparse_shrink(concept_features, sparsity_ratio, return_mask=True) + else: + concept_features = _sparse_shrink(concept_features, sparsity_ratio) + mask = None + logits = self.concept_head(concept_features) + if return_mask: + return logits, mask + return logits + + def train(self, mode: bool = True): + super().train(mode) + if self.freeze_backbone: + if self.using_lora: + self.backbone.train(mode) + base_model = getattr(self.backbone, "base_model", None) + if base_model is not None: + base_model.eval() + else: + self.backbone.eval() + return self + + def get_trainable_parameters(self) -> Iterable[nn.Parameter]: + return (p for p in self.parameters() if p.requires_grad) + + def get_lora_state_dict(self) -> Optional[Dict[str, torch.Tensor]]: + if not self.using_lora: + return None + from peft import get_peft_model_state_dict + + return get_peft_model_state_dict(self.backbone) + + def load_lora_state_dict(self, state_dict: Dict[str, torch.Tensor]) -> None: + if not self.using_lora: + raise RuntimeError("Attempting to load LoRA state dict while LoRA is disabled.") + from peft import get_peft_model_state_dict, set_peft_model_state_dict + + set_peft_model_state_dict(self.backbone, state_dict, adapter_name="default") + + # PEFT loads adapter weights non-strictly because the frozen backbone is + # intentionally absent. Re-export the adapter to make mismatches fatal. + loaded_state = get_peft_model_state_dict(self.backbone, adapter_name="default") + expected_keys = set(state_dict) + loaded_keys = set(loaded_state) + missing = sorted(expected_keys - loaded_keys) + unexpected = sorted(loaded_keys - expected_keys) + if missing or unexpected: + raise RuntimeError( + "LoRA checkpoint key mismatch after loading: " + f"missing={missing[:5]}, unexpected={unexpected[:5]}" + ) + + mismatched = [] + for name in sorted(expected_keys): + expected = state_dict[name].detach() + actual = loaded_state[name].detach() + if expected.shape != actual.shape or not torch.equal(expected.cpu(), actual.cpu()): + mismatched.append(name) + if mismatched: + raise RuntimeError( + "LoRA checkpoint tensor mismatch after loading: " + f"{mismatched[:5]} (total={len(mismatched)})" + ) + print(f"[Checkpoint] Strictly verified {len(expected_keys)} LoRA tensors.") + + def supports_resolution(self, size: int) -> bool: + if self.patch_size is None: + return True + return size % self.patch_size == 0 diff --git a/detectors/ForensicConcept/upstream/networks/trainer.py b/detectors/ForensicConcept/upstream/networks/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..2af3969a4064ad49229d451e610dafd7a4bc98ef --- /dev/null +++ b/detectors/ForensicConcept/upstream/networks/trainer.py @@ -0,0 +1,513 @@ +import contextlib +import torch +import torch.nn as nn +import torch.nn.functional as F +from networks.base_model import BaseModel +from networks.dinov3_detector import Dinov3Config, Dinov3Detector +from models import get_model + + +CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073] +CLIP_STD = [0.26862954, 0.26130258, 0.27577711] +IMAGENET_MEAN = [0.485, 0.456, 0.406] +IMAGENET_STD = [0.229, 0.224, 0.225] + + +class Trainer(BaseModel): + def name(self): + return 'Trainer' + + def __init__(self, opt): + super(Trainer, self).__init__(opt) + self.num_classes = getattr(opt, "num_classes", 1) + self._deepspeed_engine = None + self.augmix_js_loss = None + self._best_loss = float("inf") + self._loss_plateau_counter = 0 + self.full_finetune_enable = bool(getattr(opt, "full_finetune_enable", False)) + self.model = self._build_model(opt) + + if opt.trainmode == "lora" and opt.modelname.startswith("CLIP:"): + if self.isTrain and not opt.continue_train: + torch.nn.init.normal_(self.model.fc.weight.data, 0.0, opt.init_gain) + self._configure_clip_trainable(opt) + + if self.isTrain: + pos_weight = getattr(opt, "pos_weight", None) + if self.num_classes == 1: + if pos_weight is not None: + pos_tensor = torch.tensor(float(pos_weight), device=self.device) + self.loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_tensor) + else: + self.loss_fn = nn.BCEWithLogitsLoss() + elif self.num_classes == 2: + self.loss_fn = nn.CrossEntropyLoss() + # initialize optimizers + self.optimizer = self._build_optimizer() + self._init_full_finetune_plugin() + self.optimizer.zero_grad(set_to_none=True) + + self._init_augmix_js_branch() + + if not self.isTrain or opt.continue_train: + self.load_networks(opt.epoch) + self.model.to(self.device) + + def _build_model(self, opt): + if opt.trainmode == "dinov3": + model = Dinov3Detector(self._build_dinov3_config(opt), num_classes=self.num_classes) + self.model = model + self._ensure_valid_resolution(opt) + return model + if opt.trainmode == "lora" and str(getattr(opt, "modelname", "")).startswith("CLIP:"): + return get_model(opt.modelname, opt) + raise ValueError( + f"Unsupported trainmode={opt.trainmode!r}. " + "This release supports 'dinov3' and CLIP 'lora' only." + ) + + def _configure_clip_trainable(self, opt): + train_lora = bool(getattr(opt, "clip_train_lora", True)) + train_heads = bool(getattr(opt, "clip_train_fc", True)) + for name, param in self.model.named_parameters(): + is_visual_qkv_lora = ( + train_lora and "lora_" in name and "visual" in name and "qkv" in name + ) + is_head = train_heads and ( + name.startswith("fc.") or name.startswith("codebook_head.") + ) + param.requires_grad = is_visual_qkv_lora or is_head + + def _build_dinov3_config(self, opt): + freeze_backbone = bool(getattr(opt, "freeze_backbone", True)) + trainable_blocks = int(getattr(opt, "trainable_blocks", 0) or 0) + use_lora = bool(getattr(opt, "use_lora", False)) + gradient_checkpointing = bool(getattr(opt, "full_finetune_gradient_checkpointing", False)) + + if self.full_finetune_enable: + if freeze_backbone or use_lora or trainable_blocks != 0: + print( + "[FullFinetune] Enforcing DINOv3 full fine-tune: " + "freeze_backbone=false, use_lora=false, trainable_blocks=0." + ) + freeze_backbone = False + use_lora = False + trainable_blocks = 0 + else: + gradient_checkpointing = False + + return Dinov3Config( + variant=getattr(opt, "dinov3_variant", "vitl16"), + backend=getattr(opt, "dinov3_backend", "official"), + repo_path=getattr(opt, "dinov3_repo_path", None), + weights_path=getattr(opt, "dinov3_weights", None), + freeze_backbone=freeze_backbone, + trainable_blocks=trainable_blocks, + max_blocks=getattr(opt, "dinov3_max_blocks", None), + head_hidden_dim=getattr(opt, "head_hidden_dim", None), + head_dropout=getattr(opt, "head_dropout", 0.1), + use_lora=use_lora, + lora_rank=getattr(opt, "lora_rank", 4), + lora_alpha=getattr(opt, "lora_alpha", 8), + lora_dropout=getattr(opt, "lora_dropout", 0.0), + lora_bias=getattr(opt, "lora_bias", "none"), + lora_target_modules=getattr(opt, "lora_target_modules", None), + lora_target_last_n=getattr(opt, "lora_target_last_n", None), + use_concept_head=getattr(opt, "dinov3_use_concept_head", False), + concept_matrix_path=getattr(opt, "dinov3_concept_matrix_path", None), + concept_mapping_trainable=getattr(opt, "dinov3_concept_mapping_trainable", False), + concept_mapping_bias=getattr(opt, "dinov3_concept_mapping_bias", False), + concept_head_hidden_dim=getattr(opt, "dinov3_concept_head_hidden_dim", None), + concept_head_dropout=getattr(opt, "dinov3_concept_head_dropout", None), + concept_sparsity_ratio=getattr(opt, "dinov3_concept_sparsity_ratio", 0.0), + concept_loss_weight=getattr(opt, "dinov3_concept_loss_weight", 1.0), + concept_eval_sparsity=getattr(opt, "dinov3_concept_eval_sparsity", None), + disable_rope_train_jitter=getattr(opt, "dinov3_disable_rope_train_jitter", False), + gradient_checkpointing=gradient_checkpointing, + ) + + def _ensure_valid_resolution(self, opt): + if not hasattr(self.model, "supports_resolution"): + return + patch_size = getattr(self.model, "patch_size", 1) + window_size = getattr(self.model, "window_size", None) + if isinstance(window_size, (list, tuple)): + window_size = window_size[0] if window_size else None + if isinstance(window_size, int) and window_size > 0: + step = patch_size * window_size + else: + step = patch_size + for attr in ("loadSize", "cropSize"): + size = getattr(opt, attr, None) + if size is None: + continue + if not self.model.supports_resolution(size): + adjusted = max(step, (size // step) * step) + if adjusted != size: + print( + f"[Resolution] Adjusting {attr} from {size} to {adjusted} to align with step {step}." + ) + setattr(opt, attr, adjusted) + if getattr(opt, "loadSize", None) and getattr(opt, "cropSize", None): + if opt.cropSize > opt.loadSize: + print(f"[Resolution] Adjusting cropSize from {opt.cropSize} to match loadSize {opt.loadSize}.") + opt.cropSize = opt.loadSize + + def _init_full_finetune_plugin(self): + precision = str(getattr(self.opt, "full_finetune_precision", "fp32") or "fp32").lower() + if precision not in {"fp32", "fp16", "bf16"}: + precision = "fp32" + self.full_finetune_precision = precision + grad_accum_raw = getattr(self.opt, "full_finetune_grad_accum_steps", 1) + try: + self.grad_accum_steps = max(1, int(grad_accum_raw)) + except (TypeError, ValueError): + self.grad_accum_steps = 1 + self.max_grad_norm = float(getattr(self.opt, "max_grad_norm", 0.0) or 0.0) + self._grad_accum_counter = 0 + + self.use_amp = ( + self.full_finetune_enable + and precision in {"fp16", "bf16"} + and self.device.type == "cuda" + ) + if self.use_amp: + self.amp_dtype = torch.float16 if precision == "fp16" else torch.bfloat16 + self.scaler = torch.cuda.amp.GradScaler(enabled=(self.amp_dtype == torch.float16)) + else: + self.amp_dtype = torch.float32 + self.scaler = None + + if self.is_main_process and self.full_finetune_enable: + print( + f"[FullFinetune] enabled precision={self.full_finetune_precision} " + f"grad_accum_steps={self.grad_accum_steps} max_grad_norm={self.max_grad_norm}" + ) + + def _build_optimizer(self): + if self.opt.optim == 'adam': + return torch.optim.Adam( + filter(lambda p: p.requires_grad, self.model.parameters()), + lr=self.opt.lr, + betas=(self.opt.beta1, 0.999), + weight_decay=float(getattr(self.opt, "weight_decay", 0.0) or 0.0), + ) + if self.opt.optim == 'adamw': + return torch.optim.AdamW( + filter(lambda p: p.requires_grad, self.model.parameters()), + lr=self.opt.lr, + betas=(self.opt.beta1, 0.999), + weight_decay=float(getattr(self.opt, "weight_decay", 0.0) or 0.0), + ) + if self.opt.optim == 'sgd': + return torch.optim.SGD( + filter(lambda p: p.requires_grad, self.model.parameters()), + lr=self.opt.lr, + momentum=0.0, + weight_decay=float(getattr(self.opt, "weight_decay", 0.0) or 0.0), + ) + raise ValueError("optim should be [adam, adamw, sgd]") + + def reset_optimizer_for_wrapped_model(self): + """Rebuild optimizer after external wrappers (e.g., official FSDP plugin) change model params.""" + if not self.isTrain: + return + self.optimizer = self._build_optimizer() + self.optimizer.zero_grad(set_to_none=True) + if self.is_main_process: + print("[Optimizer] Rebuilt optimizer for wrapped model.") + + def _autocast_context(self): + if not self.use_amp: + return contextlib.nullcontext() + return torch.autocast(device_type="cuda", dtype=self.amp_dtype) + + def _optimizer_step_impl(self): + if self.max_grad_norm > 0.0: + if self.scaler is not None and self.scaler.is_enabled(): + self.scaler.unscale_(self.optimizer) + trainable_params = [ + p for p in self.model.parameters() + if p.requires_grad and p.grad is not None + ] + if trainable_params: + torch.nn.utils.clip_grad_norm_(trainable_params, self.max_grad_norm) + + if self.scaler is not None and self.scaler.is_enabled(): + self.scaler.step(self.optimizer) + self.scaler.update() + else: + self.optimizer.step() + self.optimizer.zero_grad(set_to_none=True) + + def adjust_learning_rate(self): + decay_factor = getattr(self.opt, "lr_decay_factor", 0.9) + min_lr = getattr(self.opt, "lr_min", 1e-6) + if decay_factor <= 0 or decay_factor >= 1: + print(f"[LR] Invalid decay factor {decay_factor}, falling back to 0.9") + decay_factor = 0.9 + + reached_min = False + prev_lr = None + for param_group in self.optimizer.param_groups: + prev_lr = param_group['lr'] + new_lr = prev_lr * decay_factor + if new_lr <= min_lr: + new_lr = min_lr + reached_min = True + param_group['lr'] = new_lr + + if prev_lr is None: + return False + + self.lr = self.optimizer.param_groups[0]['lr'] + print('*' * 25) + print(f'Changing lr from {prev_lr} to {self.lr}') + if reached_min: + print(f'[LR] Minimum lr {min_lr} reached; further decay will be skipped') + print('*' * 25) + return not reached_min + + def should_adjust_lr_on_plateau(self, loss_value: float) -> bool: + patience_raw = getattr(self.opt, "lr_plateau_patience", 0) + try: + patience = int(patience_raw) + except (TypeError, ValueError): + patience = 0 + if patience <= 0: + return False + + warmup_raw = getattr(self.opt, "lr_plateau_warmup", 0) + delta_raw = getattr(self.opt, "lr_plateau_delta", 0.0) + try: + warmup = int(warmup_raw) + except (TypeError, ValueError): + warmup = 0 + try: + delta = float(delta_raw) + except (TypeError, ValueError): + delta = 0.0 + if self.total_steps < warmup: + return False + + if loss_value + delta < self._best_loss: + self._best_loss = loss_value + self._loss_plateau_counter = 0 + return False + + self._loss_plateau_counter += 1 + if self._loss_plateau_counter >= patience: + self._loss_plateau_counter = 0 + self._best_loss = loss_value + return True + return False + + def set_input(self, input): + self.input = input[0].to(self.device) + self.label = input[1].to(self.device) + if self.num_classes == 1: + self.label = self.label.float() + + + def forward(self): + self.output = self.model(self.input) + + + def get_loss(self): + def _compute_loss(logits: torch.Tensor) -> torch.Tensor: + if self.num_classes == 1 and logits.dim() > 1: + logits = logits.squeeze(1) + return self.loss_fn(logits, self.label) + + output = self.output + if isinstance(output, dict): + main_logits = output.get("logits") + concept_logits = output.get("concept_logits") + cb_logits = output.get("cb_only") + main_loss = _compute_loss(main_logits) if main_logits is not None else None + concept_loss = _compute_loss(concept_logits) if concept_logits is not None else None + cb_loss = _compute_loss(cb_logits) if cb_logits is not None else None + if main_loss is None and concept_loss is None and cb_loss is None: + raise RuntimeError("Model output dict has no logits to compute loss.") + total_loss = main_loss + if concept_loss is not None: + weight = getattr(self.opt, "dinov3_concept_loss_weight", 1.0) + total_loss = weight * concept_loss if total_loss is None else total_loss + weight * concept_loss + if cb_loss is not None: + cb_weight = float(getattr(self.opt, "clip_cb_loss_weight", 1.0)) + total_loss = cb_weight * cb_loss if total_loss is None else total_loss + cb_weight * cb_loss + + return total_loss + if isinstance(output, tuple): + return _compute_loss(output[0]) + return _compute_loss(output) + + def _init_augmix_js_branch(self): + self.augmix_js_enable = bool(getattr(self.opt, "augmix_js_enable", False)) and bool(self.isTrain) + self.augmix_js_weight = float(getattr(self.opt, "augmix_js_weight", 12.0) or 12.0) + self.augmix_width = int(getattr(self.opt, "augmix_width", 3) or 3) + self.augmix_depth = int(getattr(self.opt, "augmix_depth", -1) or -1) + self.augmix_alpha = float(getattr(self.opt, "augmix_alpha", 1.0) or 1.0) + self.augmix_num_views = int(getattr(self.opt, "augmix_num_views", 2) or 2) + self.augmix_eps = float(getattr(self.opt, "augmix_js_eps", 1e-7) or 1e-7) + self.augmix_max_distortions = int(getattr(self.opt, "aug_utils_max_distortions", 3) or 3) + self.augmix_num_levels = int(getattr(self.opt, "aug_utils_num_levels", 5) or 5) + self._augmix_distort_images = None + + trainmode = str(getattr(self.opt, "trainmode", "")).lower() + modelname = str(getattr(self.opt, "modelname", "")) + if trainmode == "lora" and modelname.startswith("CLIP:"): + mean, std = CLIP_MEAN, CLIP_STD + else: + mean, std = IMAGENET_MEAN, IMAGENET_STD + self._augmix_mean = torch.tensor(mean, dtype=torch.float32, device=self.device).view(1, 3, 1, 1) + self._augmix_std = torch.tensor(std, dtype=torch.float32, device=self.device).view(1, 3, 1, 1) + + if not self.augmix_js_enable: + return + try: + from aug_utils_train.utils_data import distort_images as aug_utils_distort_images + + self._augmix_distort_images = aug_utils_distort_images + print( + f"[AugMix-JS] Enabled (w={self.augmix_js_weight}, views={self.augmix_num_views}, " + f"width={self.augmix_width}, depth={self.augmix_depth}, alpha={self.augmix_alpha})" + ) + except Exception as exc: + self.augmix_js_enable = False + self._augmix_distort_images = None + print(f"[AugMix-JS] Disabled because aug_utils_train import failed: {exc}") + + def _extract_primary_logits(self, output): + if isinstance(output, dict): + for key in ("logits", "main", "token_logits", "concept_logits", "cb_only", "cls_only"): + logits = output.get(key) + if logits is not None: + return logits + raise RuntimeError("Cannot find usable logits in model output dict for AugMix-JS.") + if isinstance(output, tuple): + return output[0] + return output + + def _logits_to_probs(self, logits: torch.Tensor) -> torch.Tensor: + if logits.dim() == 1: + logits = logits.unsqueeze(1) + if self.num_classes == 1 or logits.shape[1] == 1: + p_fake = torch.sigmoid(logits).view(-1, 1) + p_real = 1.0 - p_fake + probs = torch.cat([p_real, p_fake], dim=1) + else: + probs = F.softmax(logits, dim=1) + return probs.clamp_min(self.augmix_eps) + + def _js_divergence_from_probs(self, probs_list): + if not probs_list: + return None + p_mixture = torch.stack(probs_list, dim=0).mean(dim=0).clamp_min(self.augmix_eps) + p_mixture_log = torch.log(p_mixture) + js = 0.0 + for p in probs_list: + js = js + torch.sum(p_mixture * (p_mixture_log - torch.log(p.clamp_min(self.augmix_eps))), dim=1).mean() + js = js / float(len(probs_list)) + return js + + def _denormalize_to_unit(self, x: torch.Tensor) -> torch.Tensor: + return (x * self._augmix_std + self._augmix_mean).clamp(0.0, 1.0) + + def _normalize_from_unit(self, x01: torch.Tensor) -> torch.Tensor: + return (x01 - self._augmix_mean) / self._augmix_std + + def _augmix_single_image(self, img01_cpu: torch.Tensor) -> torch.Tensor: + # img01_cpu: [3,H,W] in [0,1], CPU tensor. + alpha = max(self.augmix_alpha, 1e-6) + ws = torch.distributions.Dirichlet(torch.tensor([alpha] * self.augmix_width)).sample().tolist() + m = torch.distributions.Beta(alpha, alpha).sample().item() + mix = torch.zeros_like(img01_cpu) + for i in range(self.augmix_width): + image_aug = img01_cpu.clone() + depth = self.augmix_depth if self.augmix_depth > 0 else int(torch.randint(1, 4, (1,)).item()) + for _ in range(depth): + image_aug, _, _ = self._augmix_distort_images( + image_aug, + max_distortions=self.augmix_max_distortions, + num_levels=self.augmix_num_levels, + ) + image_aug = image_aug.to(torch.float32).clamp(0.0, 1.0) + mix = mix + float(ws[i]) * image_aug + mixed = (1.0 - float(m)) * img01_cpu + float(m) * mix + return mixed.clamp(0.0, 1.0) + + def _build_augmix_views(self, clean_input: torch.Tensor): + # Build on CPU for aug_utils compatibility, then move back to model device. + clean01 = self._denormalize_to_unit(clean_input.detach()).cpu() + views = [] + for _ in range(self.augmix_num_views): + aug_batch = torch.empty_like(clean01) + for idx in range(clean01.shape[0]): + aug_batch[idx] = self._augmix_single_image(clean01[idx]) + aug_batch = aug_batch.to(self.device, non_blocking=True) + aug_batch = self._normalize_from_unit(aug_batch) + views.append(aug_batch) + return views + + def _compute_augmix_js_loss(self, clean_output): + if not self.augmix_js_enable or self._augmix_distort_images is None: + return None + clean_logits = self._extract_primary_logits(clean_output) + clean_probs = self._logits_to_probs(clean_logits) + aug_inputs = self._build_augmix_views(self.input) + aug_probs = [] + for aug_input in aug_inputs: + aug_output = self.model(aug_input) + aug_logits = self._extract_primary_logits(aug_output) + aug_probs.append(self._logits_to_probs(aug_logits)) + js_loss = self._js_divergence_from_probs([clean_probs] + aug_probs) + return js_loss + + def optimize_parameters(self): + if self._deepspeed_engine is not None: + self.forward() + base_loss = self.get_loss() + js_loss = self._compute_augmix_js_loss(self.output) + if js_loss is not None: + self.augmix_js_loss = js_loss.detach() + self.loss = base_loss + self.augmix_js_weight * js_loss + else: + self.augmix_js_loss = None + self.loss = base_loss + self._deepspeed_engine.backward(self.loss) + self._deepspeed_engine.step() + return + + with self._autocast_context(): + self.forward() + base_loss = self.get_loss() + js_loss = self._compute_augmix_js_loss(self.output) + if js_loss is not None: + self.augmix_js_loss = js_loss.detach() + self.loss = base_loss + self.augmix_js_weight * js_loss + else: + self.augmix_js_loss = None + self.loss = base_loss + + loss_for_backward = self.loss / float(self.grad_accum_steps) + if self.scaler is not None and self.scaler.is_enabled(): + self.scaler.scale(loss_for_backward).backward() + else: + loss_for_backward.backward() + + self._grad_accum_counter += 1 + if self._grad_accum_counter % self.grad_accum_steps == 0: + self._optimizer_step_impl() + + def finalize_epoch(self): + if self._deepspeed_engine is not None: + return + if not self.isTrain or self.grad_accum_steps <= 1: + return + if self._grad_accum_counter % self.grad_accum_steps == 0: + return + if self.is_main_process: + remain = self._grad_accum_counter % self.grad_accum_steps + print(f"[FullFinetune] finalize_epoch flush remaining accumulated steps: {remain}") + self._optimizer_step_impl() diff --git a/detectors/ForensicConcept/upstream/options/__init__.py b/detectors/ForensicConcept/upstream/options/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/detectors/ForensicConcept/upstream/options/base_options.py b/detectors/ForensicConcept/upstream/options/base_options.py new file mode 100644 index 0000000000000000000000000000000000000000..6eec509b36c6447b9dbd8f78fa257144e299f6c9 --- /dev/null +++ b/detectors/ForensicConcept/upstream/options/base_options.py @@ -0,0 +1,118 @@ +import argparse +import os +import time +import util +import torch +#import models +#import data + + +class BaseOptions(): + def __init__(self): + self.initialized = False + + def initialize(self, parser): + parser.add_argument('--mode', default='binary') + parser.add_argument('--arch', type=str, default='res50', help='architecture for binary classification') + + # data augmentation + parser.add_argument('--rz_interp', default='bilinear') + parser.add_argument('--blur_prob', type=float, default=0) + parser.add_argument('--blur_sig', default='0.5') + parser.add_argument('--jpg_prob', type=float, default=0) + parser.add_argument('--jpg_method', default='cv2') + parser.add_argument('--jpg_qual', default='75') + + parser.add_argument('--dataroot', default='./dataset/', help='path to images (should have subfolders trainA, trainB, valA, valB, etc)') + parser.add_argument('--classes', default='', help='image classes to train on') + parser.add_argument('--class_bal', action='store_true') + parser.add_argument('--batch_size', type=int, default=64, help='input batch size') + parser.add_argument('--loadSize', type=int, default=224, help='scale images to this size') + parser.add_argument('--cropSize', type=int, default=224, help='then crop to this size') + parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU') + parser.add_argument('--name', type=str, default='experiment_name', help='name of the experiment. It decides where to store samples and models') + parser.add_argument('--epoch', type=str, default='latest', help='which epoch to load? set to latest to use latest cached model') + parser.add_argument('--num_threads', default=8, type=int, help='# threads for loading data') + parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here') + parser.add_argument('--serial_batches', action='store_true', help='if true, takes images in order to make batches, otherwise takes them randomly') + parser.add_argument('--resize_or_crop', type=str, default='scale_and_crop', help='scaling and cropping of images at load time [resize_and_crop|crop|scale_width|scale_width_and_crop|none]') + parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data augmentation') + parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal|xavier|kaiming|orthogonal]') + parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.') + parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{netG}_size{loadSize}') + parser.add_argument('--delr_freq', type=int, default=20, help='frequency of changing lr') + + + self.initialized = True + return parser + + def gather_options(self): + # initialize parser with basic options + if not self.initialized: + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser = self.initialize(parser) + + # get the basic options + opt, _ = parser.parse_known_args() + self.parser = parser + + return opt #parser.parse_args() + + def print_options(self, opt): + message = '' + message += '----------------- Options ---------------\n' + for k, v in sorted(vars(opt).items()): + comment = '' + default = self.parser.get_default(k) + if v != default: + comment = '\t[default: %s]' % str(default) + message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment) + message += '----------------- End -------------------' + print(message) + + # save to the disk + + expr_dir = os.path.join(opt.checkpoints_dir, opt.name) + util.mkdirs(expr_dir) + file_name = os.path.join(expr_dir, 'opt.txt') + with open(file_name, 'wt') as opt_file: + opt_file.write(message) + opt_file.write('\n') + + def parse(self, print_options=True): + + opt = self.gather_options() + opt.isTrain = self.isTrain # train or test + opt.name = opt.name + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) + # process opt.suffix + if opt.suffix: + suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else '' + opt.name = opt.name + suffix + + if print_options: + self.print_options(opt) + + # set gpu ids + str_ids = opt.gpu_ids.split(',') + opt.gpu_ids = [] + for str_id in str_ids: + id = int(str_id) + if id >= 0: + opt.gpu_ids.append(id) + if len(opt.gpu_ids) > 0: + torch.cuda.set_device(opt.gpu_ids[0]) + + # additional + opt.classes = opt.classes.split(',') + opt.rz_interp = opt.rz_interp.split(',') + opt.blur_sig = [float(s) for s in opt.blur_sig.split(',')] + opt.jpg_method = opt.jpg_method.split(',') + opt.jpg_qual = [int(s) for s in opt.jpg_qual.split(',')] + if len(opt.jpg_qual) == 2: + opt.jpg_qual = list(range(opt.jpg_qual[0], opt.jpg_qual[1] + 1)) + elif len(opt.jpg_qual) > 2: + raise ValueError("Shouldn't have more than 2 values for --jpg_qual.") + + self.opt = opt + return self.opt diff --git a/detectors/ForensicConcept/upstream/options/test_options.py b/detectors/ForensicConcept/upstream/options/test_options.py new file mode 100644 index 0000000000000000000000000000000000000000..1dba350e3cadf758c2dc39e99a55b4e844e7b16d --- /dev/null +++ b/detectors/ForensicConcept/upstream/options/test_options.py @@ -0,0 +1,17 @@ +from .base_options import BaseOptions + + +class TestOptions(BaseOptions): + def initialize(self, parser): + parser = BaseOptions.initialize(self, parser) + # parser.add_argument('--dataroot') + parser.add_argument('--model_path') + parser.add_argument('--no_resize', action='store_true') + parser.add_argument('--no_crop', action='store_true') + parser.add_argument('--eval', action='store_true', help='use eval mode during test time.') + parser.add_argument('--earlystop_epoch', type=int, default=15) + parser.add_argument('--lr', type=float, default=0.00002, help='initial learning rate for adam') + parser.add_argument('--niter', type=int, default=0, help='# of iter at starting learning rate') + + self.isTrain = False + return parser diff --git a/detectors/ForensicConcept/upstream/options/train_options.py b/detectors/ForensicConcept/upstream/options/train_options.py new file mode 100644 index 0000000000000000000000000000000000000000..5682d5d49692f1c3c583d3dfd29f6023ff9d369e --- /dev/null +++ b/detectors/ForensicConcept/upstream/options/train_options.py @@ -0,0 +1,26 @@ +from .base_options import BaseOptions + + +class TrainOptions(BaseOptions): + def initialize(self, parser): + parser = BaseOptions.initialize(self, parser) + parser.add_argument('--earlystop_epoch', type=int, default=15) + parser.add_argument('--data_aug', action='store_true', help='if specified, perform additional data augmentation (photometric, blurring, jpegging)') + parser.add_argument('--optim', type=str, default='adam', help='optim to use [sgd, adam]') + parser.add_argument('--new_optim', action='store_true', help='new optimizer instead of loading the optim state') + parser.add_argument('--loss_freq', type=int, default=400, help='frequency of showing loss on tensorboard') + parser.add_argument('--save_latest_freq', type=int, default=2000, help='frequency of saving the latest results') + parser.add_argument('--save_epoch_freq', type=int, default=20, help='frequency of saving checkpoints at the end of epochs') + parser.add_argument('--continue_train', action='store_true', help='continue training: load the latest model') + parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by , +, ...') + parser.add_argument('--last_epoch', type=int, default=-1, help='starting epoch count for scheduler intialization') + parser.add_argument('--train_split', type=str, default='train', help='train, val, test, etc') + parser.add_argument('--val_split', type=str, default='val', help='train, val, test, etc') + parser.add_argument('--niter', type=int, default=1000, help='# of iter at starting learning rate') + parser.add_argument('--beta1', type=float, default=0.9, help='momentum term of adam') + parser.add_argument('--lr', type=float, default=0.0001, help='initial learning rate for adam') + # parser.add_argument('--model_path') + parser.add_argument('--no_resize', action='store_true') + # parser.add_argument('--no_crop', action='store_true') + self.isTrain = True + return parser diff --git a/detectors/ForensicConcept/upstream/plugins/__init__.py b/detectors/ForensicConcept/upstream/plugins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8570fb370258a4f1020f8a6d71af04a77ad8bb94 --- /dev/null +++ b/detectors/ForensicConcept/upstream/plugins/__init__.py @@ -0,0 +1,4 @@ +"""Optional acceleration plugins. + +Default training path is unchanged unless an explicit plugin backend is selected. +""" diff --git a/detectors/ForensicConcept/upstream/plugins/dinov3_official_accel.py b/detectors/ForensicConcept/upstream/plugins/dinov3_official_accel.py new file mode 100644 index 0000000000000000000000000000000000000000..615e9bd3323b3b07d3940d7f3d45c0917eca477a --- /dev/null +++ b/detectors/ForensicConcept/upstream/plugins/dinov3_official_accel.py @@ -0,0 +1,375 @@ +from __future__ import annotations + +import json +import sys +import types +import importlib +import contextlib +from pathlib import Path +from types import SimpleNamespace +from typing import Optional + +import torch +import torch.nn as nn + + +def _as_bool(v, default: bool = False) -> bool: + if v is None: + return default + if isinstance(v, bool): + return v + if isinstance(v, (int, float)): + return bool(v) + s = str(v).strip().lower() + if s in {"1", "true", "yes", "y", "on"}: + return True + if s in {"0", "false", "no", "n", "off"}: + return False + return default + + +def _resolve_official_repo_from_opt(opt) -> Optional[Path]: + if getattr(opt, "dinov3_repo_path", None): + p = Path(opt.dinov3_repo_path).expanduser().resolve() + if (p / "dinov3").is_dir(): + return p + return None + + +def _ensure_official_import(opt) -> Path: + repo_path = _resolve_official_repo_from_opt(opt) + if repo_path is not None: + repo_str = str(repo_path) + if repo_str in sys.path: + sys.path.remove(repo_str) + sys.path.insert(0, repo_str) + return repo_path + + try: + import dinov3 as dinov3_pkg + + return Path(dinov3_pkg.__file__).resolve().parents[1] + except Exception as exc: # noqa: BLE001 + raise RuntimeError( + "Official DINOv3 repository not found. Clone " + "https://github.com/facebookresearch/dinov3 and set " + "training.dinov3_repo_path, or install DINOv3 in the active environment." + ) from exc + + +def _effective_precision(opt) -> str: + # Reuse existing full-finetune precision key if provided. + p = str(getattr(opt, "full_finetune_precision", "fp32") or "fp32").strip().lower() + if p not in {"fp16", "bf16", "fp32"}: + p = "fp32" + return p + + +def _install_fsdp_compat_shim_for_official(*, is_main_process: bool) -> None: + """ + Compatibility shim for older PyTorch builds where official DINOv3 import + fails due to missing torch.distributed.fsdp.register_fsdp_forward_method. + """ + try: + import torch.distributed.fsdp as torch_fsdp + except Exception: # noqa: BLE001 + return + + if hasattr(torch_fsdp, "register_fsdp_forward_method"): + return + + def _noop_register_fsdp_forward_method(module, method_name): # noqa: ANN001 + return module + + setattr(torch_fsdp, "register_fsdp_forward_method", _noop_register_fsdp_forward_method) + if is_main_process: + print( + "[AccelPlugin] torch.distributed.fsdp.register_fsdp_forward_method is missing; " + "installed no-op compatibility shim." + ) + + # torch<2.6 may expose FSDPState under _composable path only. + legacy_parent = "torch.distributed.fsdp._fully_shard" + legacy_state_mod = f"{legacy_parent}._fsdp_state" + if legacy_state_mod not in sys.modules: + try: + src_state_mod = importlib.import_module("torch.distributed._composable.fsdp._fsdp_state") + if legacy_parent not in sys.modules: + parent_mod = types.ModuleType(legacy_parent) + parent_mod.__path__ = [] # type: ignore[attr-defined] + sys.modules[legacy_parent] = parent_mod + sys.modules[legacy_state_mod] = src_state_mod + if is_main_process: + print( + "[AccelPlugin] installed compatibility alias " + "torch.distributed.fsdp._fully_shard._fsdp_state -> " + "torch.distributed._composable.fsdp._fsdp_state" + ) + except Exception: # noqa: BLE001 + pass + + +def _patch_official_fsdp_transformer_for_torch25(is_main_process: bool) -> None: + """ + Torch 2.5.x may fail when fully_shard() is also applied at the backbone root + (patch_embed conv sees mixed Tensor/DTensor). Keep official block-level FSDP + wrapping but skip root-level fully_shard for transformer backbones. + """ + if not str(torch.__version__).startswith("2.5"): + return + try: + import dinov3.fsdp.ac_compile_parallelize as acp_mod + except Exception: # noqa: BLE001 + return + + fully_shard = getattr(acp_mod, "fully_shard", None) + nn_mod = getattr(acp_mod, "nn", None) + if fully_shard is None or nn_mod is None: + return + + def _fsdp_transformer_torch25(fsdp_config, model): # noqa: ANN001 + blocks = model.blocks + assert isinstance(blocks, nn_mod.ModuleList) + for block_id, block in enumerate(blocks): + blocks[block_id] = fully_shard(block, **fsdp_config, reshard_after_forward=True) + # On torch 2.5.x, block prefetch hooks can trigger + # `'FSDPCommContext' has no attribute 'all_gather_copy_in_stream'`. + # Keep sharding, but disable forward/backward prefetch wiring. + # Intentionally skip `fully_shard(model, ...)` on torch 2.5.x. + + acp_mod.fsdp_transformer = _fsdp_transformer_torch25 + if is_main_process: + print( + "[AccelPlugin] Applied torch2.5 compatibility patch: " + "official fsdp_transformer now shards blocks only (no root fully_shard)." + ) + + +@contextlib.contextmanager +def _patch_to_empty_to_preserve_loaded_weights(*, enabled: bool, is_main_process: bool): + """ + Official ac_compile_parallelize() calls model.to_empty(device="cuda") at the end. + In this project we call it after loading checkpoints, so to_empty would drop weights. + """ + if not enabled: + yield + return + + original_to_empty = nn.Module.to_empty + + def _to_empty_keep_weights(self, *args, **kwargs): + device = kwargs.get("device") + if device is None and len(args) > 0: + device = args[0] + if device is None: + return self + return self.to(device) + + nn.Module.to_empty = _to_empty_keep_weights + if is_main_process: + print( + "[AccelPlugin] Patched nn.Module.to_empty during official_fsdp apply " + "to preserve already-loaded checkpoint weights." + ) + try: + yield + finally: + nn.Module.to_empty = original_to_empty + + +def _apply_official_fsdp(trainer_model, opt, *, is_main_process: bool) -> None: + if not torch.distributed.is_initialized(): + raise RuntimeError("official_fsdp requires distributed process group. Launch with torchrun.") + if str(getattr(opt, "trainmode", "")).lower() != "dinov3": + raise RuntimeError("official_fsdp plugin currently supports only training.trainmode=dinov3.") + + repo_path = _ensure_official_import(opt) + _install_fsdp_compat_shim_for_official(is_main_process=is_main_process) + _patch_official_fsdp_transformer_for_torch25(is_main_process=is_main_process) + try: + from dinov3.fsdp.ac_compile_parallelize import ac_compile_parallelize + except Exception as exc: # noqa: BLE001 + raise RuntimeError( + "Failed to import official DINOv3 FSDP2 wrapper. " + "This typically means your PyTorch version is too old for official FSDP2 APIs " + "(e.g., missing torch.distributed.fsdp.register_fsdp_forward_method). " + "Use a newer PyTorch build compatible with the official DINOv3 code." + ) from exc + + model = trainer_model.model + if not hasattr(model, "backbone") or not hasattr(model, "head"): + raise RuntimeError("Dinov3Detector backbone/head not found; cannot apply official FSDP plugin.") + + precision = _effective_precision(opt) + cfg = SimpleNamespace( + train=SimpleNamespace( + checkpointing=_as_bool(getattr(opt, "dinov3_accel_checkpointing", True), True), + checkpointing_full=_as_bool(getattr(opt, "dinov3_accel_checkpointing_full", False), False), + compile=_as_bool(getattr(opt, "dinov3_accel_compile", False), False), + cudagraphs=_as_bool(getattr(opt, "dinov3_accel_cudagraphs", False), False), + ), + compute_precision=SimpleNamespace( + param_dtype=str(getattr(opt, "dinov3_accel_param_dtype", precision) or precision).lower(), + reduce_dtype=str(getattr(opt, "dinov3_accel_reduce_dtype", precision) or precision).lower(), + sharding_strategy="SHARD_GRAD_OP", + ), + ) + + for attr in ("param_dtype", "reduce_dtype"): + val = getattr(cfg.compute_precision, attr) + if val not in {"fp16", "bf16", "fp32"}: + setattr(cfg.compute_precision, attr, precision) + + trained_model = nn.ModuleDict( + { + "backbone": model.backbone, + "head": model.head, + } + ) + if getattr(model, "concept_mapping", None) is not None: + trained_model["concept_mapping"] = model.concept_mapping + if getattr(model, "concept_head", None) is not None: + trained_model["concept_head"] = model.concept_head + + if is_main_process: + print( + "[AccelPlugin] Applying official FSDP2 from DINOv3 " + f"(repo={repo_path}, param_dtype={cfg.compute_precision.param_dtype}, " + f"reduce_dtype={cfg.compute_precision.reduce_dtype}, " + f"checkpointing={cfg.train.checkpointing}, compile={cfg.train.compile})." + ) + + preserve_loaded_weights = _as_bool( + getattr(opt, "dinov3_accel_preserve_loaded_weights", True), + True, + ) + with _patch_to_empty_to_preserve_loaded_weights( + enabled=preserve_loaded_weights, + is_main_process=is_main_process, + ): + ac_compile_parallelize(trained_model=trained_model, inference_only_models=[], cfg=cfg) + + # Put wrapped modules back into detector. + model.backbone = trained_model["backbone"] + model.head = trained_model["head"] + if "concept_mapping" in trained_model: + model.concept_mapping = trained_model["concept_mapping"] + if "concept_head" in trained_model: + model.concept_head = trained_model["concept_head"] + + trainer_model.reset_optimizer_for_wrapped_model() + if str(torch.__version__).startswith("2.5") and float(getattr(trainer_model, "max_grad_norm", 0.0) or 0.0) > 0.0: + # torch2.5 composable FSDP gradients may mix Tensor/DTensor objects, + # and clip_grad_norm_ can fail on mixed groups. + trainer_model.max_grad_norm = 0.0 + if is_main_process: + print("[AccelPlugin] Disabled max_grad_norm clipping for official_fsdp compatibility.") + if is_main_process: + print("[AccelPlugin] official_fsdp applied and optimizer rebuilt.") + + +def _build_deepspeed_config(opt) -> dict: + cfg_path = getattr(opt, "deepspeed_config_path", None) + if cfg_path: + with open(cfg_path, "r", encoding="utf-8") as f: + return json.load(f) + + stage = int(getattr(opt, "deepspeed_zero_stage", 2) or 2) + stage = max(0, min(3, stage)) + grad_accum = int(getattr(opt, "deepspeed_grad_accum_steps", getattr(opt, "full_finetune_grad_accum_steps", 1)) or 1) + grad_accum = max(1, grad_accum) + precision = _effective_precision(opt) + grad_clip = float(getattr(opt, "max_grad_norm", 0.0) or 0.0) + + ds_cfg = { + "train_micro_batch_size_per_gpu": int(getattr(opt, "batch_size", 1) or 1), + "gradient_accumulation_steps": grad_accum, + "steps_per_print": 2000, + "wall_clock_breakdown": False, + "zero_optimization": { + "stage": stage, + "contiguous_gradients": True, + "overlap_comm": True, + "reduce_scatter": True, + "allgather_partitions": True, + "allgather_bucket_size": int(2e8), + "reduce_bucket_size": int(2e8), + }, + } + if grad_clip > 0.0: + ds_cfg["gradient_clipping"] = grad_clip + if precision == "bf16": + ds_cfg["bf16"] = {"enabled": True} + ds_cfg["fp16"] = {"enabled": False} + elif precision == "fp16": + ds_cfg["fp16"] = {"enabled": True} + ds_cfg["bf16"] = {"enabled": False} + else: + ds_cfg["fp16"] = {"enabled": False} + ds_cfg["bf16"] = {"enabled": False} + + offload_opt = str(getattr(opt, "deepspeed_offload_optimizer_device", "none") or "none").lower() + offload_param = str(getattr(opt, "deepspeed_offload_param_device", "none") or "none").lower() + if offload_opt in {"cpu", "nvme"}: + ds_cfg["zero_optimization"]["offload_optimizer"] = {"device": offload_opt} + if offload_param in {"cpu", "nvme"}: + ds_cfg["zero_optimization"]["offload_param"] = {"device": offload_param} + + return ds_cfg + + +def _apply_deepspeed(trainer_model, opt, *, is_main_process: bool) -> None: + if str(getattr(opt, "trainmode", "")).lower() != "dinov3": + raise RuntimeError("deepspeed plugin currently supports only training.trainmode=dinov3.") + _ensure_official_import(opt) + + try: + import deepspeed + except Exception as exc: # noqa: BLE001 + raise RuntimeError( + "DeepSpeed is not available. Install it first (matching your CUDA/PyTorch build)." + ) from exc + + ds_cfg = _build_deepspeed_config(opt) + model = trainer_model.model + params = [p for p in model.parameters() if p.requires_grad] + if not params: + raise RuntimeError("No trainable parameters found for DeepSpeed initialization.") + + if is_main_process: + stage = ds_cfg.get("zero_optimization", {}).get("stage", 0) + print(f"[AccelPlugin] Initializing DeepSpeed (ZeRO stage={stage}).") + + engine, optimizer, _, _ = deepspeed.initialize( + model=model, + model_parameters=params, + optimizer=trainer_model.optimizer, + config=ds_cfg, + ) + + trainer_model.model = engine + trainer_model.optimizer = optimizer + trainer_model._deepspeed_engine = engine + trainer_model.use_amp = False + trainer_model.scaler = None + if is_main_process: + print("[AccelPlugin] deepspeed initialized.") + + +def apply_dinov3_acceleration_plugin(trainer_model, opt, *, is_main_process: bool) -> str: + """Apply optional acceleration plugin. Default path is no-op.""" + backend = str(getattr(opt, "dinov3_accel_backend", "none") or "none").strip().lower() + if backend in {"", "none", "off", "disabled"}: + return "none" + + if backend == "official_fsdp": + _apply_official_fsdp(trainer_model, opt, is_main_process=is_main_process) + return backend + if backend == "deepspeed": + _apply_deepspeed(trainer_model, opt, is_main_process=is_main_process) + return backend + + raise ValueError( + f"Unsupported training.dinov3_accel_backend={backend}. " + "Expected one of: none, official_fsdp, deepspeed." + ) diff --git a/detectors/ForensicConcept/upstream/test_with_config.py b/detectors/ForensicConcept/upstream/test_with_config.py new file mode 100644 index 0000000000000000000000000000000000000000..03ba3e1535fbe4f35d345c35d34b7b2a4feb56e8 --- /dev/null +++ b/detectors/ForensicConcept/upstream/test_with_config.py @@ -0,0 +1,146 @@ +"""Run evaluation on a trained checkpoint using the same configuration pipeline as training.""" +from pathlib import Path +from typing import Optional, Tuple + +import torch + +from config_loader import create_argument_parser, load_config_from_args +from train_with_config import UnifiedTrainer + + +def _load_checkpoint_from_path(trainer: UnifiedTrainer, checkpoint: Path) -> str: + """Load a checkpoint file directly by temporarily redirecting the save directory. + + Args: + trainer: UnifiedTrainer instance with an initialized model. + checkpoint: Path to the checkpoint file to load. + + Returns: + The epoch tag inferred from the checkpoint name. + """ + if not checkpoint.exists(): + raise FileNotFoundError(f"Checkpoint not found: {checkpoint}") + + epoch_tag = checkpoint.stem.replace("model_epoch_", "") + base_model = trainer.model + original_save_dir = base_model.save_dir + original_load_dir = base_model.load_dir + try: + base_model.save_dir = str(checkpoint.parent) + base_model.load_dir = str(checkpoint.parent) + # Allow direct file loading even if directory names have been renamed. + base_model.load_networks(str(checkpoint)) + finally: + base_model.save_dir = original_save_dir + base_model.load_dir = original_load_dir + return epoch_tag + + +def _resolve_checkpoint_argument(checkpoint: Optional[str]) -> Optional[Path]: + """Normalize checkpoint argument to a concrete file path. + + Supports passing a directory (picks the newest model_epoch_*.pth inside). + """ + if not checkpoint: + return None + checkpoint_path = Path(checkpoint).expanduser() + if checkpoint_path.is_file(): + return checkpoint_path + if checkpoint_path.is_dir(): + candidates = sorted(checkpoint_path.glob("model_epoch_*.pth")) + if not candidates: + raise FileNotFoundError(f"No model_epoch_*.pth found under {checkpoint_path}") + latest = max(candidates, key=lambda p: p.stat().st_mtime) + print(f"[Checkpoint] No file specified, using latest in directory: {latest.name}") + return latest + raise FileNotFoundError(f"Checkpoint path does not exist: {checkpoint_path}") + + +def _resolve_config_path(args, default_config: str) -> Path: + """Pick the config file to load, preferring the one next to the checkpoint.""" + requested_path = Path(args.config).expanduser() if args.config else Path(default_config) + checkpoint_hint = getattr(args, "checkpoint_path", None) + + if checkpoint_hint and args.config == default_config: + ckpt = Path(checkpoint_hint).expanduser() + ckpt_dir = ckpt.parent if ckpt.is_file() else ckpt + candidate_cfg = ckpt_dir / "config.yaml" + if candidate_cfg.exists(): + print(f"[Config] Auto-using config next to checkpoint: {candidate_cfg}") + return candidate_cfg + + if requested_path.exists(): + return requested_path + + if checkpoint_hint: + ckpt = Path(checkpoint_hint).expanduser() + ckpt_dir = ckpt.parent if ckpt.is_file() else ckpt + fallback_cfg = ckpt_dir / "config.yaml" + if fallback_cfg.exists(): + print(f"[Config] Requested config {requested_path} missing; falling back to {fallback_cfg}") + return fallback_cfg + + raise FileNotFoundError(f"Configuration file not found: {requested_path}") + + +def _prepare_trainer(args) -> Tuple[UnifiedTrainer, Optional[str]]: + """Create a UnifiedTrainer and ensure the desired checkpoint is loaded.""" + config_loader = load_config_from_args(args) + + checkpoint_path = _resolve_checkpoint_argument(getattr(args, "checkpoint_path", None)) + config_checkpoint = config_loader.get('testing.model_path', None) + + epoch_tag = getattr(args, "epoch", None) + + if not checkpoint_path and not epoch_tag and config_checkpoint: + checkpoint_path = _resolve_checkpoint_argument(config_checkpoint) + + if checkpoint_path: + # Directly load the specified checkpoint during initialization. + config_loader.set('training.continue_train', True) + config_loader.set('training.epoch', str(checkpoint_path)) + trainer = UnifiedTrainer(config_loader, is_train=False) + epoch_tag = checkpoint_path.stem.replace("model_epoch_", "") + else: + if not epoch_tag: + epoch_tag = config_loader.get('training.epoch', 'latest') + # Ensure the trainer restores the requested checkpoint during initialization. + config_loader.set('training.continue_train', True) + config_loader.set('training.epoch', epoch_tag) + trainer = UnifiedTrainer(config_loader, is_train=False) + + return trainer, epoch_tag + + +def main(): + parser = create_argument_parser() + parser.add_argument( + '--epoch', + type=str, + help='Checkpoint tag to load (matches the suffix in model_epoch_.pth).' + ) + parser.add_argument( + '--checkpoint_path', + type=str, + help='Optional explicit path to a checkpoint file; overrides --epoch.' + ) + default_config = parser.get_default('config') + args = parser.parse_args() + args.config = str(_resolve_config_path(args, default_config)) + trainer, epoch_tag = _prepare_trainer(args) + trainer.model.eval() + + with torch.no_grad(): + mean_acc, mean_auc, mean_ap = trainer.test_model() + + if epoch_tag: + print(f"Evaluated checkpoint: {epoch_tag}") + print( + f"Mean Accuracy: {mean_acc*100:.2f}% | " + f"Mean AUC: {mean_auc*100:.2f}% | " + f"Mean AP: {mean_ap*100:.2f}%" + ) + + +if __name__ == '__main__': + main() diff --git a/detectors/ForensicConcept/upstream/train_with_config.py b/detectors/ForensicConcept/upstream/train_with_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f099f70c90aeb4cd64233163ef65d9fbadfd5445 --- /dev/null +++ b/detectors/ForensicConcept/upstream/train_with_config.py @@ -0,0 +1,1201 @@ +"""Configuration-driven training entry point for AIGC detection.""" +import os +import time +import re +import contextlib +from datetime import timedelta +import torch +import torch.nn +import torch.distributed as dist +import copy +try: + from tensorboardX import SummaryWriter +except ImportError: + try: + from torch.utils.tensorboard import SummaryWriter + except ImportError: + SummaryWriter = None +import numpy as np +from typing import Dict, List +from validate import validate +from data import create_dataloader +import data as data_module +from torch.utils.data import DataLoader +from torch.utils.data.distributed import DistributedSampler +from networks.trainer import Trainer +from options.train_options import TrainOptions +from util import Logger +from config_loader import ConfigLoader, create_argument_parser, load_config_from_args +from plugins.dinov3_official_accel import apply_dinov3_acceleration_plugin +import random + + +def seed_torch(seed=1029): + """Set random seed for reproducibility.""" + random.seed(seed) + os.environ['PYTHONHASHSEED'] = str(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.benchmark = False + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.enabled = False + + +class UnifiedTrainer: + """ + Unified trainer that handles the complete training pipeline including: + - Visual pretraining + - Model conversion to HuggingFace format + - Vision model replacement in LLaVA + """ + + def __init__(self, config_loader: ConfigLoader, *, is_train: bool = True): + """ + Initialize the unified trainer. + + Args: + config_loader: ConfigLoader instance containing all configuration + """ + self.config = config_loader + self.is_train = bool(is_train) + self._init_distributed() + self.setup_environment() + self.setup_data_and_model() + + def _init_distributed(self): + self.rank = int(os.environ.get("RANK", "0")) + self.world_size = int(os.environ.get("WORLD_SIZE", "1")) + self.local_rank = int(os.environ.get("LOCAL_RANK", "0")) + self.distributed = self.world_size > 1 + self.is_main_process = self.rank == 0 + if self.distributed: + if not torch.cuda.is_available(): + raise RuntimeError("Distributed training requires CUDA devices.") + torch.cuda.set_device(self.local_rank) + timeout_minutes_raw = self.config.get("system.ddp_timeout_minutes", 180) + try: + timeout_minutes = max(10, int(timeout_minutes_raw)) + except (TypeError, ValueError): + timeout_minutes = 180 + if not dist.is_initialized(): + dist.init_process_group( + backend="nccl", + init_method="env://", + timeout=timedelta(minutes=timeout_minutes), + ) + if self.is_main_process: + print(f"[DDP] Process group timeout set to {timeout_minutes} minutes.") + + def cleanup(self): + if self.distributed and dist.is_initialized(): + dist.destroy_process_group() + + def _barrier(self): + if self.distributed and dist.is_initialized(): + dist.barrier(device_ids=[self.local_rank]) + + def _build_train_dataloader(self): + return self._build_dataloader_for_opt(self.opt, distributed=self.distributed) + + def _build_dataloader_for_opt(self, opt_obj, *, distributed: bool, log_prefix: str = "[Data]"): + dataset = data_module.get_dataset(opt_obj) + shuffle = not opt_obj.serial_batches if (opt_obj.isTrain and not opt_obj.class_bal) else False + sampler = None + if distributed and opt_obj.class_bal: + sampler = data_module.get_bal_sampler( + dataset, + distributed=True, + num_replicas=self.world_size, + rank=self.rank, + seed=int(getattr(opt_obj, "seed", 0)), + ) + shuffle = False + if self.is_main_process: + print(f"{log_prefix} Using class-balanced weighted sampler in DDP mode.") + elif distributed: + sampler = DistributedSampler( + dataset, + num_replicas=self.world_size, + rank=self.rank, + shuffle=shuffle, + ) + shuffle = False + elif opt_obj.class_bal: + sampler = data_module.get_bal_sampler(dataset) + + return DataLoader( + dataset, + batch_size=opt_obj.batch_size, + shuffle=shuffle, + sampler=sampler, + num_workers=int(opt_obj.num_threads), + ) + + def _unwrap_model_for_eval(self): + model = self.model.model + if hasattr(model, "module"): + return model.module + return model + + def setup_environment(self): + """Setup training environment.""" + seed_torch(self.config.get('training.seed', 100) + self.rank) + + # Create necessary directories + self.config.create_directories() + self._barrier() + + # Setup logging + self.setup_logging() + + def setup_logging(self): + """Setup logging and tensorboard.""" + # Evaluationๆจกๅผไธ‹ไธๆ”นๅ†™่ฎญ็ปƒๆ—ฅๅฟ—/TensorBoard๏ผŒไฟๆŒ็›ฎๅฝ•ๅนฒๅ‡€ + if not self.is_train or not self.is_main_process: + self.train_writer = None + self.val_writer = None + return + + log_dir = os.path.join( + self.config.get('models.checkpoints_dir'), + self.config.get('training.name') + ) + os.makedirs(log_dir, exist_ok=True) + + # Setup file logger + Logger(os.path.join(log_dir, self.config.get('logging.log_file', 'training.log'))) + + # Setup tensorboard writers + if self.config.get('logging.tensorboard', True) and SummaryWriter is not None: + try: + self.train_writer = SummaryWriter(os.path.join(log_dir, "train")) + self.val_writer = SummaryWriter(os.path.join(log_dir, "val")) + except (PermissionError, OSError) as exc: + # tensorboardX fails in restricted environments; fall back to no-op writers + print(f"[Logging] TensorBoard disabled: {exc}") + self.train_writer = None + self.val_writer = None + else: + if self.config.get('logging.tensorboard', True) and SummaryWriter is None: + print("[Logging] TensorBoard disabled: no compatible writer is installed.") + self.train_writer = None + self.val_writer = None + + def setup_data_and_model(self): + """Setup data loaders and model.""" + # Convert config to namespace for compatibility + self.opt = self.config.to_namespace(is_train=self.is_train) + self.opt.distributed = self.distributed + self.opt.rank = self.rank + self.opt.world_size = self.world_size + self.opt.local_rank = self.local_rank if self.distributed else -1 + self.opt.ddp_find_unused_parameters = bool( + self.config.get("training.ddp_find_unused_parameters", False) + ) + if self.distributed: + # Trainer reads opt.gpu_ids[0] to select device; force per-process local rank. + self.opt.gpu_ids = str(self.local_rank) + # Update specific paths + if self.is_train: + train_root = self.config.get('data.train_dataroot') + train_split = self.config.get('data.train_split') + if train_split in (None, '', '.', './'): + self.opt.dataroot = train_root + elif os.path.isabs(train_split): + self.opt.dataroot = train_split + else: + self.opt.dataroot = os.path.join(train_root, train_split) + + extra_train_roots = self.config.get('data.extra_train_roots', []) or [] + if isinstance(extra_train_roots, str): + extra_train_roots = [p.strip() for p in extra_train_roots.split(',') if p.strip()] + self.opt.extra_train_roots = list(extra_train_roots) + if self.is_main_process and self.opt.extra_train_roots: + print(f"[Data] extra_train_roots: {self.opt.extra_train_roots}") + + self.test_dataroot = self.config.get('data.test_dataroot') + + # Create data loader + self.data_loader = self._build_train_dataloader() if self.is_train else None + + # Create model + self.model = Trainer(self.opt) + self.accel_backend = "none" + if self.is_train: + self.accel_backend = apply_dinov3_acceleration_plugin( + self.model, + self.opt, + is_main_process=self.is_main_process, + ) + + if self.distributed and self.accel_backend == "none": + self.model.model = torch.nn.parallel.DistributedDataParallel( + self.model.model, + device_ids=[self.local_rank], + output_device=self.local_rank, + find_unused_parameters=bool(getattr(self.opt, "ddp_find_unused_parameters", False)), + ) + elif self.distributed and self.accel_backend != "none" and self.is_main_process: + print(f"[AccelPlugin] DDP wrapper skipped (backend={self.accel_backend}).") + if self.is_train: + # Save an immutable snapshot of the effective config alongside checkpoints for traceability. + if self.is_main_process: + try: + cfg_out = os.path.join(self.model.save_dir, "config.yaml") + self.config.save_config(cfg_out) + except Exception as exc: + print(f"[Config] Failed to save config snapshot: {exc}") + self._barrier() + + # def create_test_options(self): + # """Reuse training options to produce a test configuration without reparsing CLI.""" + # test_opt = copy.deepcopy(self.opt) + # test_opt.isTrain = False + # test_opt.serial_batches = True + # test_opt.batch_size = self.config.get('testing.batch_size', 64) + # test_opt.no_resize = self.config.get('testing.no_resize', False) + # test_opt.no_crop = self.config.get('testing.no_crop', False) + # test_opt.noise_type = self.config.get('testing.noise_type') + # test_opt.noise_ratio = self.config.get('testing.noise_ratio') + # test_opt.legacy_preprocess = self.config.get('training.legacy_preprocess', False) + # test_opt.data_aug = self.config.get('testing.data_aug', False) + # test_opt.use_aug_utils_eval = self.config.get('testing.use_aug_utils_eval', False) + # test_opt.use_testshift_like_aug_eval = self.config.get('testing.use_testshift_like_aug_eval', False) + # test_opt.testshift_like_apply_prob = self.config.get( + # 'testing.testshift_like_apply_prob', + # self.config.get('training.testshift_like_apply_prob', 1.0), + # ) + # test_opt.testshift_like_max_groups = self.config.get( + # 'testing.testshift_like_max_groups', + # self.config.get('training.testshift_like_max_groups', 3), + # ) + # test_opt.max_eval_samples = self.config.get('testing.max_eval_samples', 0) + # test_opt.loadSize = self.config.get('training.loadSize', test_opt.loadSize) + # test_opt.cropSize = self.config.get('training.cropSize', test_opt.cropSize) + # test_opt.trainmode = self.config.get('training.trainmode', test_opt.trainmode) + # test_opt.modelname = self.config.get('training.modelname', getattr(test_opt, 'modelname', '')) + # # ไธบไบ†ๅฏน้ฝ NPR ็š„้ชŒ่ฏ้ข„ๅค„็†๏ผš้ป˜่ฎคๆ‰ง่กŒ resize -> crop -> flip -> ImageNet ๅฝ’ไธ€ๅŒ– + # # ๅฝ“ legacy_preprocess ๅผ€ๅฏๆ—ถๅผบๅˆถๅผ€ๅฏ resize๏ผˆNPR ๆต‹่ฏ•้˜ถๆฎตไธไฝฟ็”จ no_resize๏ผ‰ + # if test_opt.legacy_preprocess: + # test_opt.no_resize = False + # test_opt.classes = [] + # # Never leak training extra roots into evaluation datasets. + # test_opt.extra_train_roots = [] + # test_opt.distributed = False + # test_opt.rank = 0 + # test_opt.world_size = 1 + # test_opt.local_rank = -1 + # return test_opt + def create_test_options(self): + """Reuse training options to produce a test configuration without reparsing CLI.""" + test_opt = copy.deepcopy(self.opt) + robustness_cfg = self.config.get_testing_robustness() + + test_opt.isTrain = False + test_opt.serial_batches = True + test_opt.batch_size = self.config.get('testing.batch_size', 64) + test_opt.no_resize = self.config.get('testing.no_resize', False) + test_opt.no_crop = self.config.get('testing.no_crop', False) + test_opt.noise_type = self.config.get('testing.noise_type') + test_opt.noise_ratio = self.config.get('testing.noise_ratio') + test_opt.legacy_preprocess = self.config.get('training.legacy_preprocess', False) + test_opt.data_aug = self.config.get('testing.data_aug', False) + test_opt.use_aug_utils_eval = self.config.get('testing.use_aug_utils_eval', False) + test_opt.use_testshift_like_aug_eval = self.config.get('testing.use_testshift_like_aug_eval', False) + test_opt.testshift_like_apply_prob = self.config.get( + 'testing.testshift_like_apply_prob', + self.config.get('training.testshift_like_apply_prob', 1.0), + ) + test_opt.testshift_like_max_groups = self.config.get( + 'testing.testshift_like_max_groups', + self.config.get('training.testshift_like_max_groups', 3), + ) + + test_opt.robustness_preset = robustness_cfg['preset'] + test_opt.robustness_type = robustness_cfg['type'] + test_opt.robustness_chain = robustness_cfg['chain'] + test_opt.robustness_jpeg_quality = robustness_cfg['params']['jpeg_quality'] + test_opt.robustness_gaussian_blur_sigma = robustness_cfg['params']['gaussian_blur_sigma'] + test_opt.robustness_gaussian_noise_std = robustness_cfg['params']['gaussian_noise_std'] + test_opt.robustness_downsample_scale = robustness_cfg['params']['downsample_scale'] + test_opt.robustness_cj_brightness = robustness_cfg['params']['cj_brightness'] + test_opt.robustness_cj_contrast = robustness_cfg['params']['cj_contrast'] + test_opt.robustness_cj_saturation = robustness_cfg['params']['cj_saturation'] + test_opt.robustness_cj_hue = robustness_cfg['params']['cj_hue'] + + test_opt.max_eval_samples = self.config.get('testing.max_eval_samples', 0) + test_opt.loadSize = self.config.get('training.loadSize', test_opt.loadSize) + test_opt.cropSize = self.config.get('training.cropSize', test_opt.cropSize) + test_opt.trainmode = self.config.get('training.trainmode', test_opt.trainmode) + test_opt.modelname = self.config.get('training.modelname', getattr(test_opt, 'modelname', '')) + + # ไธบไบ†ๅฏน้ฝ NPR ็š„้ชŒ่ฏ้ข„ๅค„็†๏ผš้ป˜่ฎคๆ‰ง่กŒ resize -> crop -> flip -> ImageNet ๅฝ’ไธ€ๅŒ– + # ๅฝ“ legacy_preprocess ๅผ€ๅฏๆ—ถๅผบๅˆถๅผ€ๅฏ resize๏ผˆNPR ๆต‹่ฏ•้˜ถๆฎตไธไฝฟ็”จ no_resize๏ผ‰ + if test_opt.legacy_preprocess: + test_opt.no_resize = False + + test_opt.classes = [] + test_opt.extra_train_roots = [] + test_opt.distributed = False + test_opt.rank = 0 + test_opt.world_size = 1 + test_opt.local_rank = -1 + return test_opt + + def test_model(self): + """Test the model on all configured test datasets.""" + print('*' * 25) + print(time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())) + + eval_groups = self.config.get('testing.groups', []) + + def _pick_primary_head(metrics: Dict[str, dict]) -> str: + if "main" in metrics: + return "main" + if "token" in metrics: + return "token" + if "concept" in metrics: + return "concept" + return "" + + def _format_head_label(head_name: str) -> str: + if head_name == "cls_only": + return "cls_only" + if head_name == "cb_only": + return "cb_only" + if head_name == "main": + return "Main" + if head_name == "token": + return "Token" + return head_name.replace("concept", "Concept") + + if not eval_groups: + # Fallback to legacy behaviour when groups are not configured + test_opt = self.create_test_options() + test_vals = self.config.get('testing.test_vals', []) + multiclass = self.config.get('testing.multiclass', []) + accs, aucs, aps = [], [], [] + cb_accs, cb_aucs, cb_aps = [], [], [] + for v_id, val in enumerate(test_vals): + test_opt.dataroot = f'{self.test_dataroot}/{val}' + test_opt.dataset_name = val + if v_id < len(multiclass) and multiclass[v_id]: + test_opt.classes = os.listdir(test_opt.dataroot) + else: + test_opt.classes = [] + head_metrics, _ = validate(self._unwrap_model_for_eval(), test_opt) + primary_head = _pick_primary_head(head_metrics) + primary_metrics = head_metrics.get(primary_head, {}) if primary_head else {} + if primary_head: + accs.append(primary_metrics.get("acc", 0.0)) + aucs.append(primary_metrics.get("auc", 0.0)) + aps.append(primary_metrics.get("ap", 0.0)) + cb_metrics = head_metrics.get("cb_only") + if cb_metrics is not None: + cb_accs.append(cb_metrics.get("acc", 0.0)) + cb_aucs.append(cb_metrics.get("auc", 0.0)) + cb_aps.append(cb_metrics.get("ap", 0.0)) + for head_name, metrics in head_metrics.items(): + label = _format_head_label(head_name) + print( + f"({v_id} {val:>16}) [{label}] acc: {metrics.get('acc', 0.0)*100:.1f}; " + f"auc: {metrics.get('auc', 0.0)*100:.1f}; ap: {metrics.get('ap', 0.0)*100:.1f}, " + f"racc: {metrics.get('r_acc', 0.0)*100:.1f}, " + f"facc: {metrics.get('f_acc', 0.0)*100:.1f};" + ) + mean_acc = float(np.mean(accs)) if accs else 0.0 + mean_auc = float(np.mean(aucs)) if aucs else 0.0 + mean_ap = float(np.mean(aps)) if aps else 0.0 + if not accs: + raise RuntimeError( + "Evaluation produced no results. Check testing.test_vals and data.test_dataroot." + ) + print( + f"({len(test_vals)} {'Mean':>16}) " + f"acc: {mean_acc*100:.1f}; auc: {mean_auc*100:.1f}; ap: {mean_ap*100:.1f}" + ) + if cb_accs: + cb_mean_acc = float(np.mean(cb_accs)) + cb_mean_auc = float(np.mean(cb_aucs)) + cb_mean_ap = float(np.mean(cb_aps)) + print( + f"({len(test_vals)} {'cb_only Mean':>16}) " + f"acc: {cb_mean_acc*100:.1f}; auc: {cb_mean_auc*100:.1f}; ap: {cb_mean_ap*100:.1f}" + ) + print('*' * 25) + print(time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())) + return mean_acc, mean_auc, mean_ap + + overall_accs = [] + overall_aucs = [] + overall_aps = [] + overall_head_stats: Dict[str, Dict[str, List[float]]] = {} + overall_concept_stats: Dict[str, Dict[str, List[float]]] = {} + + for group_cfg in eval_groups: + group_name = group_cfg.get('name') or os.path.basename(group_cfg.get('path', 'unknown')) + base_path = group_cfg.get('path') + if not base_path or not os.path.exists(base_path): + print(f"[Eval] Skipping group '{group_name}' because path does not exist: {base_path}") + continue + + mode = group_cfg.get('mode', 'subdirs') + include = set(group_cfg.get('include', []) or []) + exclude = set(group_cfg.get('exclude', []) or []) + datasets_to_eval = [] + + if mode == 'single': + datasets_to_eval.append((group_name, base_path)) + else: + if mode == 'list': + candidate_subdirs = list(include) + else: # default to enumerating direct sub directories + candidate_subdirs = [d for d in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, d))] + if include: + candidate_subdirs = [d for d in candidate_subdirs if d in include] + if exclude: + candidate_subdirs = [d for d in candidate_subdirs if d not in exclude] + candidate_subdirs.sort() + for sub in candidate_subdirs: + datasets_to_eval.append((sub, os.path.join(base_path, sub))) + + test_opt = self.create_test_options() + override_keys = [ + "data_aug", + "no_resize", + "no_crop", + "noise_type", + "noise_ratio", + "use_aug_utils_train", + "use_aug_utils_eval", + "use_testshift_like_aug_eval", + "testshift_like_apply_prob", + "testshift_like_max_groups", + "aug_utils_prob", + "aug_utils_max_distortions", + "aug_utils_num_levels", + "max_eval_samples", + ] + for key in override_keys: + if key in group_cfg: + setattr(test_opt, key, group_cfg.get(key)) + group_results = [] + for dataset_name, dataset_path in datasets_to_eval: + if not os.path.exists(dataset_path): + print(f"[Eval] Skip '{dataset_name}' in group '{group_name}' (missing path: {dataset_path})") + continue + test_opt.dataroot = dataset_path + test_opt.dataset_name = dataset_name + test_opt.classes = [] # allow recursive discovery of 0/1 structure + + head_metrics, _ = validate(self._unwrap_model_for_eval(), test_opt) + primary_head = _pick_primary_head(head_metrics) + primary_metrics = head_metrics.get(primary_head, {}) if primary_head else {} + + main_acc = primary_metrics.get("acc", 0.0) + main_auc = primary_metrics.get("auc", 0.0) + main_ap = primary_metrics.get("ap", 0.0) + if primary_head: + overall_accs.append(main_acc) + overall_aucs.append(main_auc) + overall_aps.append(main_ap) + + result_entry = { + 'dataset': dataset_name, + 'acc': main_acc, + 'auc': main_auc, + 'ap': main_ap, + 'r_acc': primary_metrics.get('r_acc', 0.0), + 'f_acc': primary_metrics.get('f_acc', 0.0), + } + + for head_name, metrics in head_metrics.items(): + if head_name.startswith("concept"): + stats = overall_concept_stats.setdefault(head_name, {'accs': [], 'aucs': [], 'aps': []}) + stats['accs'].append(metrics.get('acc', 0.0)) + stats['aucs'].append(metrics.get('auc', 0.0)) + stats['aps'].append(metrics.get('ap', 0.0)) + result_entry.setdefault('concept_variants', {})[head_name] = metrics + if head_name == "cb_only": + stats = overall_head_stats.setdefault("cb_only", {'accs': [], 'aucs': [], 'aps': []}) + stats['accs'].append(metrics.get('acc', 0.0)) + stats['aucs'].append(metrics.get('auc', 0.0)) + stats['aps'].append(metrics.get('ap', 0.0)) + + label = _format_head_label(head_name) + print( + f"[Eval] {group_name:>12} | {dataset_name:>12} :: [{label}] acc {metrics.get('acc', 0.0)*100:.2f} " + f"auc {metrics.get('auc', 0.0)*100:.2f} ap {metrics.get('ap', 0.0)*100:.2f} " + f"racc {metrics.get('r_acc', 0.0)*100:.2f} " + f"facc {metrics.get('f_acc', 0.0)*100:.2f}" + ) + + group_results.append(result_entry) + + if group_results: + group_acc = float(np.mean([r['acc'] for r in group_results])) + group_auc = float(np.mean([r['auc'] for r in group_results])) + group_ap = float(np.mean([r['ap'] for r in group_results])) + summary_entry = { + 'results': group_results, + 'mean_acc': group_acc, + 'mean_auc': group_auc, + 'mean_ap': group_ap, + } + + concept_means = {} + for result in group_results: + concepts = result.get('concept_variants') or {} + for head_name, metrics in concepts.items(): + concept_means.setdefault(head_name, {'accs': [], 'aucs': [], 'aps': []}) + concept_means[head_name]['accs'].append(metrics.get('acc', 0.0)) + concept_means[head_name]['aucs'].append(metrics.get('auc', 0.0)) + concept_means[head_name]['aps'].append(metrics.get('ap', 0.0)) + + if concept_means: + summary_entry['concept_means'] = { + name: { + 'acc': float(np.mean(values['accs'])) if values['accs'] else 0.0, + 'auc': float(np.mean(values['aucs'])) if values['aucs'] else 0.0, + 'ap': float(np.mean(values['aps'])) if values['aps'] else 0.0, + } + for name, values in concept_means.items() + } + + print( + f"[Eval] {group_name:>12} | {'Mean':>12} :: " + f"acc {group_acc*100:.2f} auc {group_auc*100:.2f} ap {group_ap*100:.2f}" + ) + if concept_means: + for name, values in summary_entry['concept_means'].items(): + label = name.replace('concept', 'Concept') + print( + f"{'':>33}[{label} Mean] " + f"acc {values['acc']*100:.2f} auc {values['auc']*100:.2f} ap {values['ap']*100:.2f}" + ) + + if not overall_accs: + raise RuntimeError( + "Evaluation produced no results. Every testing group was empty, missing, " + "or failed to provide model outputs; check testing.groups paths." + ) + mean_acc = float(np.mean(overall_accs)) + mean_auc = float(np.mean(overall_aucs)) + mean_ap = float(np.mean(overall_aps)) + print( + f"[Eval] {'Overall':>12} | {'Mean':>12} :: " + f"acc {mean_acc*100:.2f} auc {mean_auc*100:.2f} ap {mean_ap*100:.2f}" + ) + cb_stats = overall_head_stats.get("cb_only") + if cb_stats and cb_stats.get('accs'): + cb_overall_acc = float(np.mean(cb_stats['accs'])) + cb_overall_auc = float(np.mean(cb_stats['aucs'])) + cb_overall_ap = float(np.mean(cb_stats['aps'])) + print( + f"{'':>33}[cb_only Overall] " + f"acc {cb_overall_acc*100:.2f} auc {cb_overall_auc*100:.2f} ap {cb_overall_ap*100:.2f}" + ) + if overall_concept_stats: + for head_name, values in overall_concept_stats.items(): + label = head_name.replace('concept', 'Concept') + concept_overall_acc = float(np.mean(values['accs'])) if values['accs'] else 0.0 + concept_overall_auc = float(np.mean(values['aucs'])) if values['aucs'] else 0.0 + concept_overall_ap = float(np.mean(values['aps'])) if values['aps'] else 0.0 + print( + f"{'':>33}[{label} Overall] acc {concept_overall_acc*100:.2f} " + f"auc {concept_overall_auc*100:.2f} " + f"ap {concept_overall_ap*100:.2f}" + ) + print('*' * 25) + print(time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())) + return mean_acc, mean_auc, mean_ap + + + def train(self): + """Execute the training loop.""" + if self.is_main_process: + print(f"Starting training with config: {self.config.config_path}") + if self.is_main_process and self.config.get('logging.print_options', True): + self.config.print_config() + + # Initial testing + initial_eval = self.config.get('training.initial_eval', False) + if initial_eval: + if self.is_main_process: + print("Initial model testing...") + self.model.train() + self.model.eval() + self._barrier() + if self.is_main_process: + self.test_model() + self._barrier() + else: + if self.is_main_process: + print("Initial model testing skipped (set training.initial_eval=true to enable).") + self.model.train() + + if self.is_main_process: + print(f"Current working directory: {os.getcwd()}") + + plateau_patience_raw = self.config.get('training.lr_plateau_patience', 0) + try: + plateau_patience = int(plateau_patience_raw) + except (TypeError, ValueError): + plateau_patience = 0 + plateau_enabled = plateau_patience > 0 + if self.distributed and plateau_enabled: + if self.is_main_process: + print("[LR] Disabling loss-plateau LR adjustment in DDP to keep optimizer states synchronized.") + plateau_enabled = False + lr_adjustment_available = True + delr_freq_raw = self.config.get('training.delr_freq', 20) + try: + delr_freq = max(1, int(delr_freq_raw)) + except (TypeError, ValueError): + delr_freq = 20 + total_epochs_raw = self.config.get('training.niter', 1000) + try: + total_epochs = max(1, int(total_epochs_raw)) + except (TypeError, ValueError): + total_epochs = 1000 + skip_eval_during_train = bool(self.config.get('training.skip_eval_during_train', False)) + skip_final_eval = bool(self.config.get('training.skip_final_eval', skip_eval_during_train)) + save_by_epoch = bool(self.config.get('training.save_by_epoch', skip_eval_during_train)) + save_before_eval = bool(self.config.get('training.save_before_eval', False)) + save_best_by_auc = bool(self.config.get('training.save_best_by_auc', False)) + keep_only_best_auc_checkpoints = bool(self.config.get('training.keep_only_best_auc_checkpoints', False)) + save_last_checkpoint = bool(self.config.get('training.save_last_checkpoint', True)) + best_auc_keep_topk_raw = self.config.get('training.keep_topk_best_auc', 5) + try: + best_auc_keep_topk = max(0, int(best_auc_keep_topk_raw)) + except (TypeError, ValueError): + best_auc_keep_topk = 5 + if keep_only_best_auc_checkpoints and save_best_by_auc: + save_by_epoch = False + save_before_eval = False + best_auc_delta = float(self.config.get('training.best_auc_delta', 0.0) or 0.0) + best_auc = float("-inf") + best_auc_epoch = -1 + if self.is_main_process and skip_eval_during_train: + print("[Eval] Per-epoch validation disabled (training.skip_eval_during_train=true).") + if save_by_epoch: + print("[Checkpoint] Saving checkpoints by epoch index.") + if self.is_main_process and save_best_by_auc: + print(f"[Checkpoint] Best-AUC selection enabled (delta={best_auc_delta}).") + if best_auc_keep_topk > 0: + print(f"[Checkpoint] Keep top-{best_auc_keep_topk} best-AUC checkpoints.") + if self.is_main_process and save_before_eval and not skip_eval_during_train: + print("[Checkpoint] save_before_eval enabled: save checkpoint before each validation.") + if self.is_main_process and keep_only_best_auc_checkpoints and save_best_by_auc: + print("[Checkpoint] keep_only_best_auc_checkpoints enabled: disable epoch/pre-eval checkpoint saves.") + batch_size_raw = self.config.get('training.batch_size', 16) + try: + train_batch_size = max(1, int(batch_size_raw)) + except (TypeError, ValueError): + train_batch_size = 16 + loss_freq_raw = self.config.get('training.loss_freq', 400) + try: + loss_print_freq = max(1, int(loss_freq_raw)) + except (TypeError, ValueError): + loss_print_freq = 400 + + eval_every_steps_raw = self.config.get('training.eval_every_steps', 0) + try: + eval_every_steps = max(0, int(eval_every_steps_raw)) + except (TypeError, ValueError): + eval_every_steps = 0 + eval_by_epoch = bool(self.config.get('training.eval_by_epoch', True)) + if skip_eval_during_train: + eval_every_steps = 0 + eval_by_epoch = False + if self.is_main_process and eval_every_steps > 0: + print(f"[Eval] Step-based validation enabled every {eval_every_steps} steps.") + if self.is_main_process and not eval_by_epoch and not skip_eval_during_train: + print("[Eval] Epoch-end validation disabled (training.eval_by_epoch=false).") + + val_ft_cfg_raw = self.config.get('training.val_finetune_after_eval', {}) + if isinstance(val_ft_cfg_raw, bool): + val_ft_cfg = {"enable": bool(val_ft_cfg_raw)} + elif isinstance(val_ft_cfg_raw, dict): + val_ft_cfg = dict(val_ft_cfg_raw) + else: + val_ft_cfg = {} + val_ft_enable = bool(val_ft_cfg.get("enable", False)) + val_ft_run_on_step_eval = bool(val_ft_cfg.get("run_on_step_eval", False)) + try: + val_ft_epochs_per_round = max(1, int(val_ft_cfg.get("epochs_per_round", 1))) + except (TypeError, ValueError): + val_ft_epochs_per_round = 1 + try: + val_ft_max_steps = max(0, int(val_ft_cfg.get("max_steps", 0))) + except (TypeError, ValueError): + val_ft_max_steps = 0 + try: + val_ft_batch_size = max(1, int(val_ft_cfg.get("batch_size", train_batch_size))) + except (TypeError, ValueError): + val_ft_batch_size = train_batch_size + val_ft_class_bal = bool(val_ft_cfg.get("class_bal", False)) + val_ft_use_train_aug = bool(val_ft_cfg.get("use_train_augmentations", False)) + + def _normalize_roots_local(value): + if value is None: + return [] + if isinstance(value, str): + return [p.strip() for p in value.split(',') if p.strip()] + if isinstance(value, (list, tuple)): + return [str(p).strip() for p in value if str(p).strip()] + return [str(value).strip()] + + val_ft_roots = _normalize_roots_local(val_ft_cfg.get("roots")) + if not val_ft_roots and bool(val_ft_cfg.get("use_testing_groups", True)): + for group_cfg in self.config.get('testing.groups', []) or []: + if not isinstance(group_cfg, dict): + continue + path = str(group_cfg.get("path", "")).strip() + if path: + val_ft_roots.append(path) + if not val_ft_roots and self.test_dataroot: + val_ft_roots.append(str(self.test_dataroot)) + val_ft_roots = _normalize_roots_local(val_ft_roots) + val_ft_roots = [p for p in val_ft_roots if os.path.exists(p)] + if val_ft_enable and not val_ft_roots: + if self.is_main_process: + print("[ValFT] Disabled: no valid roots were found.") + val_ft_enable = False + if val_ft_enable and self.is_main_process: + print( + f"[ValFT] enabled roots={val_ft_roots} bs={val_ft_batch_size} " + f"epochs_per_round={val_ft_epochs_per_round} max_steps={val_ft_max_steps or 'all'} " + f"class_bal={val_ft_class_bal} use_train_aug={val_ft_use_train_aug} " + f"run_on_step_eval={val_ft_run_on_step_eval}" + ) + + curriculum_phases = self.config.get('training.curriculum_phases', []) or [] + if not isinstance(curriculum_phases, list): + curriculum_phases = [] + current_phase_idx = -1 + last_eval_step = -1 + best_auc_marker = "" + + def _prune_best_auc_checkpoints(): + if not self.is_main_process: + return + if not save_best_by_auc: + return + if best_auc_keep_topk <= 0: + return + save_dir = getattr(self.model, "save_dir", None) + if not save_dir or not os.path.isdir(save_dir): + return + + pattern = re.compile(r"^model_epoch_best_auc_([0-9]*\.?[0-9]+)_(e|s)(\d+)\.pth$") + scored = [] + for filename in os.listdir(save_dir): + match = pattern.match(filename) + if not match: + continue + auc = float(match.group(1)) + marker = int(match.group(3)) + scored.append((auc, marker, filename)) + + if len(scored) <= best_auc_keep_topk: + return + + scored.sort(key=lambda x: (x[0], x[1], x[2]), reverse=True) + to_remove = scored[best_auc_keep_topk:] + removed = 0 + for _, _, filename in to_remove: + path = os.path.join(save_dir, filename) + try: + os.remove(path) + removed += 1 + except FileNotFoundError: + continue + if removed > 0: + print( + f"[Checkpoint] Pruned {removed} best-AUC checkpoints in {save_dir}, " + f"keeping top {best_auc_keep_topk}." + ) + + def _normalize_roots(value): + if value is None: + return [] + if isinstance(value, str): + return [p.strip() for p in value.split(',') if p.strip()] + if isinstance(value, (list, tuple)): + return [str(p).strip() for p in value if str(p).strip()] + return [str(value).strip()] + + def _active_phase_index(epoch_one_based): + if not curriculum_phases: + return -1 + for idx, phase in enumerate(curriculum_phases): + if not isinstance(phase, dict): + continue + start_raw = phase.get("start_epoch", 1) + end_raw = phase.get("end_epoch", total_epochs) + try: + start_epoch = max(1, int(start_raw)) + except (TypeError, ValueError): + start_epoch = 1 + try: + end_epoch = max(start_epoch, int(end_raw)) + except (TypeError, ValueError): + end_epoch = total_epochs + if start_epoch <= epoch_one_based <= end_epoch: + return idx + return -1 + + def _apply_curriculum_if_needed(epoch_one_based): + nonlocal current_phase_idx + nonlocal train_batch_size + target_idx = _active_phase_index(epoch_one_based) + if target_idx < 0 or target_idx == current_phase_idx: + return + + phase = curriculum_phases[target_idx] + phase_name = str(phase.get("name", f"phase_{target_idx}")) + + if "train_dataroot" in phase and phase.get("train_dataroot"): + self.opt.dataroot = str(phase.get("train_dataroot")) + if "extra_train_roots" in phase: + self.opt.extra_train_roots = _normalize_roots(phase.get("extra_train_roots")) + + override_keys = [ + "data_aug", + "use_testshift_like_aug", + "testshift_like_apply_prob", + "testshift_like_max_groups", + "use_aug_utils_train", + "aug_utils_prob", + "aug_utils_max_distortions", + "aug_utils_num_levels", + "no_resize", + "loadSize", + "cropSize", + ] + for key in override_keys: + if key in phase: + setattr(self.opt, key, phase.get(key)) + + if "batch_size" in phase: + try: + self.opt.batch_size = max(1, int(phase.get("batch_size"))) + train_batch_size = self.opt.batch_size + except (TypeError, ValueError): + pass + + self.data_loader = self._build_train_dataloader() + current_phase_idx = target_idx + if self.is_main_process: + print( + f"[Curriculum] Switched to '{phase_name}' at epoch {epoch_one_based}: " + f"dataroot={self.opt.dataroot}, extra_roots={getattr(self.opt, 'extra_train_roots', [])}, " + f"bs={self.opt.batch_size}, testshift_prob={getattr(self.opt, 'testshift_like_apply_prob', 1.0)}" + ) + + def _run_validation(eval_label, *, epoch_for_tag=None, step_for_tag=None): + nonlocal best_auc + nonlocal best_auc_epoch + nonlocal best_auc_marker + nonlocal last_eval_step + + did_save_epoch_before_eval = False + if save_before_eval: + self._barrier() + if self.is_main_process: + if epoch_for_tag is not None and save_by_epoch: + pre_eval_tag = str(epoch_for_tag) + did_save_epoch_before_eval = True + elif step_for_tag is not None: + pre_eval_tag = f"pre_eval_s{int(step_for_tag)}" + elif epoch_for_tag is not None: + pre_eval_tag = f"pre_eval_e{int(epoch_for_tag)}" + else: + pre_eval_tag = f"pre_eval_s{int(self.model.total_steps)}" + self.model.save_networks(pre_eval_tag) + print(f"[Checkpoint] Saved pre-eval checkpoint: {pre_eval_tag}") + self._barrier() + + self.model.eval() + self._barrier() + run_eval_on_all_ranks = self.distributed and self.accel_backend in {"official_fsdp", "deepspeed"} + if self.is_main_process or run_eval_on_all_ranks: + # FSDP/DeepSpeed evaluation requires all ranks to participate in forward pass. + if (not self.is_main_process) and run_eval_on_all_ranks: + with open(os.devnull, "w") as devnull: + with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull): + acc, auc, ap = self.test_model() + else: + acc, auc, ap = self.test_model() + + if self.is_main_process: + if epoch_for_tag is not None: + if save_by_epoch and not did_save_epoch_before_eval: + self.model.save_networks(str(int(epoch_for_tag))) + elif not save_best_by_auc: + self.model.save_networks(f'{acc:.3f}_{auc:.3f}') + else: + if save_by_epoch: + self.model.save_networks(f"step_{int(step_for_tag)}") + elif not save_best_by_auc: + self.model.save_networks(f'{acc:.3f}_{auc:.3f}') + + if save_best_by_auc and (auc > best_auc + best_auc_delta): + best_auc = float(auc) + if epoch_for_tag is not None: + best_auc_epoch = int(epoch_for_tag) + best_auc_marker = f"epoch={best_auc_epoch}" + save_tag = f"best_auc_{best_auc:.4f}_e{best_auc_epoch}" + else: + best_auc_marker = f"step={int(step_for_tag)}" + save_tag = f"best_auc_{best_auc:.4f}_s{int(step_for_tag)}" + self.model.save_networks(save_tag) + print( + f"[Checkpoint] New best AUC={best_auc:.6f} at {best_auc_marker}; " + "saved best checkpoint." + ) + _prune_best_auc_checkpoints() + else: + acc, auc, ap = 0.0, 0.0, 0.0 + + if self.distributed: + metrics = torch.tensor([acc, auc, ap], dtype=torch.float32, device=self.model.device) + dist.broadcast(metrics, src=0) + acc, auc, ap = float(metrics[0].item()), float(metrics[1].item()), float(metrics[2].item()) + self._barrier() + + if self.val_writer: + self.val_writer.add_scalar('accuracy', acc, self.model.total_steps) + self.val_writer.add_scalar('auc', auc, self.model.total_steps) + self.val_writer.add_scalar('ap', ap, self.model.total_steps) + + if self.is_main_process: + print(f"(Val @ {eval_label}) acc: {acc}; auc: {auc}; ap: {ap}") + self.model.train() + last_eval_step = int(self.model.total_steps) + + def _run_val_finetune_after_eval(eval_label, *, epoch_for_sampler): + if not val_ft_enable: + return + + ft_opt = copy.deepcopy(self.opt) + ft_opt.isTrain = True + ft_opt.serial_batches = False + ft_opt.class_bal = bool(val_ft_class_bal) + ft_opt.batch_size = int(val_ft_batch_size) + ft_opt.dataroot = val_ft_roots[0] + ft_opt.extra_train_roots = list(val_ft_roots[1:]) + + if not val_ft_use_train_aug: + # Default to "distribution alignment": no synthetic train-time corruption. + ft_opt.data_aug = False + ft_opt.no_flip = True + ft_opt.use_aug_utils_train = False + ft_opt.use_testshift_like_aug = False + + # Optional fine control for this stage. + for key in [ + "data_aug", + "no_flip", + "no_resize", + "loadSize", + "cropSize", + "use_aug_utils_train", + "aug_utils_prob", + "aug_utils_max_distortions", + "aug_utils_num_levels", + "use_testshift_like_aug", + "testshift_like_apply_prob", + "testshift_like_max_groups", + ]: + if key in val_ft_cfg: + setattr(ft_opt, key, val_ft_cfg.get(key)) + + self._barrier() + ft_loader = self._build_dataloader_for_opt( + ft_opt, + distributed=self.distributed, + log_prefix="[ValFT]", + ) + self._barrier() + + start_steps = int(self.model.total_steps) + ft_steps = 0 + t0 = time.time() + self.model.train() + + for local_ep in range(val_ft_epochs_per_round): + if hasattr(ft_loader, "dataset") and hasattr(ft_loader.dataset, "set_epoch"): + ft_loader.dataset.set_epoch(int(epoch_for_sampler) * 1000 + int(local_ep)) + if hasattr(ft_loader, "sampler") and hasattr(ft_loader.sampler, "set_epoch"): + ft_loader.sampler.set_epoch(int(epoch_for_sampler) * 1000 + int(local_ep)) + + for data in ft_loader: + if val_ft_max_steps > 0 and ft_steps >= val_ft_max_steps: + break + self.model.total_steps += 1 + self.model.set_input(data) + self.model.optimize_parameters() + ft_steps += 1 + + if self.is_main_process and (self.model.total_steps % loss_print_freq == 0): + loss_scalar = float(self.model.loss.detach().item()) + print( + f"{time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime())} " + f"[ValFT] loss: {loss_scalar} at step: {self.model.total_steps} " + f"(trigger={eval_label})" + ) + + if val_ft_max_steps > 0 and ft_steps >= val_ft_max_steps: + break + + self._barrier() + if self.is_main_process: + dt = time.time() - t0 + print( + f"[ValFT] done trigger={eval_label}, steps={ft_steps}, " + f"global_step {start_steps}->{self.model.total_steps}, time={dt:.1f}s" + ) + + # Training loop + for epoch in range(total_epochs): + _apply_curriculum_if_needed(epoch + 1) + epoch_start_time = time.time() + epoch_iter = 0 + if hasattr(self.data_loader, "dataset") and hasattr(self.data_loader.dataset, "set_epoch"): + self.data_loader.dataset.set_epoch(epoch) + if hasattr(self.data_loader, "sampler") and hasattr(self.data_loader.sampler, "set_epoch"): + self.data_loader.sampler.set_epoch(epoch) + + if self.is_main_process: + print(f"Epoch {epoch + 1}/{total_epochs}") + + for i, data in enumerate(self.data_loader): + self.model.total_steps += 1 + epoch_iter += train_batch_size + self.model.set_input(data) + self.model.optimize_parameters() + # Log training loss + if self.model.total_steps % loss_print_freq == 0: + loss_scalar = float(self.model.loss.detach().item()) + js_scalar = None + if getattr(self.model, "augmix_js_loss", None) is not None: + js_scalar = float(self.model.augmix_js_loss.item()) + if self.is_main_process: + timestamp = time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime()) + msg = ( + f"{timestamp} Train loss: {loss_scalar} at step: {self.model.total_steps} lr {self.model.lr}" + ) + if js_scalar is not None: + msg += f" augmix_js: {js_scalar}" + print(msg) + + if plateau_enabled and lr_adjustment_available and self.model.should_adjust_lr_on_plateau(loss_scalar): + timestamp = time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime()) + if self.is_main_process: + print(f"{timestamp} Loss plateau detected (patience {plateau_patience}); adjusting lr") + lr_adjustment_available = self.model.adjust_learning_rate() + if not lr_adjustment_available: + plateau_enabled = False + + if self.train_writer: + self.train_writer.add_scalar('loss', loss_scalar, self.model.total_steps) + if js_scalar is not None: + self.train_writer.add_scalar('augmix_js_loss', js_scalar, self.model.total_steps) + + if ( + eval_every_steps > 0 + and self.model.total_steps % eval_every_steps == 0 + ): + _run_validation( + f"step {self.model.total_steps}", + step_for_tag=int(self.model.total_steps), + ) + if val_ft_enable and val_ft_run_on_step_eval: + _run_val_finetune_after_eval( + f"step {self.model.total_steps}", + epoch_for_sampler=int(epoch + 1), + ) + + if hasattr(self.model, "finalize_epoch"): + self.model.finalize_epoch() + + # Learning rate decay + if ( + lr_adjustment_available + and not plateau_enabled + and epoch % delr_freq == 0 + and epoch != 0 + ): + if self.is_main_process: + print(f"{time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime())} " + f"Changing lr at the end of epoch {epoch}, iters {self.model.total_steps}") + lr_adjustment_available = self.model.adjust_learning_rate() + + if skip_eval_during_train: + self._barrier() + if self.is_main_process: + if save_by_epoch: + self.model.save_networks(str(epoch + 1)) + else: + if save_last_checkpoint: + self.model.save_networks('last') + self._barrier() + self.model.train() + continue + + if eval_by_epoch: + if last_eval_step == int(self.model.total_steps): + if self.is_main_process: + print( + f"[Eval] Skip epoch-end validation at epoch {epoch + 1}: " + f"already validated at step {self.model.total_steps}." + ) + else: + _run_validation( + f"epoch {epoch + 1}", + epoch_for_tag=int(epoch + 1), + ) + _run_val_finetune_after_eval( + f"epoch {epoch + 1}", + epoch_for_sampler=int(epoch + 1), + ) + + # Final testing and saving + self.model.eval() + # self.validate_holdout_split() + self._barrier() + if self.is_main_process: + if not skip_final_eval: + self.test_model() + else: + print("[Eval] Final validation disabled (training.skip_final_eval=true).") + if save_best_by_auc and (best_auc_epoch > 0 or best_auc_marker): + marker = best_auc_marker or f"epoch={best_auc_epoch}" + print(f"[Checkpoint] Best AUC summary: {marker}, auc={best_auc:.6f}") + if save_last_checkpoint: + self.model.save_networks('last') + print("Training completed!") + self._barrier() + +def main(): + """Main function.""" + parser = create_argument_parser() + args = parser.parse_args() + + # Load configuration + config_loader = load_config_from_args(args) + + # Create and run trainer + trainer = UnifiedTrainer(config_loader) + try: + trainer.train() + finally: + trainer.cleanup() + + +if __name__ == '__main__': + main() diff --git a/detectors/ForensicConcept/upstream/util.py b/detectors/ForensicConcept/upstream/util.py new file mode 100644 index 0000000000000000000000000000000000000000..94f2331859a9182914adfe59491d20f6acc96867 --- /dev/null +++ b/detectors/ForensicConcept/upstream/util.py @@ -0,0 +1,148 @@ +import sys +import os +import json +from pathlib import Path +from typing import Any, Dict, Optional + +import torch + + +def mkdirs(paths): + if isinstance(paths, list) and not isinstance(paths, str): + for path in paths: + mkdir(path) + else: + mkdir(paths) + + +def mkdir(path): + if not os.path.exists(path): + os.makedirs(path) + + +def unnormalize(tens, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]): + # assume tensor of shape NxCxHxW + return tens * torch.Tensor(std)[None, :, None, None] + torch.Tensor( + mean)[None, :, None, None] + + + + +class Logger(object): + """Log stdout messages.""" + + def __init__(self, outfile): + self.terminal = sys.stdout + self.log = open(outfile, "a") + sys.stdout = self + + def write(self, message): + self.terminal.write(message) + self.log.write(message) + + def flush(self): + self.terminal.flush() + + +def printSet(set_str): + set_str = str(set_str) + num = len(set_str) + print("="*num*3) + print(" "*num + set_str) + print("="*num*3) + + +class ConceptSparsityRecorder: + """Accumulates kept-cluster statistics for concept sparsification runs.""" + + def __init__( + self, + output_path: Optional[str], + *, + dataset: Optional[str] = None, + extra_meta: Optional[Dict[str, Any]] = None, + accumulate_runs: bool = True, + ) -> None: + self._path = Path(output_path).expanduser().resolve() if output_path else None + self._records: Dict[str, Dict[str, Any]] = {} + self._meta: Dict[str, Any] = {} + self._accumulate = accumulate_runs + if dataset: + self._meta["dataroot"] = dataset + if extra_meta: + self._meta.update(extra_meta) + + def enabled(self) -> bool: + return self._path is not None + + def update(self, key: str, ratio: float, keep_mask: Optional[torch.Tensor]) -> None: + if not self.enabled() or keep_mask is None: + return + entry = self._records.setdefault(key, {"ratio": ratio, "counts": None, "samples": 0}) + counts = keep_mask.to(torch.int64).sum(dim=0).detach().cpu() + if entry["counts"] is None: + entry["counts"] = counts.clone() + else: + entry["counts"] += counts + entry["samples"] += keep_mask.shape[0] + + def finalize(self, *, total_samples: Optional[int] = None) -> Optional[Dict[str, Any]]: + if not self.enabled() or not self._records: + return None + + run_entry: Dict[str, Any] = { + "metadata": dict(self._meta), + "ratios": [], + } + if total_samples is not None: + run_entry["metadata"]["total_samples"] = int(total_samples) + + def _sort_key(item: tuple[str, Dict[str, Any]]) -> float: + return item[1]["ratio"] + + for key, entry in sorted(self._records.items(), key=_sort_key): + counts_tensor: Optional[torch.Tensor] = entry.get("counts") + if counts_tensor is None: + continue + counts_list = counts_tensor.tolist() + order = [idx for idx, val in sorted( + enumerate(counts_list), key=lambda pair: pair[1], reverse=True + ) if val > 0] + kept_total = int(sum(counts_list)) + ratio_payload = { + "ratio": float(entry["ratio"]), + "samples": int(entry["samples"]), + "kept_total": kept_total, + "avg_kept_per_sample": float(kept_total / entry["samples"]) + if entry["samples"] + else 0.0, + "clusters": [ + {"cluster_id": int(idx), "kept": int(counts_list[idx])} + for idx in order + ], + } + run_entry["ratios"].append(ratio_payload) + + payload: Any + if self._accumulate: + runs = [] + if self._path.is_file(): + try: + existing = json.loads(self._path.read_text(encoding="utf-8")) + if isinstance(existing, dict) and "runs" in existing and isinstance(existing["runs"], list): + runs = existing["runs"] + elif isinstance(existing, list): + runs = existing + elif isinstance(existing, dict) and existing: + runs = [existing] + except json.JSONDecodeError: + runs = [] + runs.append(run_entry) + payload = {"runs": runs} + else: + payload = run_entry + + self._path.parent.mkdir(parents=True, exist_ok=True) + with open(self._path, "w", encoding="utf-8") as handle: + json.dump(payload, handle, ensure_ascii=False, indent=2) + return run_entry diff --git a/detectors/ForensicConcept/upstream/validate.py b/detectors/ForensicConcept/upstream/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..85a27115f8ef1526c4012faf43d94434021075b6 --- /dev/null +++ b/detectors/ForensicConcept/upstream/validate.py @@ -0,0 +1,422 @@ +import json +import math +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import ConcatDataset, Subset +from tqdm import tqdm + +from sklearn.metrics import average_precision_score, accuracy_score, roc_auc_score +from data import create_dataloader +from util import ConceptSparsityRecorder + + +def _compute_binary_metrics(y_true: np.ndarray, y_pred: np.ndarray, y_prob: np.ndarray, reverse: bool) -> dict: + if reverse: + real_mask = y_true == 1 + fake_mask = y_true == 0 + else: + real_mask = y_true == 0 + fake_mask = y_true == 1 + + try: + auc = roc_auc_score(y_true, y_prob) if y_prob.size > 0 else 0.5 + except ValueError: + # roc_auc_score is undefined when only one class is present in y_true. + auc = 0.5 + + metrics = { + "acc": accuracy_score(y_true, y_pred), + "auc": float(auc), + "ap": average_precision_score(y_true, y_prob) if y_prob.size > 0 else 0.0, + "r_acc": accuracy_score(y_true[real_mask], y_pred[real_mask]) if real_mask.any() else 0.0, + "f_acc": accuracy_score(y_true[fake_mask], y_pred[fake_mask]) if fake_mask.any() else 0.0, + "y_pred": y_pred, + "y_prob": y_prob, + } + return metrics + + +def _format_ratio_key(ratio: float) -> str: + ratio_str = f"{ratio:.6f}".rstrip("0").rstrip(".") + return ratio_str if ratio_str else "0" + + +def _extract_dataset_paths(dataset): + """Return a flat list of file paths for ImageFolder-style datasets, or None.""" + if isinstance(dataset, Subset): + base_paths = _extract_dataset_paths(dataset.dataset) + if base_paths is None: + return None + return [base_paths[i] for i in dataset.indices] + if isinstance(dataset, ConcatDataset): + paths = [] + for sub in dataset.datasets: + sub_paths = _extract_dataset_paths(sub) + if sub_paths is None: + return None + paths.extend(sub_paths) + return paths + if hasattr(dataset, "samples"): + return [path for path, _ in dataset.samples] + if hasattr(dataset, "imgs"): + return [path for path, _ in dataset.imgs] + return None + + +def _get_patch_size_from_model(model) -> int: + """Best-effort extraction of patch size from CLIP/ViT style models.""" + visual = getattr(model, "visual", None) + if visual is None and hasattr(model, "model"): + visual = getattr(model.model, "visual", None) + if visual is None: + return 0 + patch_size = getattr(visual, "patch_size", None) + if isinstance(patch_size, (tuple, list)): + patch_size = patch_size[0] + if patch_size: + return int(patch_size) + conv1 = getattr(visual, "conv1", None) + if conv1 is not None and hasattr(conv1, "kernel_size"): + ks = conv1.kernel_size + return int(ks[0]) if isinstance(ks, (tuple, list)) else int(ks) + return 0 + + +def _infer_grid_size(num_patches: int, height: int, width: int, patch_size: int): + """Infer (grid_h, grid_w) for patch tokens.""" + if patch_size and height % patch_size == 0 and width % patch_size == 0: + grid_h = height // patch_size + grid_w = width // patch_size + if grid_h * grid_w == num_patches: + return grid_h, grid_w + if num_patches: + side = int(math.sqrt(num_patches)) + if side * side == num_patches: + return side, side + if patch_size and num_patches and width: + grid_w = max(1, int(round(width / patch_size))) + grid_h = max(1, int(math.ceil(num_patches / grid_w))) + return grid_h, grid_w + return 0, 0 + + +def validate(model, opt): + print( + f"[validate] dataroot={getattr(opt, 'dataroot', None)} " + f"data_aug={getattr(opt, 'data_aug', None)} " + f"isTrain={getattr(opt, 'isTrain', None)}" + ) + data_loader = create_dataloader(opt) + + # Keep evaluation on the same device as the model to avoid cross-GPU tensor mixups. + try: + model_device = next(model.parameters()).device + except StopIteration: + model_device = torch.device("cpu") + num_classes = getattr(opt, "num_classes", 1) + reverse = getattr(opt, "reverse", False) + try: + max_eval_samples = int(getattr(opt, "max_eval_samples", 0) or 0) + except (TypeError, ValueError): + max_eval_samples = 0 + + + eval_ratios = ( + getattr(opt, "clip_concept_eval_sparsity", None) + or getattr(opt, "dinov3_concept_eval_sparsity", None) + or [] + ) + sparsity_recorder = ConceptSparsityRecorder( + getattr(opt, "clip_concept_eval_log_path", None) + or getattr(opt, "dinov3_concept_eval_log_path", None), + dataset=getattr(opt, "dataroot", None), + extra_meta={ + "mode": "validate", + "experiment": getattr(opt, "name", None), + }, + ) + + coords_path_raw = getattr(opt, "codebook_coords_path", None) + dataset_name = getattr(opt, "dataset_name", None) or Path(getattr(opt, "dataroot", "dataset")).name or "dataset" + if coords_path_raw and "{dataset}" in str(coords_path_raw): + coords_path_raw = str(coords_path_raw).replace("{dataset}", dataset_name) + coords_limit = getattr(opt, "codebook_coords_limit", None) + try: + coords_limit = int(coords_limit) if coords_limit is not None else None + except (TypeError, ValueError): + coords_limit = None + + coords_path = Path(coords_path_raw).expanduser() if coords_path_raw else None + coords_mode = None + coords_base_dir = None + if coords_path: + suffix = coords_path.suffix.lower() + if suffix in {".dat", ".jsonl"}: + coords_mode = "dat" if suffix == ".dat" else "jsonl" + else: + coords_base_dir = coords_path + coords_mode = "dat" + coords_fp = None + coords_bin = None + indices_bin = None + scores_bin = None + concepts_bin = None + paths_fp = None + sample_paths = None + dumped_labels = [] + dumped_samples = 0 + meta_template = {} + if coords_path: + if coords_base_dir is not None: + coords_path = coords_base_dir / dataset_name / ( + "top_patch_coords.dat" if coords_mode == "dat" else "coords.jsonl" + ) + coords_path.parent.mkdir(parents=True, exist_ok=True) + sample_paths = _extract_dataset_paths(data_loader.dataset) + if coords_mode == "jsonl": + coords_fp = coords_path.open("w", encoding="utf-8") + print(f"[validate] dumping codebook coords to {coords_path}") + else: + coords_bin = coords_path.open("wb") + indices_bin = coords_path.with_name("top_patch_indices.dat").open("wb") + scores_bin = coords_path.with_name("top_patch_scores.dat").open("wb") + concepts_bin = coords_path.with_name("top_patch_concept_ids.dat").open("wb") + paths_fp = coords_path.with_name("paths.txt").open("w", encoding="utf-8") + print(f"[validate] dumping codebook coords to {coords_path} (dat format)") + + sample_offset = 0 + with torch.no_grad(): + y_true: list = [] + head_probs: defaultdict = defaultdict(list) + head_preds: defaultdict = defaultdict(list) + for img, label in tqdm(data_loader, desc="Testing", leave=False): + if max_eval_samples > 0 and sample_offset >= max_eval_samples: + break + if max_eval_samples > 0: + remain = max_eval_samples - sample_offset + if remain <= 0: + break + if img.shape[0] > remain: + img = img[:remain] + label = label[:remain] + in_tens = img.to(model_device, non_blocking=True) + if coords_path is not None: + try: + raw_output = model(in_tens, return_debug=True) + except TypeError: + raw_output = model(in_tens) + else: + raw_output = model(in_tens) + + head_outputs = {} + concept_raw = None + if isinstance(raw_output, dict): + if raw_output.get("logits") is not None: + head_outputs["main"] = raw_output["logits"] + if raw_output.get("cb_only") is not None: + head_outputs["cb_only"] = raw_output["cb_only"] + if raw_output.get("concept_logits") is not None: + head_outputs["concept"] = raw_output["concept_logits"] + if raw_output.get("token_logits") is not None: + head_outputs["token"] = raw_output["token_logits"] + concept_raw = raw_output.get("concept_features_raw") + elif isinstance(raw_output, tuple): + head_outputs["main"] = raw_output[0] + else: + head_outputs["main"] = raw_output + + if concept_raw is not None and eval_ratios: + for ratio in eval_ratios: + try: + ratio_val = float(ratio) + except (TypeError, ValueError): + continue + key = f"concept_s_{_format_ratio_key(ratio_val)}" + if sparsity_recorder.enabled(): + logits_variant, keep_mask = model.compute_concept_logits_with_ratio( + concept_raw, ratio_val, return_mask=True + ) + sparsity_recorder.update(key, ratio_val, keep_mask) + else: + logits_variant = model.compute_concept_logits_with_ratio(concept_raw, ratio_val) + head_outputs[key] = logits_variant + + labels_cpu = label.flatten().cpu().tolist() + y_true.extend(labels_cpu) + + for head_name, logits in head_outputs.items(): + logits_cpu = logits.detach().cpu() + if logits_cpu.ndim == 1: + logits_cpu = logits_cpu.unsqueeze(1) + if num_classes == 1 or logits_cpu.shape[1] == 1: + probs_fake = torch.sigmoid(logits_cpu).flatten() + preds = (probs_fake >= 0.5).long() + head_probs[head_name].extend(probs_fake.tolist()) + head_preds[head_name].extend(preds.tolist()) + else: + probs = torch.softmax(logits_cpu, dim=1) + probs_fake = probs[:, 1] + preds = torch.argmax(probs, dim=1) + head_probs[head_name].extend(probs_fake.tolist()) + head_preds[head_name].extend(preds.tolist()) + + if coords_path is not None and isinstance(raw_output, dict): + topk_idx = raw_output.get("codebook_topk_idx") + if topk_idx is not None: + num_patches = None + tokens = raw_output.get("tokens") + if tokens is not None and hasattr(tokens, "shape"): + num_patches = int(tokens.shape[1]) + if "embedding_dim" not in meta_template: + meta_template["embedding_dim"] = int(tokens.shape[-1]) + if num_patches is None: + num_patches = int(getattr(model, "num_patches", 0) or 0) + if not num_patches: + num_patches = int(getattr(opt, "clip_num_patches", 0) or 0) + if not num_patches: + num_patches = int(topk_idx.max().item() + 1) + + height, width = int(in_tens.shape[-2]), int(in_tens.shape[-1]) + patch_size = _get_patch_size_from_model(model) + grid_h, grid_w = _infer_grid_size(num_patches, height, width, patch_size) + + if coords_mode == "jsonl": + topk_idx_cpu = topk_idx.detach().cpu().tolist() + for b, idx_list in enumerate(topk_idx_cpu): + global_idx = sample_offset + b + if coords_limit is not None and global_idx >= coords_limit: + continue + path = None + if sample_paths is not None and global_idx < len(sample_paths): + path = sample_paths[global_idx] + coords_rc = None + coords_xyxy = None + if grid_w and grid_h: + coords_rc = [] + coords_xyxy = [] + for idx in idx_list: + row = int(idx) // grid_w + col = int(idx) % grid_w + coords_rc.append([row, col]) + if patch_size: + x0 = col * patch_size + y0 = row * patch_size + coords_xyxy.append([x0, y0, x0 + patch_size, y0 + patch_size]) + entry = { + "index": int(global_idx), + "path": path, + "label": int(labels_cpu[b]) if b < len(labels_cpu) else None, + "topk_idx": [int(i) for i in idx_list], + "coords_rc": coords_rc, + "coords_xyxy": coords_xyxy if coords_xyxy else None, + "grid_size": [int(grid_h), int(grid_w)] if grid_h and grid_w else None, + "patch_size": int(patch_size) if patch_size else None, + "image_size": [height, width], + } + coords_fp.write(json.dumps(entry, ensure_ascii=True) + "\n") + else: + idx_np = topk_idx.detach().cpu().to(torch.int32).numpy() + if idx_np.ndim == 1: + idx_np = idx_np.reshape(-1, 1) + top_k = idx_np.shape[1] + scores = raw_output.get("codebook_score") + topk_concept = raw_output.get("codebook_topk_concept") + if scores is not None: + score_np = scores.detach().cpu().numpy() + score_sel = np.take_along_axis(score_np, idx_np.astype(np.int64), axis=1).astype(np.float32) + else: + score_sel = np.zeros_like(idx_np, dtype=np.float32) + if topk_concept is not None: + concept_sel = topk_concept.detach().cpu().to(torch.int32).numpy() + else: + concept_sel = np.zeros_like(idx_np, dtype=np.int32) + + if grid_w and grid_h: + row = idx_np // grid_w + col = idx_np % grid_w + coords_packed = (row.astype(np.int32) << 16) | col.astype(np.int32) + else: + coords_packed = idx_np.astype(np.int32) + + for b in range(idx_np.shape[0]): + global_idx = sample_offset + b + if coords_limit is not None and global_idx >= coords_limit: + continue + coords_packed[b].tofile(coords_bin) + idx_np[b].tofile(indices_bin) + score_sel[b].tofile(scores_bin) + if concepts_bin is not None: + concept_sel[b].reshape(-1).tofile(concepts_bin) + if paths_fp is not None and sample_paths is not None and global_idx < len(sample_paths): + paths_fp.write(f"{sample_paths[global_idx]}\n") + dumped_labels.append(int(labels_cpu[b]) if b < len(labels_cpu) else 0) + dumped_samples += 1 + if "num_patches" not in meta_template: + meta_template["num_patches"] = int(num_patches) + if "top_k" not in meta_template: + meta_template["top_k"] = int(top_k) + if "top_r" not in meta_template and concept_sel is not None and concept_sel.ndim == 3: + meta_template["top_r"] = int(concept_sel.shape[-1]) + if "grid_h" not in meta_template and grid_h and grid_w: + meta_template["grid_h"] = int(grid_h) + meta_template["grid_w"] = int(grid_w) + if "patch_size" not in meta_template and patch_size: + meta_template["patch_size"] = int(patch_size) + + sample_offset += len(labels_cpu) + y_true_arr = np.array(y_true) + metrics = {} + for head_name, preds in head_preds.items(): + y_pred_arr = np.array(preds) + y_prob_arr = np.array(head_probs[head_name]) + metrics[head_name] = _compute_binary_metrics(y_true_arr, y_pred_arr, y_prob_arr, reverse) + + sparsity_recorder.finalize(total_samples=len(y_true)) + + if coords_fp is not None: + coords_fp.close() + if coords_mode == "dat": + if coords_bin is not None: + coords_bin.close() + if indices_bin is not None: + indices_bin.close() + if scores_bin is not None: + scores_bin.close() + if concepts_bin is not None: + concepts_bin.close() + paths_path = coords_path.with_name("paths.txt") + labels_path = coords_path.with_name("labels.npy") + meta_path = coords_path.with_name("meta.json") + if paths_fp is not None: + paths_fp.close() + if dumped_labels: + np.save(labels_path, np.array(dumped_labels, dtype=np.int64)) + patch_grid = None + if meta_template.get("grid_h") and meta_template.get("grid_w"): + patch_grid = [meta_template["grid_h"], meta_template["grid_w"]] + patch_size = meta_template.get("patch_size") + meta = { + "top_patch_tokens.dat": None, + "top_patch_scores.dat": "top_patch_scores.dat", + "cls_tokens.dat": None, + "top_patch_indices.dat": "top_patch_indices.dat", + "top_patch_coords.dat": coords_path.name, + "top_patch_concept_ids.dat": "top_patch_concept_ids.dat", + "num_samples": dumped_samples, + "num_patches": meta_template.get("num_patches"), + "top_k": meta_template.get("top_k"), + "top_r": meta_template.get("top_r"), + "embedding_dim": meta_template.get("embedding_dim"), + "projection": "post", + "dtype": "float32", + "labels.npy": labels_path.name, + "paths.txt": paths_path.name, + "patch_grid": patch_grid, + "patch_size": [patch_size, patch_size] if patch_size else None, + } + with meta_path.open("w", encoding="utf-8") as fp: + json.dump(meta, fp, indent=2) + return metrics, y_true_arr diff --git a/detectors/MDMF/checkpoint/pretrained/weights/calibration.json b/detectors/MDMF/checkpoint/pretrained/weights/calibration.json new file mode 100644 index 0000000000000000000000000000000000000000..b8862335b3801abf486324e2923c20b5ce85f601 --- /dev/null +++ b/detectors/MDMF/checkpoint/pretrained/weights/calibration.json @@ -0,0 +1,7 @@ +{ + "threshold": 0.0004629194736480713, + "scale": 0.0001961737871170044, + "source": "validation split", + "real_count": 16, + "fake_count": 16 +} diff --git a/detectors/MDMF/checkpoint/pretrained/weights/reference.pkl b/detectors/MDMF/checkpoint/pretrained/weights/reference.pkl new file mode 100644 index 0000000000000000000000000000000000000000..5040c577789a973834179a1450d6193907bd6cdd --- /dev/null +++ b/detectors/MDMF/checkpoint/pretrained/weights/reference.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b5dfe8e2abc948266aece16d61d6f4234e7c749e7bc719c2a2988a2f28d71be +size 3213111 diff --git a/detectors/MDMF/detect.py b/detectors/MDMF/detect.py new file mode 100644 index 0000000000000000000000000000000000000000..522ff9aa1d6e556109504580af8c068d97076239 --- /dev/null +++ b/detectors/MDMF/detect.py @@ -0,0 +1,4 @@ +from run import main + +if __name__ == "__main__": + main("detect") diff --git a/detectors/MDMF/prepare.py b/detectors/MDMF/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..f0bfa026621b848c2638ba9c6975a3264d573e8b --- /dev/null +++ b/detectors/MDMF/prepare.py @@ -0,0 +1,27 @@ +"""Build an MDMF reference from real training images and calibrate on validation.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from run import HERE, backbone_for, calibrate, model_for, reference_for +from support.recent_common import checkpoint, device_for, parser, validate_inputs +from support.recent_data import samples +from run import embedding_bank + + +if __name__ == "__main__": + args = parser("MDMF", "prepare").parse_args() + validate_inputs(args, "prepare") + device = device_for(args.device) + directory = HERE / "checkpoint" / args.name / "weights" + model, patch_size = model_for(checkpoint("MDMF", args.name), device) + backbone = backbone_for(device) + real = [(p, y) for p, y in samples(args.data_root, args.split_file, "train", args.data_keys) if y == 0] + if not real: + raise ValueError("No real training images for MDMF reference") + embedding_bank(backbone, device, real, "train", directory / "reference.pkl", args.batch_size) + reference = reference_for(model, device, directory / "reference.pkl") + val = samples(args.data_root, args.split_file, "val", args.data_keys) + calibrate(backbone, model, device, patch_size, reference, val, directory / "calibration.json") + print(f"Prepared {len(real)} training-real reference images") diff --git a/detectors/MDMF/run.py b/detectors/MDMF/run.py new file mode 100644 index 0000000000000000000000000000000000000000..55256087d3c7d290586cb96481fdceb73d3f2214 --- /dev/null +++ b/detectors/MDMF/run.py @@ -0,0 +1,195 @@ +"""DeepShield adapter for MDMF's DINOv2 embeddings and MMDยฒ score.""" + +import json +import math +import pickle +import sys +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path[:0] = [str(ROOT), str(HERE / "upstream" / "src")] + +import torch +from PIL import Image +from torchvision import transforms +from transformers import AutoModel + +from support.recent_common import checkpoint, detection_result, device_for, parser, timed_score, validate_inputs, write_results +from support.recent_data import samples +from test_MDMF import MMD_MIL_Detector, pool_tokens_to_patch_size, precompute_ref_stats, score_mmd2_batch + + +def backbone_for(device): + location = HERE / "checkpoint" / "backbones" / "dinov2-large" + if not (location / "config.json").is_file(): + raise FileNotFoundError(f"DINOv2 backbone missing: {location}; run support/setup_recent_weights.py MDMF") + return AutoModel.from_pretrained(location).to(device).eval() + + +TRANSFORM = transforms.Compose([ + transforms.Resize((224, 224)), transforms.ToTensor(), + transforms.Normalize([.485, .456, .406], [.229, .224, .225]), +]) + + +@torch.inference_mode() +def embedding_batch(backbone, device, paths, patch_size=32): + images = [] + for path in paths: + with Image.open(path) as image: + images.append(TRANSFORM(image.convert("RGB"))) + tensor = torch.stack(images).to(device) + tokens = backbone(tensor).last_hidden_state[:, 1:, :].float() + return pool_tokens_to_patch_size(tokens, patch_size, 224).cpu().numpy() + + +def embedding(backbone, device, path, patch_size=32): + return embedding_batch(backbone, device, [path], patch_size)[0] + + +def embedding_bank(backbone, device, entries, split, target, batch_size=4): + vectors = [] + for offset in range(0, len(entries), batch_size): + vectors.extend(embedding_batch(backbone, device, + [path for path, _ in entries[offset:offset + batch_size]])) + data = {"embeddings": vectors, "labels": [label for _, label in entries], + "image_paths": [str(path) for path, _ in entries], "patch_size": 32, + "split": split, "embed_dim": 1024} + target.parent.mkdir(parents=True, exist_ok=True) + with target.open("wb") as handle: + pickle.dump(data, handle, protocol=4) + return data + + +def model_for(path, device): + state = torch.load(path, map_location="cpu", weights_only=False) + config = state.get("config", {}) + model = MMD_MIL_Detector(config.get("embed_dim", 1024), config.get("hidden_dim", 256), + config.get("dropout", .3), config.get("init_sigma", 1.)).to(device) + model.load_state_dict(state["model_state_dict"]) + return model.eval(), int(config.get("patch_size", 32)) + + +def reference_for(model, device, path): + if not path.is_file(): + raise FileNotFoundError(f"MDMF real training reference bank missing: {path}; run detectors/MDMF/prepare.py") + with path.open("rb") as handle: + bank = pickle.load(handle) + if bank.get("split") != "train" or any(bank["labels"]): + raise ValueError("MDMF reference bank must contain training-split real images only") + if not bank["embeddings"]: + raise ValueError("MDMF reference bank is empty") + with torch.inference_mode(): + logits = torch.stack([model.compute_logits(torch.from_numpy(x).float().unsqueeze(0).to(device)).squeeze(0) + for x in bank["embeddings"]]) + stats = precompute_ref_stats(logits, model.get_sigma()) + return logits, stats + + +def scorer(backbone, model, device, patch_size, reference, calibration): + ref, (xx_mean, norm2) = reference + threshold, scale = calibration["threshold"], calibration["scale"] + + @torch.inference_mode() + def score_batch(paths): + vectors = torch.from_numpy(embedding_batch(backbone, device, paths, patch_size)).float().to(device) + logits = model.compute_logits(vectors) + raws = score_mmd2_batch(ref, norm2, xx_mean, logits, model.get_sigma()) + fakes = torch.sigmoid((raws - threshold) / scale) + return list(zip(raws.cpu().tolist(), fakes.cpu().tolist())) + + def score(path): + return score_batch([path])[0] + + score.batch = score_batch + return score + + +def calibrate(backbone, model, device, patch_size, reference, entries, path): + # The released MDMF checkpoint contains no binary decision threshold. + neutral = {"threshold": 0., "scale": 1.} + score = scorer(backbone, model, device, patch_size, reference, neutral) + real = [score(p)[0] for p, label in entries if label == 0] + fake = [score(p)[0] for p, label in entries if label == 1] + if not real or not fake: + raise ValueError("MDMF calibration needs both real and fake validation images") + import statistics + a, b = statistics.median(real), statistics.median(fake) + if b <= a: + raise ValueError("MDMF validation scores do not separate in the expected direction; inspect data and checkpoint") + result = {"threshold": (a + b) / 2, "scale": max((b - a) / 4, 1e-6), + "source": "validation split", "real_count": len(real), "fake_count": len(fake)} + path.write_text(json.dumps(result, indent=2) + "\n") + return result + + +def main(task): + args = parser("MDMF", task).parse_args() + validate_inputs(args, task) + device = device_for(args.device) + name = args.model or args.name if task == "detect" else args.name + directory = HERE / "checkpoint" / name / "weights" + backbone = backbone_for(device) + + if task == "train": + train = samples(args.data_root, args.split_file, "train", args.data_keys) + val = samples(args.data_root, args.split_file, "val", args.data_keys) + real = [(p, y) for p, y in train if y == 0] + if not real or not any(y == 1 for _, y in train): + raise ValueError("MDMF training requires real and fake training images") + directory.mkdir(parents=True, exist_ok=True) + train_bank = embedding_bank(backbone, device, train, "train", directory / "train.pkl", args.batch_size) + embedding_bank(backbone, device, real, "train", directory / "reference.pkl", args.batch_size) + model = MMD_MIL_Detector().to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) + real_vec = [torch.from_numpy(x).float() for x, y in zip(train_bank["embeddings"], train_bank["labels"]) if y == 0] + fake_vec = [torch.from_numpy(x).float() for x, y in zip(train_bank["embeddings"], train_bank["labels"]) if y == 1] + for epoch in range(args.epochs): + model.train() + half_batch = max(1, args.batch_size // 2) + steps = math.ceil(max(len(real_vec), len(fake_vec)) / half_batch) + if args.max_steps: + steps = min(steps, args.max_steps) + for step in range(steps): + a = torch.stack([real_vec[(step * half_batch + i) % len(real_vec)] + for i in range(half_batch)]).to(device) + b = torch.stack([fake_vec[(step * half_batch + i) % len(fake_vec)] + for i in range(half_batch)]).to(device) + optimizer.zero_grad(set_to_none=True) + loss, mmd, _ = model(a, b) + loss.backward() + optimizer.step() + print(f"epoch={epoch + 1} step={step + 1} loss={loss.item():.5f} mmd2={mmd.item():.5f}") + torch.save({"model_state_dict": model.state_dict(), "config": {"embed_dim": 1024, "hidden_dim": 256, + "dropout": .3, "init_sigma": 1., "patch_size": 32}}, directory / "best.pt") + model.eval() + reference = reference_for(model, device, directory / "reference.pkl") + calibrate(backbone, model, device, 32, reference, val, directory / "calibration.json") + return + + model, patch_size = model_for(checkpoint("MDMF", name), device) + reference = reference_for(model, device, directory / "reference.pkl") + calibration_path = directory / "calibration.json" + if not calibration_path.is_file(): + raise FileNotFoundError(f"MDMF calibration missing: {calibration_path}; run detectors/MDMF/prepare.py") + score = scorer(backbone, model, device, patch_size, reference, json.loads(calibration_path.read_text())) + if task == "detect": + image = Path(args.image) + if not image.is_file(): + raise FileNotFoundError(image) + raw, fake, elapsed = timed_score(score, image) + detection_result("MDMF", image, raw, fake, elapsed, args.output) + else: + rows = [] + entries = samples(args.data_root, args.split_file, "test", args.data_keys) + for offset in range(0, len(entries), args.batch_size): + chunk = entries[offset:offset + args.batch_size] + start = time.perf_counter() + scores = score.batch([path for path, _ in chunk]) + elapsed = (time.perf_counter() - start) / len(chunk) + for (path, label), (raw, fake) in zip(chunk, scores): + rows.append({"path": str(path), "label": label, "raw_score": raw, + "fake_score": fake, "prediction": int(fake >= .5), "elapsed_time": elapsed}) + write_results("MDMF", name, args.data_keys, rows) diff --git a/detectors/MDMF/test.py b/detectors/MDMF/test.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1a7a4aa7e0a6d8be04e70943b022b6dfa77d35 --- /dev/null +++ b/detectors/MDMF/test.py @@ -0,0 +1,4 @@ +from run import main + +if __name__ == "__main__": + main("test") diff --git a/detectors/MDMF/train.py b/detectors/MDMF/train.py new file mode 100644 index 0000000000000000000000000000000000000000..c7fd0a1ae6fd21a7b36d8d13da9cb1a9962627d5 --- /dev/null +++ b/detectors/MDMF/train.py @@ -0,0 +1,4 @@ +from run import main + +if __name__ == "__main__": + main("train") diff --git a/detectors/MDMF/upstream/LICENSE b/detectors/MDMF/upstream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3abf9290c62fe32390e4caacd0aa265807274d6c --- /dev/null +++ b/detectors/MDMF/upstream/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 The MDMF Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/detectors/MDMF/upstream/config.json b/detectors/MDMF/upstream/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a65bdf8d1d6b747b3420929f0f9a5c7cbbae95f1 --- /dev/null +++ b/detectors/MDMF/upstream/config.json @@ -0,0 +1,16 @@ +{ + "train_embeddings": "/path/to/train.pkl", + "val_embeddings": "/path/to/val.pkl", + "ref_embeddings": "/path/to/ref_5k.pkl", + "embed_dim": 1024, + "hidden_dim": 256, + "dropout": 0.3, + "init_sigma": 1.0, + "batch_size": 256, + "num_epochs": 25, + "lr": 0.0001, + "betas": [0.9, 0.99], + "weight_decay": 0.01, + "num_workers": 4, + "save_interval": 5 +} \ No newline at end of file diff --git a/detectors/MDMF/upstream/src/precompute_embeddings.py b/detectors/MDMF/upstream/src/precompute_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..3d4c336e0ac5bd08a7480f96e57999200e998cf5 --- /dev/null +++ b/detectors/MDMF/upstream/src/precompute_embeddings.py @@ -0,0 +1,668 @@ +""" +Pre-compute DINOv2 patch embeddings for training, validation, and reference sets. + +This script extracts patch-level embeddings using DINOv2 ViT-L/14 backbone. +""" + +import os +import math +import time +import random +import pickle +import argparse +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from torchvision import transforms +from torch.utils.data import Dataset, DataLoader +from PIL import Image +from tqdm import tqdm + + +# ================================ +# DINOv2 Helper Functions +# ================================ + +def get_patch_tokens(backbone, x): + """ + Extract patch tokens from a DINOv2 backbone. + + Args: + backbone: DINOv2 model + x: Input tensor (B, C, H, W) + + Returns: + tokens: Patch tokens (B, N, D) where N is number of patches + """ + if hasattr(backbone, "forward_features"): + out = backbone.forward_features(x) + else: + out = backbone(x) + + # Handle dict-like output + if isinstance(out, dict): + tokens = None + + # Try common keys for patch tokens + for key in ["x_norm_patchtokens", "patch_tokens", "tokens"]: + if key in out: + tokens = out[key] + break + + # Fallback: try full output with CLS token + if tokens is None: + for key in ["x_norm", "x"]: + if key in out: + t = out[key] + if t.dim() == 3 and t.size(1) > 1: + tokens = t[:, 1:, :] # Drop CLS token + break + + if tokens is None: + raise RuntimeError( + f"Cannot find patch tokens in output keys: {list(out.keys())}" + ) + + else: + # Handle tensor or tuple/list output + if isinstance(out, (list, tuple)): + out = out[0] + + if not torch.is_tensor(out): + raise RuntimeError(f"Unsupported backbone output type: {type(out)}") + + if out.dim() == 3 and out.size(1) > 1: + # Assume format: [CLS] + patch tokens + tokens = out[:, 1:, :] + else: + raise RuntimeError( + f"Cannot interpret backbone output shape {out.shape} as patch tokens" + ) + + return tokens # (B, N, D) + + +def pool_tokens_to_patch_size(tokens, patch_size, image_size=224): + """ + Pool token grid to match desired patch grid size. + + Args: + tokens: (B, N, D) patch tokens where N = H_t * W_t + patch_size: Desired virtual patch size (e.g., 16, 32, 56) + image_size: Input image size (default: 224) + + Returns: + pooled: (B, K, D) where K = (image_size // patch_size)^2 + """ + B, N, D = tokens.shape + H_t = int(math.sqrt(N)) + + if H_t * H_t != N: + raise ValueError(f"Token count {N} is not a perfect square") + + # Reshape to spatial grid: (B, H_t, W_t, D) + tokens_spatial = tokens.view(B, H_t, H_t, D) + + # Calculate target grid size + grid_size = image_size // patch_size + if grid_size < 1: + raise ValueError( + f"Patch size {patch_size} is too large for image size {image_size}" + ) + + # Adaptive pooling: (B, D, H_t, W_t) -> (B, D, grid_size, grid_size) + tokens_spatial_ch = tokens_spatial.permute(0, 3, 1, 2) + pooled = F.adaptive_avg_pool2d( + tokens_spatial_ch, + output_size=(grid_size, grid_size) + ) + + # Back to (B, K, D) + pooled = pooled.permute(0, 2, 3, 1).contiguous() + pooled = pooled.view(B, grid_size * grid_size, D) + + return pooled + + +# ================================ +# Dataset Classes +# ================================ + +class TrainDataset(Dataset): + """ + Training dataset with real/fake binary labels. + + Expected structure: + data_root/ + class1/ + 0_real/ + img1.png + img2.png + 1_fake/ + img1.png + img2.png + class2/ + 0_real/ + 1_fake/ + """ + + def __init__(self, root_dir, transform=None): + self.root_dir = Path(root_dir) + self.transform = transform + self.samples = [] + + print("="*70) + print("Scanning Training Dataset") + print("="*70) + + # Collect all class directories + class_dirs = sorted([d for d in self.root_dir.iterdir() if d.is_dir()]) + + for cls_dir in class_dirs: + cls_name = cls_dir.name + print(f"\nProcessing class: {cls_name}") + + # Real images (label=0) + real_dir = cls_dir / '0_real' + if real_dir.exists(): + real_files = list(real_dir.glob('*.png')) + \ + list(real_dir.glob('*.jpg')) + \ + list(real_dir.glob('*.JPEG')) + for img_path in real_files: + self.samples.append({ + 'path': str(img_path), + 'label': 0, + 'class': cls_name + }) + print(f" Found {len(real_files)} real images") + + # Fake images (label=1) + fake_dir = cls_dir / '1_fake' + if fake_dir.exists(): + fake_files = list(fake_dir.glob('*.png')) + \ + list(fake_dir.glob('*.jpg')) + \ + list(fake_dir.glob('*.JPEG')) + for img_path in fake_files: + self.samples.append({ + 'path': str(img_path), + 'label': 1, + 'class': cls_name + }) + print(f" Found {len(fake_files)} fake images") + + print(f"\n{'='*70}") + print(f"Total samples: {len(self.samples)}") + print(f" Real: {sum(1 for s in self.samples if s['label'] == 0)}") + print(f" Fake: {sum(1 for s in self.samples if s['label'] == 1)}") + print('='*70) + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + sample = self.samples[idx] + image = Image.open(sample['path']).convert('RGB') + + if self.transform: + image = self.transform(image) + + return image, sample['label'], sample['class'] + + +class ValDataset(Dataset): + """ + Validation dataset with category-based organization. + + Expected structure: + data_root/ + category1/ + 0_real/ + img1.png + 1_fake/ + img1.png + category2/ + 0_real/ + 1_fake/ + """ + + def __init__(self, root_dir, transform=None): + self.root_dir = Path(root_dir) + self.transform = transform + self.samples = [] + + print("="*70) + print("Scanning Validation Dataset") + print("="*70) + + # Collect all category directories + categories = sorted([d for d in self.root_dir.iterdir() if d.is_dir()]) + + for category_dir in categories: + category = category_dir.name + + # Real images + real_dir = category_dir / '0_real' + if real_dir.exists(): + for img_path in real_dir.glob('*.png'): + self.samples.append({ + 'path': str(img_path), + 'label': 0, + 'category': category + }) + + # Fake images + fake_dir = category_dir / '1_fake' + if fake_dir.exists(): + for img_path in fake_dir.glob('*.png'): + self.samples.append({ + 'path': str(img_path), + 'label': 1, + 'category': category + }) + + print(f"Found {len(self.samples)} images") + print(f" Real: {sum(1 for s in self.samples if s['label'] == 0)}") + print(f" Fake: {sum(1 for s in self.samples if s['label'] == 1)}") + print('='*70) + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + sample = self.samples[idx] + image = Image.open(sample['path']).convert('RGB') + + if self.transform: + image = self.transform(image) + + return image, sample['label'], sample.get('category', '') + + +# ================================ +# Pre-compute Functions +# ================================ + +def precompute_train_val_embeddings( + data_root, + save_path, + split='train', + patch_size=32, + batch_size=64 +): + """ + Pre-compute embeddings for training or validation set. + + Args: + data_root: Path to dataset root + save_path: Path to save embeddings (.pkl) + split: 'train' or 'val' + patch_size: Virtual patch size (e.g., 16, 32, 56) + batch_size: Batch size for processing + """ + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + # Load DINOv2 backbone + print("\nLoading DINOv2 ViT-L/14 backbone...") + backbone = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14') + backbone.to(device) + backbone.eval() + backbone.half() # Use FP16 for efficiency + print(f"Backbone loaded on {device}") + + # Data transform + transform = transforms.Compose([ + transforms.Resize((224, 224)), + transforms.ToTensor(), + transforms.Normalize( + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225] + ) + ]) + + # Load dataset + if split == 'train': + dataset = TrainDataset(data_root, transform=transform) + elif split == 'val': + dataset = ValDataset(data_root, transform=transform) + else: + raise ValueError(f"Unknown split: {split}") + + # DataLoader + loader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=False, + num_workers=8, + pin_memory=True, + persistent_workers=True + ) + + # Storage + all_embeddings = [] + all_labels = [] + all_metadata = [] + embed_dim = None + + print(f"\nExtracting embeddings for {split} set...") + print(f"Patch size: {patch_size}x{patch_size}") + print(f"Batch size: {batch_size}") + + start_time = time.time() + + with torch.no_grad(): + for batch_images, batch_labels, batch_meta in tqdm( + loader, + desc=f"Processing {split}" + ): + B = batch_images.size(0) + batch_images = batch_images.to(device, non_blocking=True).half() + + # Extract patch tokens + with torch.cuda.amp.autocast(dtype=torch.float16): + tokens = get_patch_tokens(backbone, batch_images) + + tokens = tokens.float() + + if embed_dim is None: + embed_dim = tokens.shape[-1] + + # Pool to desired patch size + pooled = pool_tokens_to_patch_size( + tokens, + patch_size=patch_size, + image_size=224 + ) + pooled_np = pooled.cpu().numpy() + + # Store per-image + for i in range(B): + all_embeddings.append(pooled_np[i]) # (K, D) + all_labels.append(int(batch_labels[i])) + all_metadata.append(batch_meta[i] if isinstance(batch_meta, list) else '') + + elapsed = time.time() - start_time + + # Save to disk + print(f"\nSaving embeddings to {save_path}...") + os.makedirs(os.path.dirname(save_path), exist_ok=True) + + data = { + 'embeddings': all_embeddings, + 'labels': all_labels, + 'metadata': all_metadata, + 'patch_size': patch_size, + 'split': split, + 'dataset_size': len(all_embeddings), + 'image_shape': (224, 224), + 'backbone': 'dinov2_vitl14', + 'embed_dim': embed_dim + } + + with open(save_path, 'wb') as f: + pickle.dump(data, f, protocol=4) + + # Print statistics + print(f"\n{'='*70}") + print(f"Embedding Extraction Complete ({split.upper()})") + print(f"{'='*70}") + print(f"Total images: {len(all_embeddings)}") + print(f"Total patches: {sum(emb.shape[0] for emb in all_embeddings)}") + print(f"Avg patches/image: {sum(emb.shape[0] for emb in all_embeddings) / len(all_embeddings):.1f}") + print(f"Embedding dimension: {embed_dim}") + print(f"Patch size: {patch_size}x{patch_size}") + print(f"Real samples: {sum(1 for l in all_labels if l == 0)}") + print(f"Fake samples: {sum(1 for l in all_labels if l == 1)}") + print(f"Time elapsed: {elapsed/60:.1f} min") + print(f"File size: {os.path.getsize(save_path) / (1024**2):.1f} MB") + print(f"Saved to: {save_path}") + print('='*70) + + +def precompute_ref_embeddings( + data_root, + save_path, + patch_size=32, + images_per_class=5, + seed=42 +): + """ + Pre-compute reference embeddings from ImageNet-style dataset. + Randomly selects N images per class. + + Args: + data_root: Path to ImageNet train folder + save_path: Path to save embeddings (.pkl) + patch_size: Virtual patch size (e.g., 16, 32, 56) + images_per_class: Number of images to select per class + seed: Random seed for reproducibility + """ + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + # Load backbone + print("\nLoading DINOv2 ViT-L/14 backbone...") + backbone = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14') + backbone.to(device) + backbone.eval() + backbone.half() + print(f"Backbone loaded on {device}") + + # Data transform + transform = transforms.Compose([ + transforms.Resize((224, 224)), + transforms.ToTensor(), + transforms.Normalize( + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225] + ) + ]) + + # Collect class directories + data_root = Path(data_root) + class_dirs = sorted([d for d in data_root.iterdir() if d.is_dir()]) + + if len(class_dirs) == 0: + raise RuntimeError(f"No class directories found in {data_root}") + + print(f"\n{'='*70}") + print("Reference Set Selection") + print(f"{'='*70}") + print(f"Found {len(class_dirs)} classes") + print(f"Selecting {images_per_class} image(s) per class") + print(f"Random seed: {seed}") + + # Select N images per class + random.seed(seed) + selected_images = [] + class_labels = [] + + for class_idx, class_dir in enumerate(tqdm(class_dirs, desc="Selecting images")): + images = list(class_dir.glob("*.png")) + \ + list(class_dir.glob("*.jpg")) + \ + list(class_dir.glob("*.JPEG")) + + if len(images) == 0: + continue + + n_select = min(images_per_class, len(images)) + selected = random.sample(images, n_select) + + selected_images.extend(selected) + class_labels.extend([class_idx] * n_select) + + print(f"Selected {len(selected_images)} images total") + print(f"Average per class: {len(selected_images) / len(class_dirs):.1f}") + + # Extract embeddings + all_embeddings = [] + image_paths = [] + image_class_labels = [] + embed_dim = None + + print("\nExtracting embeddings...") + with torch.no_grad(): + for img_idx, img_path in enumerate(tqdm(selected_images, desc="Processing")): + try: + image = Image.open(img_path).convert('RGB') + image = transform(image) + except Exception as e: + print(f"Error loading {img_path}: {e}") + continue + + image = image.unsqueeze(0).to(device).half() + + # Extract tokens + with torch.cuda.amp.autocast(dtype=torch.float16): + tokens = get_patch_tokens(backbone, image) + + tokens = tokens.float() + + if embed_dim is None: + embed_dim = tokens.shape[-1] + + # Pool to patch size + patch_embeddings = pool_tokens_to_patch_size( + tokens, + patch_size=patch_size, + image_size=224 + ) + + patch_embeddings = patch_embeddings.squeeze(0).cpu().numpy() + + all_embeddings.append(patch_embeddings) + image_paths.append(str(img_path)) + image_class_labels.append(class_labels[img_idx]) + + # Save to disk + print(f"\nSaving embeddings to {save_path}...") + os.makedirs(os.path.dirname(save_path), exist_ok=True) + + data = { + 'embeddings': all_embeddings, + 'labels': [0] * len(all_embeddings), # All real images + 'class_labels': image_class_labels, + 'patch_size': patch_size, + 'split': 'ref', + 'dataset_size': len(all_embeddings), + 'image_paths': image_paths, + 'image_shape': (224, 224), + 'backbone': 'dinov2_vitl14', + 'embed_dim': embed_dim, + 'num_classes': len(class_dirs), + 'images_per_class': images_per_class, + 'seed': seed + } + + with open(save_path, 'wb') as f: + pickle.dump(data, f, protocol=4) + + # Print statistics + print(f"\n{'='*70}") + print("Reference Embedding Extraction Complete") + print(f"{'='*70}") + print(f"Total images: {len(all_embeddings)}") + print(f"Number of classes: {len(class_dirs)}") + print(f"Images per class: {images_per_class}") + print(f"Total patches: {sum(emb.shape[0] for emb in all_embeddings)}") + print(f"Avg patches/image: {sum(emb.shape[0] for emb in all_embeddings) / len(all_embeddings):.1f}") + print(f"Embedding dimension: {embed_dim}") + print(f"Patch size: {patch_size}x{patch_size}") + print(f"File size: {os.path.getsize(save_path) / (1024**2):.1f} MB") + print(f"Random seed: {seed}") + print(f"Saved to: {save_path}") + print('='*70) + + +# ================================ +# Main +# ================================ + +def main(): + parser = argparse.ArgumentParser( + description='Pre-compute DINOv2 patch embeddings', + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=__doc__ + ) + + # Required arguments + parser.add_argument( + '--split', + type=str, + required=True, + choices=['train', 'val', 'ref'], + help='Dataset split to process' + ) + parser.add_argument( + '--data_root', + type=str, + required=True, + help='Path to dataset root directory' + ) + parser.add_argument( + '--save_path', + type=str, + required=True, + help='Path to save embeddings (.pkl file)' + ) + + # Optional parameters + parser.add_argument( + '--patch_size', + type=int, + default=32, + help='Virtual patch size (default: 32)' + ) + parser.add_argument( + '--batch_size', + type=int, + default=64, + help='Batch size for train/val (default: 64)' + ) + parser.add_argument( + '--images_per_class', + type=int, + default=5, + help='Images per class for ref split (default: 5)' + ) + parser.add_argument( + '--seed', + type=int, + default=42, + help='Random seed for ref split (default: 42)' + ) + + args = parser.parse_args() + + print("="*70) + print("DINOv2 Patch Embedding Pre-computation") + print("="*70) + print(f"Split: {args.split}") + print(f"Data root: {args.data_root}") + print(f"Save path: {args.save_path}") + print(f"Patch size: {args.patch_size}") + + if args.split in ['train', 'val']: + print(f"Batch size: {args.batch_size}") + precompute_train_val_embeddings( + data_root=args.data_root, + save_path=args.save_path, + split=args.split, + patch_size=args.patch_size, + batch_size=args.batch_size + ) + + elif args.split == 'ref': + print(f"Images per class: {args.images_per_class}") + print(f"Random seed: {args.seed}") + precompute_ref_embeddings( + data_root=args.data_root, + save_path=args.save_path, + patch_size=args.patch_size, + images_per_class=args.images_per_class, + seed=args.seed + ) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/detectors/MDMF/upstream/src/test_MDMF.py b/detectors/MDMF/upstream/src/test_MDMF.py new file mode 100644 index 0000000000000000000000000000000000000000..67e87fe835e34dead25df3ff914151d819ad2144 --- /dev/null +++ b/detectors/MDMF/upstream/src/test_MDMF.py @@ -0,0 +1,632 @@ +""" +Test trained MDMF detector on test datasets. + +This script evaluates a trained MDMF detector using standard MMDยฒ scoring between +test samples and reference distribution. +""" + +import os +import json +import argparse +from pathlib import Path +from datetime import datetime + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils.data import DataLoader +from torchvision import transforms, datasets +from tqdm import tqdm +import pickle +import math +import matplotlib.pyplot as plt +from sklearn import metrics + + +# ================================ +# Model Definition +# ================================ + +class MMD_MIL_Detector(nn.Module): + """MMD-based Multiple Instance Learning detector.""" + + def __init__(self, embed_dim=1024, hidden_dim=256, dropout=0.3, init_sigma=1.0): + super().__init__() + self.embed_dim = embed_dim + + self.log_sigma = nn.Parameter( + torch.log(torch.tensor([init_sigma])), + requires_grad=True + ) + + self.score_head = nn.Sequential( + nn.Linear(embed_dim, hidden_dim), + nn.ReLU(), + nn.Dropout(dropout), + nn.Linear(hidden_dim, hidden_dim // 2), + nn.ReLU(), + nn.Dropout(dropout), + nn.Linear(hidden_dim // 2, 1), + nn.Tanh() + ) + + def get_sigma(self): + return torch.exp(self.log_sigma.clamp(min=-3.0, max=3.0)) + + def compute_logits(self, embeddings, mask=None): + B, K, D = embeddings.shape + embeddings = F.normalize(embeddings, p=2, dim=-1) + flat = embeddings.view(B * K, D) + logits = self.score_head(flat).view(B, K) + + if mask is not None: + logits = logits.masked_fill(~mask, 0.0) + + return logits + + +# ================================ +# DINOv2 Helper Functions +# ================================ + +def get_patch_tokens(backbone, x): + """Extract patch tokens from DINOv2 backbone.""" + if hasattr(backbone, "forward_features"): + out = backbone.forward_features(x) + else: + out = backbone(x) + + if isinstance(out, dict): + tokens = None + for key in ["x_norm_patchtokens", "patch_tokens", "tokens"]: + if key in out: + tokens = out[key] + break + + if tokens is None: + for key in ["x_norm", "x"]: + if key in out: + t = out[key] + if t.dim() == 3 and t.size(1) > 1: + tokens = t[:, 1:, :] + break + + if tokens is None: + raise RuntimeError(f"Cannot find patch tokens in output") + else: + if isinstance(out, (list, tuple)): + out = out[0] + + if not torch.is_tensor(out): + raise RuntimeError(f"Unsupported backbone output type: {type(out)}") + + if out.dim() == 3 and out.size(1) > 1: + tokens = out[:, 1:, :] + else: + raise RuntimeError(f"Cannot interpret output shape {out.shape}") + + return tokens + + +def pool_tokens_to_patch_size(tokens, patch_size, image_size=224): + """Pool token grid to match patch size.""" + B, N, D = tokens.shape + H_t = int(math.sqrt(N)) + if H_t * H_t != N: + raise ValueError(f"Token count {N} is not a perfect square") + + tokens_spatial = tokens.view(B, H_t, H_t, D) + grid_size = image_size // patch_size + if grid_size < 1: + raise ValueError(f"Patch size {patch_size} too large for image size {image_size}") + + tokens_spatial_ch = tokens_spatial.permute(0, 3, 1, 2) + pooled = F.adaptive_avg_pool2d(tokens_spatial_ch, output_size=(grid_size, grid_size)) + pooled = pooled.permute(0, 2, 3, 1).contiguous() + pooled = pooled.view(B, grid_size * grid_size, D) + + return pooled + + +@torch.no_grad() +def extract_patch_logits_batch(images, backbone, model, patch_size): + """ + Extract patch embeddings and compute logits for batch of images. + + Args: + images: [B, C, H, W] on GPU + backbone: DINOv2 backbone + model: MMD-MIL detector + patch_size: Virtual patch size + + Returns: + patch_logits: [B, K] patch logits + """ + with torch.cuda.amp.autocast(dtype=torch.float16, enabled=(images.dtype == torch.float16)): + tokens = get_patch_tokens(backbone, images) + + tokens = tokens.float() + patch_embeddings = pool_tokens_to_patch_size(tokens, patch_size=patch_size, image_size=224) + patch_logits = model.compute_logits(patch_embeddings) + + return patch_logits + + +# ================================ +# MMDยฒ Scoring Functions +# ================================ + +@torch.no_grad() +def precompute_ref_stats(ref_X, sigma, epsilon=1e-8): + """ + Precompute reference statistics for MMDยฒ scoring. + + Args: + ref_X: [n, d] reference samples (on GPU) + sigma: Kernel bandwidth (on GPU) + + Returns: + xx_mean: Mean of K(x, x') for reference + ref_norm2: [n, 1] squared norms + """ + n = ref_X.shape[0] + sigma = sigma + epsilon + + ref_norm2 = (ref_X ** 2).sum(dim=1, keepdim=True) + + # Compute reference kernel matrix + XX = ref_norm2 + distances = XX + XX.t() - 2.0 * (ref_X @ ref_X.t()) + Kxx = torch.exp(-distances / (2.0 * sigma**2)) + + # Biased estimator (includes diagonal) + xx_mean = Kxx.mean() + + return xx_mean, ref_norm2 + + +@torch.no_grad() +def score_mmd2_batch(ref_X, ref_norm2, xx_mean, Y, sigma, epsilon=1e-8): + """ + Compute MMDยฒ scores for batch of test samples. + + MMDยฒ(ref, {y}) = E[k(x,x')] + k(y,y) - 2*E[k(x,y)] + = xx_mean + 1 - 2*mean(k(x,y)) + + Args: + ref_X: [n, d] reference samples (on GPU) + ref_norm2: [n, 1] reference squared norms (on GPU) + xx_mean: Scalar, mean of reference kernel + Y: [B, d] batch of test samples (on GPU) + sigma: Kernel bandwidth (on GPU) + + Returns: + scores: [B] MMDยฒ scores (higher = more likely fake) + """ + sigma = sigma + epsilon + + # Compute distances from test to reference + Y_norm2 = (Y ** 2).sum(dim=1, keepdim=True) # [B, 1] + distances = ref_norm2 + Y_norm2.t() - 2.0 * (ref_X @ Y.t()) # [n, B] + + # Compute kernel values + kxy = torch.exp(-distances / (2.0 * sigma**2)) # [n, B] + + # Mean similarity for each test sample + mean_kxy = kxy.mean(dim=0) # [B] + + # MMDยฒ = xx_mean + 1 - 2*mean_kxy + mmd2_scores = xx_mean + 1.0 - 2.0 * mean_kxy + + return mmd2_scores + + +# ================================ +# Load Reference Logits +# ================================ + +@torch.no_grad() +def load_reference_logits(ref_embeddings_path, model, device): + """ + Load reference patch logits from pre-computed embeddings. + + Args: + ref_embeddings_path: Path to reference embeddings (.pkl) + model: MMD-MIL detector + device: torch.device + + Returns: + ref_logits: [N, K] reference logits (on GPU) + """ + print("\n" + "="*70) + print("Loading Reference Logits") + print("="*70) + + with open(ref_embeddings_path, 'rb') as f: + data = pickle.load(f) + + ref_embeddings = data['embeddings'] + ref_labels = data['labels'] + + print(f"Reference dataset size: {len(ref_embeddings)} images") + print(f"Patch size: {data['patch_size']}x{data['patch_size']}") + + # Only use real images (label=0) + real_indices = [i for i, l in enumerate(ref_labels) if l == 0] + ref_embeddings = [ref_embeddings[i] for i in real_indices] + + print(f"Using {len(ref_embeddings)} real images as reference") + + all_logits = [] + + for emb in tqdm(ref_embeddings, desc="Computing reference logits"): + emb_tensor = torch.from_numpy(emb).float().unsqueeze(0).to(device) + patch_logits = model.compute_logits(emb_tensor) + all_logits.append(patch_logits.squeeze(0)) + + ref_logits = torch.stack(all_logits, dim=0) + print(f"Reference logits shape: {ref_logits.shape}") + print("="*70 + "\n") + + return ref_logits + + +# ================================ +# Metrics and Plotting +# ================================ + +def calculate_metrics_and_plot(real_scores, fake_scores, dataset_name, output_dir): + """Calculate metrics and generate plots.""" + + all_scores = np.concatenate([real_scores, fake_scores]) + labels = np.concatenate([np.zeros(len(real_scores)), np.ones(len(fake_scores))]) + + # Calculate metrics + fpr, tpr, _ = metrics.roc_curve(labels, all_scores) + auroc = metrics.auc(fpr, tpr) + + tpr_threshold = 0.95 + valid_indices = tpr >= tpr_threshold + fpr95 = fpr[valid_indices].min() if np.any(valid_indices) else 1.0 + + ap = metrics.average_precision_score(labels, all_scores) + + # Print metrics + print(f"\n{'='*70}") + print(f"Dataset: {dataset_name}") + print(f"{'='*70}") + print(f" Samples: Real={len(real_scores)}, Fake={len(fake_scores)}") + print(f" AUROC: {auroc:.4f}") + print(f" FPR @ 95% TPR: {fpr95:.4f}") + print(f" Average Precision: {ap:.4f}") + print(f"\n Real - Score: {real_scores.mean():.6f} ยฑ {real_scores.std():.6f}") + print(f" Fake - Score: {fake_scores.mean():.6f} ยฑ {fake_scores.std():.6f}") + print(f" Separation: {fake_scores.mean() - real_scores.mean():.6f}") + print(f"{'='*70}\n") + + # Plot + fig, axes = plt.subplots(2, 2, figsize=(14, 10)) + + # Score distribution + axes[0, 0].hist(real_scores, bins=50, alpha=0.7, density=True, + color='#5B9BD5', label='Real', edgecolor='black', linewidth=0.5) + axes[0, 0].hist(fake_scores, bins=50, alpha=0.7, density=True, + color='#A5665F', label='Fake', edgecolor='black', linewidth=0.5) + axes[0, 0].set_xlabel('MMDยฒ Score', fontsize=12, fontweight='bold') + axes[0, 0].set_ylabel('Density', fontsize=12, fontweight='bold') + axes[0, 0].set_title(f'Score Distribution: {dataset_name}', fontsize=14, fontweight='bold') + axes[0, 0].legend(fontsize=10) + axes[0, 0].grid(True, alpha=0.3) + + # Log-scale distribution + axes[0, 1].hist(real_scores, bins=50, alpha=0.7, density=True, + color='#5B9BD5', label='Real', edgecolor='black', linewidth=0.5) + axes[0, 1].hist(fake_scores, bins=50, alpha=0.7, density=True, + color='#A5665F', label='Fake', edgecolor='black', linewidth=0.5) + axes[0, 1].set_xlabel('MMDยฒ Score', fontsize=12, fontweight='bold') + axes[0, 1].set_ylabel('Density (Log Scale)', fontsize=12, fontweight='bold') + axes[0, 1].set_title(f'Score Distribution (Log): {dataset_name}', fontsize=14, fontweight='bold') + axes[0, 1].set_yscale('log') + axes[0, 1].legend(fontsize=10) + axes[0, 1].grid(True, alpha=0.3) + + # ROC curve + axes[1, 0].plot(fpr, tpr, linewidth=2, color='#2E86AB', label=f'AUROC = {auroc:.4f}') + axes[1, 0].plot([0, 1], [0, 1], 'k--', linewidth=1, label='Random') + axes[1, 0].scatter([fpr95], [0.95], color='red', s=100, zorder=5, + label=f'FPR@95%TPR = {fpr95:.4f}') + axes[1, 0].set_xlabel('False Positive Rate', fontsize=12, fontweight='bold') + axes[1, 0].set_ylabel('True Positive Rate', fontsize=12, fontweight='bold') + axes[1, 0].set_title(f'ROC Curve: {dataset_name}', fontsize=14, fontweight='bold') + axes[1, 0].legend(fontsize=10) + axes[1, 0].grid(True, alpha=0.3) + + # PR curve + precision, recall, _ = metrics.precision_recall_curve(labels, all_scores) + axes[1, 1].plot(recall, precision, linewidth=2, color='#A23B72', label=f'AP = {ap:.4f}') + axes[1, 1].set_xlabel('Recall', fontsize=12, fontweight='bold') + axes[1, 1].set_ylabel('Precision', fontsize=12, fontweight='bold') + axes[1, 1].set_title(f'Precision-Recall Curve: {dataset_name}', fontsize=14, fontweight='bold') + axes[1, 1].legend(fontsize=10) + axes[1, 1].grid(True, alpha=0.3) + + plt.tight_layout() + + plot_path = os.path.join(output_dir, f'{dataset_name}_analysis.png') + plt.savefig(plot_path, dpi=300, bbox_inches='tight') + plt.close() + + return { + 'dataset': dataset_name, + 'num_real': int(len(real_scores)), + 'num_fake': int(len(fake_scores)), + 'auroc': float(auroc), + 'fpr_at_95_tpr': float(fpr95), + 'ap': float(ap), + 'real_score_mean': float(real_scores.mean()), + 'real_score_std': float(real_scores.std()), + 'fake_score_mean': float(fake_scores.mean()), + 'fake_score_std': float(fake_scores.std()), + 'score_difference': float(fake_scores.mean() - real_scores.mean()) + } + + +# ================================ +# Main Testing Function +# ================================ + +def test_detector(model_path, ref_embeddings_path, test_real_dir, test_fake_dirs, + output_dir, batch_size=256): + """ + Test trained MMD-MIL detector. + + Args: + model_path: Path to trained model checkpoint + ref_embeddings_path: Path to reference embeddings + test_real_dir: Path to real test images + test_fake_dirs: List of paths to fake test images + output_dir: Output directory for results + batch_size: Batch size for processing + """ + + # Create output directory + os.makedirs(output_dir, exist_ok=True) + plots_dir = os.path.join(output_dir, 'plots') + os.makedirs(plots_dir, exist_ok=True) + + # Setup device + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + print(f"Using device: {device}") + + # Load model + print(f"\nLoading model from {model_path}...") + checkpoint = torch.load(model_path, map_location=device) + config = checkpoint['config'] + patch_size = config.get('patch_size', 32) + + print(f"Model trained at epoch {checkpoint['epoch']}") + print(f"Training AUROC: {checkpoint['auroc']:.4f}") + + model = MMD_MIL_Detector( + embed_dim=config['embed_dim'], + hidden_dim=config['hidden_dim'], + dropout=config['dropout'], + init_sigma=config['init_sigma'] + ).to(device) + + model.load_state_dict(checkpoint['model_state_dict']) + model.eval() + + sigma = model.get_sigma() + print(f"Learned kernel bandwidth (sigma): {sigma.item():.6f}") + + # Load DINOv2 backbone + print("\nLoading DINOv2 backbone...") + backbone = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14').to(device) + backbone.eval() + backbone.half() + + # Load reference logits + ref_logits = load_reference_logits(ref_embeddings_path, model, device) + + # Precompute reference statistics + print("Precomputing reference statistics...") + xx_mean, ref_norm2 = precompute_ref_stats(ref_logits, sigma) + print(f"Reference kernel mean: {xx_mean.item():.6f}") + + # Data transform + transform = transforms.Compose([ + transforms.Resize((224, 224)), + transforms.ToTensor(), + transforms.Normalize(mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]) + ]) + + print("\n" + "="*70) + print("Starting Evaluation") + print(f"Batch size: {batch_size}") + print(f"Patch size: {patch_size}x{patch_size}") + print(f"Scoring: MMDยฒ (standard)") + print("="*70) + + # Process real images + print(f"\nProcessing real images from {test_real_dir}") + real_dataset = datasets.ImageFolder(root=test_real_dir, transform=transform) + real_loader = DataLoader(real_dataset, batch_size=batch_size, shuffle=False, + num_workers=4, pin_memory=True) + + real_scores_list = [] + + for images, _ in tqdm(real_loader, desc="Testing real"): + images = images.to(device, non_blocking=True).half() + test_logits = extract_patch_logits_batch(images, backbone, model, patch_size) + batch_scores = score_mmd2_batch(ref_logits, ref_norm2, xx_mean, test_logits, sigma) + real_scores_list.append(batch_scores.cpu()) + + real_scores = torch.cat(real_scores_list).numpy() + + print(f"Real images: {len(real_scores)}") + print(f" Score: {real_scores.mean():.6f} ยฑ {real_scores.std():.6f}") + + # Process fake datasets + all_results = [] + scores_dict = {'real': real_scores} + + for fake_dir in test_fake_dirs: + dataset_name = Path(fake_dir).name + print(f"\nProcessing fake dataset: {dataset_name}") + + fake_dataset = datasets.ImageFolder(root=fake_dir, transform=transform) + fake_loader = DataLoader(fake_dataset, batch_size=batch_size, shuffle=False, + num_workers=4, pin_memory=True) + + fake_scores_list = [] + + for images, _ in tqdm(fake_loader, desc=f"Testing {dataset_name}"): + images = images.to(device, non_blocking=True).half() + test_logits = extract_patch_logits_batch(images, backbone, model, patch_size) + batch_scores = score_mmd2_batch(ref_logits, ref_norm2, xx_mean, test_logits, sigma) + fake_scores_list.append(batch_scores.cpu()) + + fake_scores = torch.cat(fake_scores_list).numpy() + scores_dict[dataset_name] = fake_scores + + print(f"Fake images: {len(fake_scores)}") + print(f" Score: {fake_scores.mean():.6f} ยฑ {fake_scores.std():.6f}") + + # Calculate metrics + result = calculate_metrics_and_plot(real_scores, fake_scores, dataset_name, plots_dir) + all_results.append(result) + + # Calculate averages + print("\n" + "="*70) + print("OVERALL SUMMARY") + print("="*70) + + avg_auroc = np.mean([r['auroc'] for r in all_results]) + avg_fpr95 = np.mean([r['fpr_at_95_tpr'] for r in all_results]) + avg_ap = np.mean([r['ap'] for r in all_results]) + + print(f"\nAverage metrics across {len(all_results)} fake datasets:") + print(f" AUROC: {avg_auroc:.4f}") + print(f" FPR @ 95% TPR: {avg_fpr95:.4f}") + print(f" Average Precision: {avg_ap:.4f}") + print("="*70) + + # Save results + summary = { + 'model_path': model_path, + 'checkpoint_epoch': checkpoint['epoch'], + 'training_auroc': checkpoint['auroc'], + 'learned_sigma': float(sigma.item()), + 'patch_size': patch_size, + 'batch_size': batch_size, + 'num_ref_samples': int(ref_logits.shape[0]), + 'scoring_method': 'MMDยฒ (standard)', + 'average_metrics': { + 'auroc': float(avg_auroc), + 'fpr_at_95_tpr': float(avg_fpr95), + 'ap': float(avg_ap) + }, + 'per_dataset_results': all_results, + 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S') + } + + results_path = os.path.join(output_dir, 'test_results.json') + with open(results_path, 'w') as f: + json.dump(summary, f, indent=4) + print(f"\nResults saved to {results_path}") + + pickle_path = os.path.join(output_dir, 'test_scores.pkl') + with open(pickle_path, 'wb') as f: + pickle.dump(scores_dict, f) + print(f"Scores saved to {pickle_path}") + + return scores_dict, summary + + +# ================================ +# Main +# ================================ + +def main(): + parser = argparse.ArgumentParser( + description='Test MMD-MIL detector', + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=__doc__ + ) + + parser.add_argument( + '--model', + type=str, + required=True, + help='Path to trained model checkpoint (.pth)' + ) + parser.add_argument( + '--ref_embeddings', + type=str, + required=True, + help='Path to reference embeddings (.pkl)' + ) + parser.add_argument( + '--test_real', + type=str, + required=True, + help='Path to real test images directory' + ) + parser.add_argument( + '--test_fake', + type=str, + nargs='+', + required=True, + help='Paths to fake test images directories' + ) + parser.add_argument( + '--output_dir', + type=str, + required=True, + help='Output directory for results' + ) + parser.add_argument( + '--batch_size', + type=int, + default=256, + help='Batch size for processing (default: 256)' + ) + + args = parser.parse_args() + + print("="*70) + print("MMD-MIL Detector Testing") + print("="*70) + print(f"Model: {args.model}") + print(f"Reference: {args.ref_embeddings}") + print(f"Real test: {args.test_real}") + print(f"Fake test: {len(args.test_fake)} datasets") + for fake_dir in args.test_fake: + print(f" - {fake_dir}") + print(f"Output: {args.output_dir}") + print(f"Batch size: {args.batch_size}") + print("="*70) + + scores_dict, summary = test_detector( + model_path=args.model, + ref_embeddings_path=args.ref_embeddings, + test_real_dir=args.test_real, + test_fake_dirs=args.test_fake, + output_dir=args.output_dir, + batch_size=args.batch_size + ) + + print("\n" + "="*70) + print("TESTING COMPLETE!") + print(f"Average AUROC: {summary['average_metrics']['auroc']:.4f}") + print(f"Average FPR95: {summary['average_metrics']['fpr_at_95_tpr']:.4f}") + print(f"Average AP: {summary['average_metrics']['ap']:.4f}") + print(f"Results saved to {args.output_dir}") + print("="*70) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/detectors/MDMF/upstream/src/train_MDMF.py b/detectors/MDMF/upstream/src/train_MDMF.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bf3b71b889d5ce817ea5597ee9142f2873550c --- /dev/null +++ b/detectors/MDMF/upstream/src/train_MDMF.py @@ -0,0 +1,754 @@ +""" +Train MDMF detector for AIGC detection. + +This script trains a MDMF detector to distinguish between real and AI-generated images at the patch level. +""" + +import os +import json +import argparse +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import Dataset, DataLoader +from torch import nn +import torch.nn.functional as F +from torch.optim import AdamW +from torch.optim.lr_scheduler import CosineAnnealingLR +from tqdm import tqdm +import pickle +from sklearn import metrics + + +# ================================ +# Dataset +# ================================ + +class PrecomputedEmbeddingDataset(Dataset): + """Dataset that loads pre-computed patch embeddings.""" + + def __init__(self, embeddings_path, label=None): + """ + Args: + embeddings_path: Path to pre-computed embeddings (.pkl file) + label: Optional label filter (0=real, 1=fake, None=all) + """ + print(f"Loading embeddings from {embeddings_path}...") + with open(embeddings_path, 'rb') as f: + data = pickle.load(f) + + all_embeddings = data['embeddings'] # List of (K, D) arrays + all_labels = data['labels'] + self.patch_size = data['patch_size'] + + if label is not None: + # Filter by label + indices = [i for i, l in enumerate(all_labels) if l == label] + self.embeddings = [all_embeddings[i] for i in indices] + self.labels = [all_labels[i] for i in indices] + label_name = "Real" if label == 0 else "Fake" + print(f"[{label_name}] Loaded {len(self.embeddings)} images") + else: + self.embeddings = all_embeddings + self.labels = all_labels + print(f"Loaded {len(self.embeddings)} images") + + print(f"Patch size: {self.patch_size}x{self.patch_size}") + real_count = sum(1 for l in self.labels if l == 0) + fake_count = sum(1 for l in self.labels if l == 1) + print(f"Distribution: Real={real_count}, Fake={fake_count}") + + def __len__(self): + return len(self.embeddings) + + def __getitem__(self, idx): + embeddings = torch.from_numpy(self.embeddings[idx]).float() # (K, D) + label = self.labels[idx] + return embeddings, label + + +def collate_fn(batch): + """ + Custom collate function to handle variable-length patch sequences. + + Args: + batch: List of (embeddings, label) tuples + + Returns: + padded_embeddings: [B, K_max, D] padded tensor + labels: [B] label tensor + mask: [B, K_max] boolean mask (True for valid patches) + """ + embeddings, labels = zip(*batch) + max_patches = max(emb.shape[0] for emb in embeddings) + B = len(embeddings) + D = embeddings[0].shape[1] + + padded_embeddings = torch.zeros(B, max_patches, D) + mask = torch.zeros(B, max_patches, dtype=torch.bool) + + for i, emb in enumerate(embeddings): + K = emb.shape[0] + padded_embeddings[i, :K] = emb + mask[i, :K] = True + + labels = torch.tensor(labels, dtype=torch.long) + return padded_embeddings, labels, mask + + +# ================================ +# Kernel and MMD Functions +# ================================ + +def rbf_kernel(X, Y, sigma): + """ + Compute RBF (Gaussian) kernel matrix between X and Y. + + K(x, y) = exp(-||x - y||^2 / (2 * sigma^2)) + + Args: + X: [n, d] tensor + Y: [m, d] tensor + sigma: kernel bandwidth + + Returns: + K: [n, m] kernel matrix + """ + XX = torch.sum(X ** 2, dim=1, keepdim=True) # [n, 1] + YY = torch.sum(Y ** 2, dim=1, keepdim=True) # [m, 1] + distances = XX + YY.t() - 2 * (X @ Y.t()) # [n, m] + return torch.exp(-distances / (2 * sigma ** 2)) + + +def mmd_squared(X, Y, sigma, epsilon=1e-8): + """ + Compute unbiased MMD^2 estimate between two samples. + + MMD^2 = E[k(x,x')] - 2*E[k(x,y)] + E[k(y,y')] + + Uses unbiased estimators (excludes diagonal terms). + + Args: + X: [n, d] real sample + Y: [m, d] fake sample + sigma: kernel bandwidth + epsilon: numerical stability constant + + Returns: + mmd2: Scalar MMD^2 value + """ + n = X.shape[0] + m = Y.shape[0] + assert X.shape[1] == Y.shape[1], f"Dimension mismatch: X={X.shape[1]}, Y={Y.shape[1]}" + + sigma = sigma + epsilon + + # Compute kernel matrices + Kxx = rbf_kernel(X, X, sigma) + Kyy = rbf_kernel(Y, Y, sigma) + Kxy = rbf_kernel(X, Y, sigma) + + # Unbiased estimators (exclude diagonal) + if n > 1: + xx = (torch.sum(Kxx) - torch.sum(torch.diag(Kxx))) / (n * (n - 1)) + else: + xx = torch.tensor(0.0, device=X.device) + + if m > 1: + yy = (torch.sum(Kyy) - torch.sum(torch.diag(Kyy))) / (m * (m - 1)) + else: + yy = torch.tensor(0.0, device=Y.device) + + xy = torch.sum(Kxy) / (n * m) + + return xx + yy - 2.0 * xy + + +# ================================ +# Model +# ================================ + +class MMD_MIL_Detector(nn.Module): + """ + MMD-based Multiple Instance Learning detector. + + Architecture: + 1. MLP head: maps patch embeddings to scalar logits + 2. Learnable kernel bandwidth (sigma) + 3. Training objective: maximize MMD^2 between real/fake distributions + """ + + def __init__(self, embed_dim=1024, hidden_dim=256, dropout=0.3, init_sigma=1.0): + """ + Args: + embed_dim: Input embedding dimension (e.g., 1024 for DINOv2-L) + hidden_dim: Hidden layer dimension + dropout: Dropout rate + init_sigma: Initial kernel bandwidth + """ + super().__init__() + self.embed_dim = embed_dim + + # Learnable kernel bandwidth (log-parameterized) + self.log_sigma = nn.Parameter( + torch.log(torch.tensor([init_sigma])), + requires_grad=True + ) + + # MLP head: embedding -> logit + self.score_head = nn.Sequential( + nn.Linear(embed_dim, hidden_dim), + nn.ReLU(), + nn.Dropout(dropout), + nn.Linear(hidden_dim, hidden_dim // 2), + nn.ReLU(), + nn.Dropout(dropout), + nn.Linear(hidden_dim // 2, 1), + nn.Tanh() # Bounded output in [-1, 1] + ) + + print(f"Initialized MMD-MIL Detector:") + print(f" Embed dim: {embed_dim}") + print(f" Hidden dim: {hidden_dim}") + print(f" Dropout: {dropout}") + print(f" Initial sigma: {init_sigma}") + + def get_sigma(self): + """Get current kernel bandwidth with range constraint.""" + # Constrain sigma to [exp(-3), exp(3)] โ‰ˆ [0.05, 20] + return torch.exp(self.log_sigma.clamp(min=-3.0, max=3.0)) + + def compute_logits(self, embeddings, mask=None): + """ + Compute patch-level logits. + + Args: + embeddings: [B, K, D] patch embeddings + mask: [B, K] boolean mask for valid patches + + Returns: + logits: [B, K] patch logits + """ + B, K, D = embeddings.shape + + # L2 normalize embeddings + embeddings = F.normalize(embeddings, p=2, dim=-1) + + # Flatten and pass through MLP + flat = embeddings.view(B * K, D) + logits = self.score_head(flat).view(B, K) + + # Mask out invalid patches + if mask is not None: + logits = logits.masked_fill(~mask, 0.0) + + return logits + + def forward(self, real_embeddings, fake_embeddings, real_mask=None, fake_mask=None): + """ + Forward pass for training. + + Args: + real_embeddings: [B, K, D] real image embeddings + fake_embeddings: [B, K, D] fake image embeddings + real_mask: [B, K] mask for real patches + fake_mask: [B, K] mask for fake patches + + Returns: + loss: Training loss (-MMD^2) + mmd2: MMD^2 value + sigma: Current kernel bandwidth + """ + # Compute logits for both distributions + real_logits = self.compute_logits(real_embeddings, real_mask) # [B, K] + fake_logits = self.compute_logits(fake_embeddings, fake_mask) # [B, K] + + # Flatten to get distributions + X = real_logits.view(-1, 1) # [B*K, 1] - treat each patch as sample + Y = fake_logits.view(-1, 1) # [B*K, 1] + + sigma = self.get_sigma() + + # Compute MMD^2 + mmd2 = mmd_squared(X, Y, sigma) + + # Loss: maximize MMD^2 => minimize -MMD^2 + loss = -mmd2 + + return loss, mmd2, sigma + + +# ================================ +# Training Functions +# ================================ + +def train_epoch(model, train_loaders, optimizer, device, epoch): + """ + Train for one epoch. + + Args: + model: MMD-MIL detector + train_loaders: Dict with 'real' and 'fake' DataLoaders + optimizer: Optimizer + device: torch.device + epoch: Current epoch number + + Returns: + avg_loss: Average loss + avg_mmd: Average MMD^2 + """ + model.train() + + real_loader = train_loaders["real"] + fake_loader = train_loaders["fake"] + + total_loss = 0.0 + total_mmd = 0.0 + num_batches = 0 + + pbar = tqdm( + zip(real_loader, fake_loader), + desc=f"Epoch {epoch}", + total=min(len(real_loader), len(fake_loader)) + ) + + for (real_emb, _, real_mask), (fake_emb, _, fake_mask) in pbar: + # Skip if batch sizes don't match + if real_emb.shape[0] != fake_emb.shape[0]: + continue + + # Move to device + real_emb = real_emb.to(device) + fake_emb = fake_emb.to(device) + real_mask = real_mask.to(device) + fake_mask = fake_mask.to(device) + + # Forward pass + optimizer.zero_grad() + loss, mmd2, sigma = model(real_emb, fake_emb, real_mask, fake_mask) + + # Backward pass + loss.backward() + optimizer.step() + + # Accumulate stats + total_loss += loss.item() + total_mmd += mmd2.item() + num_batches += 1 + + # Update progress bar + pbar.set_postfix({ + "loss": f"{loss.item():.4f}", + "mmd2": f"{mmd2.item():.6f}", + "sigma": f"{sigma.item():.4f}" + }) + + avg_loss = total_loss / max(1, num_batches) + avg_mmd = total_mmd / max(1, num_batches) + + return avg_loss, avg_mmd + + +# ================================ +# Validation Functions +# ================================ + +@torch.no_grad() +def extract_ref_logits(model, ref_loader, device): + """ + Extract logits for reference set (all real images). + + Args: + model: MMD-MIL detector + ref_loader: Reference set DataLoader + device: torch.device + + Returns: + ref_logits: [N, K] tensor of reference logits + """ + model.eval() + all_logits = [] + + for embeddings, _, mask in tqdm(ref_loader, desc="Extracting ref logits"): + embeddings = embeddings.to(device) + mask = mask.to(device) + logits = model.compute_logits(embeddings, mask) + all_logits.append(logits.cpu()) + + return torch.cat(all_logits, dim=0) # [N, K] + + +@torch.no_grad() +def precompute_ref_stats(ref_logits, sigma, epsilon=1e-8): + """ + Precompute reference statistics for fast scoring. + + Args: + ref_logits: [N, K] reference logits + sigma: Kernel bandwidth + epsilon: Numerical stability + + Returns: + xx_mean: Mean of K(x, x') for reference + ref_norm2: [N, K] squared norms for distance computation + """ + sigma = sigma + epsilon + N, K = ref_logits.shape + + # Compute squared norms + ref_norm2 = (ref_logits ** 2).sum(dim=1, keepdim=True) # [N, 1] + + # Compute reference kernel matrix + XX = ref_norm2 + distances = XX + XX.t() - 2.0 * (ref_logits @ ref_logits.t()) + Kxx = torch.exp(-distances / (2.0 * sigma ** 2)) + + # Mean kernel value (biased estimator, includes diagonal) + xx_mean = Kxx.mean() + + return xx_mean, ref_norm2 + + +@torch.no_grad() +def score_sample(test_logit, ref_logits, ref_norm2, xx_mean, sigma, epsilon=1e-8): + """ + Score a single test sample using MMD^2(ref, {test}). + + For a single sample y: + MMD^2(ref, {y}) = E[k(x,x')] + k(y,y) - 2*E[k(x,y)] + = xx_mean + 1 - 2*mean(k(x,y)) + + Args: + test_logit: [1, K] test sample logits + ref_logits: [N, K] reference logits + ref_norm2: [N, 1] reference squared norms + xx_mean: Scalar, mean of reference kernel + sigma: Kernel bandwidth + epsilon: Numerical stability + + Returns: + score: Scalar MMD^2 score (higher = more likely fake) + """ + sigma = sigma + epsilon + + # Compute distances from test to all reference samples + y_norm2 = (test_logit ** 2).sum(dim=1, keepdim=True) # [1, 1] + distances = ref_norm2 + y_norm2 - 2.0 * (ref_logits @ test_logit.t()) # [N, 1] + + # Compute kernel values + kxy = torch.exp(-distances / (2.0 * sigma ** 2)) # [N, 1] + + # Mean similarity + mean_kxy = kxy.mean() + + # MMD^2 = xx_mean + 1 - 2*mean_kxy + mmd2 = xx_mean + 1.0 - 2.0 * mean_kxy + + return mmd2.item() + + +@torch.no_grad() +def validate(model, val_loaders, ref_loader, device): + """ + Validate model on validation set. + + Args: + model: MMD-MIL detector + val_loaders: Dict with 'real' and 'fake' DataLoaders + ref_loader: Reference set DataLoader + device: torch.device + + Returns: + auroc: Area under ROC curve + fpr95: False positive rate at 95% TPR + """ + model.eval() + sigma = model.get_sigma() + + print(f"\nValidation - Kernel bandwidth: {sigma.item():.6f}") + + # Extract and precompute reference statistics + print("Extracting reference logits...") + ref_logits = extract_ref_logits(model, ref_loader, device).to(device) + print(f"Reference shape: {ref_logits.shape}") + + print("Precomputing reference statistics...") + xx_mean, ref_norm2 = precompute_ref_stats(ref_logits, sigma) + print(f"Reference kernel mean: {xx_mean.item():.6f}") + + # Score validation samples + all_scores = [] + all_labels = [] + + # Score real samples + print("Scoring real samples...") + for embeddings, _, mask in tqdm(val_loaders["real"], desc="Real"): + embeddings = embeddings.to(device) + mask = mask.to(device) + test_logits = model.compute_logits(embeddings, mask) # [B, K] + + for i in range(test_logits.shape[0]): + y = test_logits[i:i+1] + score = score_sample(y, ref_logits, ref_norm2, xx_mean, sigma) + + if np.isfinite(score): + all_scores.append(score) + all_labels.append(0) + + # Score fake samples + print("Scoring fake samples...") + for embeddings, _, mask in tqdm(val_loaders["fake"], desc="Fake"): + embeddings = embeddings.to(device) + mask = mask.to(device) + test_logits = model.compute_logits(embeddings, mask) # [B, K] + + for i in range(test_logits.shape[0]): + y = test_logits[i:i+1] + score = score_sample(y, ref_logits, ref_norm2, xx_mean, sigma) + + if np.isfinite(score): + all_scores.append(score) + all_labels.append(1) + + # Convert to numpy + all_scores = np.array(all_scores) + all_labels = np.array(all_labels) + + # Compute metrics + fpr, tpr, _ = metrics.roc_curve(all_labels, all_scores) + auroc = metrics.auc(fpr, tpr) + + # FPR at 95% TPR + tpr_threshold = 0.95 + valid_indices = tpr >= tpr_threshold + fpr95 = fpr[valid_indices].min() if np.any(valid_indices) else 1.0 + + # Print statistics + real_scores = all_scores[all_labels == 0] + fake_scores = all_scores[all_labels == 1] + + print(f"\nScore Statistics:") + print(f" Real: mean={real_scores.mean():.6f}, std={real_scores.std():.6f}") + print(f" Fake: mean={fake_scores.mean():.6f}, std={fake_scores.std():.6f}") + print(f" Separation: {fake_scores.mean() - real_scores.mean():.6f}") + + return auroc, fpr95 + + +# ================================ +# Main Training Loop +# ================================ + +def main(): + # Parse arguments + parser = argparse.ArgumentParser( + description='Train MMD-MIL detector', + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=__doc__ + ) + parser.add_argument( + '--config', + type=str, + required=True, + help='Path to config JSON file' + ) + parser.add_argument( + '--output_dir', + type=str, + required=True, + help='Output directory for checkpoints and logs' + ) + + args = parser.parse_args() + + # Load config + print(f"Loading config from {args.config}...") + with open(args.config, 'r') as f: + config = json.load(f) + + # Create output directory + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + # Save config to output directory + with open(output_dir / 'config.json', 'w') as f: + json.dump(config, f, indent=4) + + print("\n" + "="*70) + print("Training Configuration") + print("="*70) + for key, value in config.items(): + print(f" {key}: {value}") + print("="*70) + + # Load datasets + print("\n" + "="*70) + print("Loading Datasets") + print("="*70) + + train_datasets = { + "real": PrecomputedEmbeddingDataset(config['train_embeddings'], label=0), + "fake": PrecomputedEmbeddingDataset(config['train_embeddings'], label=1) + } + + val_datasets = { + "real": PrecomputedEmbeddingDataset(config['val_embeddings'], label=0), + "fake": PrecomputedEmbeddingDataset(config['val_embeddings'], label=1) + } + + ref_dataset = PrecomputedEmbeddingDataset(config['ref_embeddings'], label=0) + + # Create data loaders + train_loaders = { + "real": DataLoader( + train_datasets["real"], + batch_size=config['batch_size'] // 2, + shuffle=True, + num_workers=config['num_workers'], + collate_fn=collate_fn, + pin_memory=True + ), + "fake": DataLoader( + train_datasets["fake"], + batch_size=config['batch_size'] // 2, + shuffle=True, + num_workers=config['num_workers'], + collate_fn=collate_fn, + pin_memory=True + ) + } + + val_loaders = { + "real": DataLoader( + val_datasets["real"], + batch_size=config['batch_size'], + shuffle=False, + num_workers=config['num_workers'], + collate_fn=collate_fn, + pin_memory=True + ), + "fake": DataLoader( + val_datasets["fake"], + batch_size=config['batch_size'], + shuffle=False, + num_workers=config['num_workers'], + collate_fn=collate_fn, + pin_memory=True + ) + } + + ref_loader = DataLoader( + ref_dataset, + batch_size=config['batch_size'], + shuffle=False, + num_workers=config['num_workers'], + collate_fn=collate_fn, + pin_memory=True + ) + + # Initialize model + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + print(f"\nUsing device: {device}") + + model = MMD_MIL_Detector( + embed_dim=config['embed_dim'], + hidden_dim=config['hidden_dim'], + dropout=config['dropout'], + init_sigma=config['init_sigma'] + ).to(device) + + # Optimizer and scheduler + optimizer = AdamW( + model.parameters(), + lr=config['lr'], + weight_decay=config['weight_decay'] + ) + + scheduler = CosineAnnealingLR( + optimizer, + T_max=config['num_epochs'] + ) + + # Training loop + print("\n" + "="*70) + print("Starting Training") + print("="*70) + print(f"Train real: {len(train_datasets['real'])}") + print(f"Train fake: {len(train_datasets['fake'])}") + print(f"Val real: {len(val_datasets['real'])}") + print(f"Val fake: {len(val_datasets['fake'])}") + print(f"Reference: {len(ref_dataset)}") + print("="*70) + + best_auroc = 0.0 + history = { + 'train_loss': [], + 'train_mmd': [], + 'val_auroc': [], + 'val_fpr95': [] + } + + for epoch in range(1, config['num_epochs'] + 1): + # Train + train_loss, train_mmd = train_epoch( + model, train_loaders, optimizer, device, epoch + ) + + # Validate + val_auroc, val_fpr95 = validate( + model, val_loaders, ref_loader, device + ) + + # Step scheduler + scheduler.step() + + # Log results + print(f"\nEpoch {epoch}/{config['num_epochs']}:") + print(f" Train - Loss: {train_loss:.4f}, MMDยฒ: {train_mmd:.6f}") + print(f" Val - AUROC: {val_auroc:.4f}, FPR@95: {val_fpr95:.4f}") + + # Save history + history['train_loss'].append(train_loss) + history['train_mmd'].append(train_mmd) + history['val_auroc'].append(val_auroc) + history['val_fpr95'].append(val_fpr95) + + # Save best model + if val_auroc > best_auroc: + best_auroc = val_auroc + torch.save({ + 'epoch': epoch, + 'model_state_dict': model.state_dict(), + 'optimizer_state_dict': optimizer.state_dict(), + 'auroc': val_auroc, + 'fpr95': val_fpr95, + 'config': config + }, output_dir / 'best_model.pth') + print(f" โœ“ Saved best model (AUROC: {val_auroc:.4f})") + + # Periodic checkpoint + if epoch % config['save_interval'] == 0: + torch.save({ + 'epoch': epoch, + 'model_state_dict': model.state_dict(), + 'optimizer_state_dict': optimizer.state_dict(), + 'auroc': val_auroc, + 'fpr95': val_fpr95, + 'config': config + }, output_dir / f'checkpoint_epoch{epoch}.pth') + + # Save training history + with open(output_dir / 'history.json', 'w') as f: + json.dump(history, f, indent=4) + + print("\n" + "="*70) + print("Training Complete!") + print("="*70) + print(f"Best AUROC: {best_auroc:.4f}") + print(f"Results saved to: {output_dir}") + print("="*70) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/detectors/NPR/__pycache__/util.cpython-310.pyc b/detectors/NPR/__pycache__/util.cpython-310.pyc deleted file mode 100644 index 154443e1f337ad766f69b880c617741f184ae6c6..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/__pycache__/util.cpython-310.pyc and /dev/null differ diff --git a/detectors/NPR/__pycache__/validate.cpython-310.pyc b/detectors/NPR/__pycache__/validate.cpython-310.pyc deleted file mode 100644 index 140666367248604756b8b5aa93fe21bd6c60ed29..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/__pycache__/validate.cpython-310.pyc and /dev/null differ diff --git a/detectors/NPR/data/__pycache__/__init__.cpython-310.pyc b/detectors/NPR/data/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 16d67175135848a0607fba9f8dff50e4c08da1f1..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/data/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/detectors/NPR/data/__pycache__/datasets.cpython-310.pyc b/detectors/NPR/data/__pycache__/datasets.cpython-310.pyc deleted file mode 100644 index 7c4cf1a65f94d2a9340b494445e326b358beb76a..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/data/__pycache__/datasets.cpython-310.pyc and /dev/null differ diff --git a/detectors/NPR/networks/__pycache__/__init__.cpython-310.pyc b/detectors/NPR/networks/__pycache__/__init__.cpython-310.pyc index dc88b87ae8652559c64795a888a720eaff9fd0da..8336f4a2dd1c084ba3ad8613b6b5430fe946a4ca 100644 Binary files a/detectors/NPR/networks/__pycache__/__init__.cpython-310.pyc and b/detectors/NPR/networks/__pycache__/__init__.cpython-310.pyc differ diff --git a/detectors/NPR/networks/__pycache__/base_model.cpython-310.pyc b/detectors/NPR/networks/__pycache__/base_model.cpython-310.pyc deleted file mode 100644 index fffcac5b5fed21a037a04ef6ad5237952348559f..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/networks/__pycache__/base_model.cpython-310.pyc and /dev/null differ diff --git a/detectors/NPR/networks/__pycache__/resnet.cpython-310.pyc b/detectors/NPR/networks/__pycache__/resnet.cpython-310.pyc index 34c82b218bc94bba421ae5b6fa6abd885d1daade..d657182bb331c99ab712865b0b0314c4fe544cb9 100644 Binary files a/detectors/NPR/networks/__pycache__/resnet.cpython-310.pyc and b/detectors/NPR/networks/__pycache__/resnet.cpython-310.pyc differ diff --git a/detectors/NPR/networks/__pycache__/trainer.cpython-310.pyc b/detectors/NPR/networks/__pycache__/trainer.cpython-310.pyc deleted file mode 100644 index 9a55acec3c7d8290b5fb425a7bd463179a3bad9a..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/networks/__pycache__/trainer.cpython-310.pyc and /dev/null differ diff --git a/detectors/NPR/options/__pycache__/__init__.cpython-310.pyc b/detectors/NPR/options/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 7187b27e05ffc886384b01962a6e47abaf06076b..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/options/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/detectors/NPR/options/__pycache__/base_options.cpython-310.pyc b/detectors/NPR/options/__pycache__/base_options.cpython-310.pyc deleted file mode 100644 index ca0a48908f4f30910d77356cbba79999cac8b901..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/options/__pycache__/base_options.cpython-310.pyc and /dev/null differ diff --git a/detectors/NPR/options/__pycache__/test_options.cpython-310.pyc b/detectors/NPR/options/__pycache__/test_options.cpython-310.pyc deleted file mode 100644 index 7340d1d92332039986676e9ea1dea65c8bd98526..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/options/__pycache__/test_options.cpython-310.pyc and /dev/null differ diff --git a/detectors/NPR/options/__pycache__/train_options.cpython-310.pyc b/detectors/NPR/options/__pycache__/train_options.cpython-310.pyc deleted file mode 100644 index b670d5e3676eef5d74fc7483faed77700be4fca4..0000000000000000000000000000000000000000 Binary files a/detectors/NPR/options/__pycache__/train_options.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/__pycache__/parser.cpython-310.pyc b/detectors/P2G/__pycache__/parser.cpython-310.pyc deleted file mode 100644 index 5a47de68cb879c2cc938cc983b5f37d14b02ad04..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/__pycache__/parser.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/src/__pycache__/eval.cpython-310.pyc b/detectors/P2G/src/__pycache__/eval.cpython-310.pyc deleted file mode 100644 index c514afd67fd958d3eafa8a06e1ba9b3f22154d85..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/src/__pycache__/eval.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/src/__pycache__/trainer.cpython-310.pyc b/detectors/P2G/src/__pycache__/trainer.cpython-310.pyc deleted file mode 100644 index b6c94b69ecc3dd9178fa21599b79f87a6a3d6e7a..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/src/__pycache__/trainer.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/src/methods/__pycache__/__init__.cpython-310.pyc b/detectors/P2G/src/methods/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 8f1538a8da8fddbc02752492c6b74f8805659838..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/src/methods/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/src/methods/__pycache__/prompt2guard.cpython-310.pyc b/detectors/P2G/src/methods/__pycache__/prompt2guard.cpython-310.pyc deleted file mode 100644 index 1e6c1e703ed92f0b7aaaac4955d2e187e4000a99..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/src/methods/__pycache__/prompt2guard.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/src/models/__pycache__/__init__.cpython-310.pyc b/detectors/P2G/src/models/__pycache__/__init__.cpython-310.pyc index c9c14d20967ef9fca86436f57f20882a96093f4f..3d45626860bff20d5d984c9414898d0648696154 100644 Binary files a/detectors/P2G/src/models/__pycache__/__init__.cpython-310.pyc and b/detectors/P2G/src/models/__pycache__/__init__.cpython-310.pyc differ diff --git a/detectors/P2G/src/models/__pycache__/slinet.cpython-310.pyc b/detectors/P2G/src/models/__pycache__/slinet.cpython-310.pyc deleted file mode 100644 index 92ca47cd758fbc4a9365ef52c7762db18823107f..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/src/models/__pycache__/slinet.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/src/models/__pycache__/slinet_det.cpython-310.pyc b/detectors/P2G/src/models/__pycache__/slinet_det.cpython-310.pyc index a820ca055ae5d86421aa759c5813536402af7efe..e1299e10028d99d9951a974615d009bf2501739f 100644 Binary files a/detectors/P2G/src/models/__pycache__/slinet_det.cpython-310.pyc and b/detectors/P2G/src/models/__pycache__/slinet_det.cpython-310.pyc differ diff --git a/detectors/P2G/src/models/clip/__pycache__/__init__.cpython-310.pyc b/detectors/P2G/src/models/clip/__pycache__/__init__.cpython-310.pyc index d92624f71cc80b36935f610b6cefa290a7b2996c..20a2246314afdc792d0e1870ddafbb5f371defca 100644 Binary files a/detectors/P2G/src/models/clip/__pycache__/__init__.cpython-310.pyc and b/detectors/P2G/src/models/clip/__pycache__/__init__.cpython-310.pyc differ diff --git a/detectors/P2G/src/models/clip/__pycache__/clip.cpython-310.pyc b/detectors/P2G/src/models/clip/__pycache__/clip.cpython-310.pyc index df0de077003b8b5c95892be2afa774946fc06251..67b1a08d078e5f813ffc4f5b63aa504c339bf6a8 100644 Binary files a/detectors/P2G/src/models/clip/__pycache__/clip.cpython-310.pyc and b/detectors/P2G/src/models/clip/__pycache__/clip.cpython-310.pyc differ diff --git a/detectors/P2G/src/models/clip/__pycache__/model.cpython-310.pyc b/detectors/P2G/src/models/clip/__pycache__/model.cpython-310.pyc index 6aeba0bd87395d0eddbb0ab793cf386a13eea174..c3b2c227c9487ee80d870844f5d12f2c851fe529 100644 Binary files a/detectors/P2G/src/models/clip/__pycache__/model.cpython-310.pyc and b/detectors/P2G/src/models/clip/__pycache__/model.cpython-310.pyc differ diff --git a/detectors/P2G/src/models/clip/__pycache__/prompt_learner.cpython-310.pyc b/detectors/P2G/src/models/clip/__pycache__/prompt_learner.cpython-310.pyc index fed417df8cbf278e1a4fc2dad8a1ba8ec048af4c..80d7c3256d24f9f53e7c6e6b87e7e0cfa4eae138 100644 Binary files a/detectors/P2G/src/models/clip/__pycache__/prompt_learner.cpython-310.pyc and b/detectors/P2G/src/models/clip/__pycache__/prompt_learner.cpython-310.pyc differ diff --git a/detectors/P2G/src/models/clip/__pycache__/simple_tokenizer.cpython-310.pyc b/detectors/P2G/src/models/clip/__pycache__/simple_tokenizer.cpython-310.pyc index ef71be1cdab77cbdff2a76fafa8f281e04b539aa..b863478e5f76db51b3f8beecbf3db091fda57c3b 100644 Binary files a/detectors/P2G/src/models/clip/__pycache__/simple_tokenizer.cpython-310.pyc and b/detectors/P2G/src/models/clip/__pycache__/simple_tokenizer.cpython-310.pyc differ diff --git a/detectors/P2G/src/utils/__pycache__/__init__.cpython-310.pyc b/detectors/P2G/src/utils/__pycache__/__init__.cpython-310.pyc index a34a0a4c97f6e3dba31413b8826c7d09529b773a..7cb3a07c54a99cfa40a3cd50fb62138aaa3a5e0a 100644 Binary files a/detectors/P2G/src/utils/__pycache__/__init__.cpython-310.pyc and b/detectors/P2G/src/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/detectors/P2G/src/utils/__pycache__/class_names.cpython-310.pyc b/detectors/P2G/src/utils/__pycache__/class_names.cpython-310.pyc index 91ed9e1b41bf0b32649f565eb7d056edd75d4d71..bb637266fad724ed9363055683d9dcc84cd25624 100644 Binary files a/detectors/P2G/src/utils/__pycache__/class_names.cpython-310.pyc and b/detectors/P2G/src/utils/__pycache__/class_names.cpython-310.pyc differ diff --git a/detectors/P2G/src/utils/__pycache__/data.cpython-310.pyc b/detectors/P2G/src/utils/__pycache__/data.cpython-310.pyc deleted file mode 100644 index d41a36df1bdde68857d1ff27bea4ba328b1432cb..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/src/utils/__pycache__/data.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/src/utils/__pycache__/data_manager.cpython-310.pyc b/detectors/P2G/src/utils/__pycache__/data_manager.cpython-310.pyc deleted file mode 100644 index 2c9eb18c51b4ce343677beadb33082f93efe92a5..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/src/utils/__pycache__/data_manager.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/src/utils/__pycache__/lr_scheduler.cpython-310.pyc b/detectors/P2G/src/utils/__pycache__/lr_scheduler.cpython-310.pyc deleted file mode 100644 index 34eafc38d561eb2e5218fb76e08d005e6b90fea7..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/src/utils/__pycache__/lr_scheduler.cpython-310.pyc and /dev/null differ diff --git a/detectors/P2G/src/utils/__pycache__/toolkit.cpython-310.pyc b/detectors/P2G/src/utils/__pycache__/toolkit.cpython-310.pyc deleted file mode 100644 index e339a7b885d0270958fd20985f801086c506f11c..0000000000000000000000000000000000000000 Binary files a/detectors/P2G/src/utils/__pycache__/toolkit.cpython-310.pyc and /dev/null differ diff --git a/detectors/PGC/detect.py b/detectors/PGC/detect.py new file mode 100644 index 0000000000000000000000000000000000000000..522ff9aa1d6e556109504580af8c068d97076239 --- /dev/null +++ b/detectors/PGC/detect.py @@ -0,0 +1,4 @@ +from run import main + +if __name__ == "__main__": + main("detect") diff --git a/detectors/PGC/run.py b/detectors/PGC/run.py new file mode 100644 index 0000000000000000000000000000000000000000..2df729296637c16a903ed8ba1bddee13baa5c6f9 --- /dev/null +++ b/detectors/PGC/run.py @@ -0,0 +1,108 @@ +"""DeepShield adapter for the official PGC model and preprocessing.""" + +import sys +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path[:0] = [str(ROOT), str(HERE / "upstream")] + +import torch +from PIL import Image +from torch.utils.data import DataLoader, Dataset + +from support.recent_common import checkpoint, detection_result, device_for, parser, timed_score, validate_inputs, write_results +from support.recent_data import samples +from data.transforms import MEAN, STD, create_eval_transforms, create_train_transforms +from models.pgc import PGCNetwork + + +class Images(Dataset): + def __init__(self, entries, transform): + self.entries, self.transform = entries, transform + + def __len__(self): + return len(self.entries) + + def __getitem__(self, index): + path, label = self.entries[index] + with Image.open(path) as image: + return self.transform(image.convert("RGB")), label + + +def model_for(device): + backbone = HERE / "checkpoint" / "backbones" / "dinov2-large" + if not backbone.is_dir(): + raise FileNotFoundError(f"DINOv2 backbone missing: {backbone}; run support/setup_recent_weights.py PGC") + return PGCNetwork(dino_variant="dinov2-large", pretrained_root=str(backbone)).to(device) + + +def transform(train=False): + fn = create_train_transforms if train else create_eval_transforms + return fn(image_size=224, mean=MEAN["dino"], std=STD["dino"]) + + +def main(task): + args = parser("PGC", task).parse_args() + validate_inputs(args, task) + device = device_for(args.device) + model = model_for(device) + if task == "train": + entries = samples(args.data_root, args.split_file, "train", args.data_keys) + loader = DataLoader(Images(entries, transform(True)), batch_size=args.batch_size, + shuffle=True, num_workers=args.num_threads) + optimizer = torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=1e-4) + model.train() + for epoch in range(args.epochs): + for step, (images, labels) in enumerate(loader): + optimizer.zero_grad(set_to_none=True) + logits = model(images.to(device)).flatten() + loss = torch.nn.functional.binary_cross_entropy_with_logits(logits, labels.float().to(device)) + loss.backward() + optimizer.step() + print(f"epoch={epoch + 1} step={step + 1} loss={loss.item():.5f}") + if args.max_steps and step + 1 >= args.max_steps: + break + target = HERE / "checkpoint" / args.name / "weights" / "best.pt" + target.parent.mkdir(parents=True, exist_ok=True) + torch.save({"model": model.state_dict()}, target) + print(f"Saved {target}") + return + + state = torch.load(checkpoint("PGC", getattr(args, "model", None) or args.name), map_location="cpu", weights_only=False) + model.load_state_dict(state["model"] if "model" in state else state) + model.eval() + evaluation = transform() + + @torch.inference_mode() + def score(path): + with Image.open(path) as image: + tensor = evaluation(image.convert("RGB")).unsqueeze(0).to(device) + raw = float(model(tensor).flatten()[0].item()) + return raw, float(torch.sigmoid(torch.tensor(raw)).item()) + + if task == "detect": + image = Path(args.image) + if not image.is_file(): + raise FileNotFoundError(image) + raw, fake, elapsed = timed_score(score, image) + detection_result("PGC", image, raw, fake, elapsed, args.output) + else: + entries = samples(args.data_root, args.split_file, "test", args.data_keys) + loader = DataLoader(Images(entries, evaluation), batch_size=args.batch_size, + shuffle=False, num_workers=args.num_threads) + rows = [] + offset = 0 + with torch.inference_mode(): + for images, _ in loader: + start = time.perf_counter() + logits = model(images.to(device)).flatten().cpu() + elapsed = (time.perf_counter() - start) / len(logits) + probabilities = torch.sigmoid(logits) + for index, (raw, fake) in enumerate(zip(logits.tolist(), probabilities.tolist())): + path, label = entries[offset + index] + rows.append({"path": str(path), "label": label, "raw_score": raw, + "fake_score": fake, "prediction": int(fake >= .5), "elapsed_time": elapsed}) + offset += len(logits) + write_results("PGC", args.name, args.data_keys, rows) diff --git a/detectors/PGC/test.py b/detectors/PGC/test.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1a7a4aa7e0a6d8be04e70943b022b6dfa77d35 --- /dev/null +++ b/detectors/PGC/test.py @@ -0,0 +1,4 @@ +from run import main + +if __name__ == "__main__": + main("test") diff --git a/detectors/PGC/train.py b/detectors/PGC/train.py new file mode 100644 index 0000000000000000000000000000000000000000..c7fd0a1ae6fd21a7b36d8d13da9cb1a9962627d5 --- /dev/null +++ b/detectors/PGC/train.py @@ -0,0 +1,4 @@ +from run import main + +if __name__ == "__main__": + main("train") diff --git a/detectors/PGC/upstream/LICENSE b/detectors/PGC/upstream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/detectors/PGC/upstream/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/detectors/PGC/upstream/data/__init__.py b/detectors/PGC/upstream/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb55899ada37c4fc1c34c493ad616c99f1a4fa6 --- /dev/null +++ b/detectors/PGC/upstream/data/__init__.py @@ -0,0 +1,46 @@ +"""Data pipeline package for the PGC project. + +Re-exports the symbols that other parts of the codebase rely on: + +- Constants and transforms from :mod:`data.transforms` +- Datasets from :mod:`data.train_dataset` and :mod:`data.eval_dataset` +- The training :func:`create_dataloader` factory from :mod:`data.dataloader` +""" + +from .dataloader import create_dataloader +from .eval_dataset import UniversalFakeDetectDataset +from .train_dataset import RealFakeDataset +from .transforms import ( + MEAN, + STD, + RESIDUAL_MEAN, + RESIDUAL_STD, + AppendResidual, + PadCenterCrop, + PadRandomCrop, + create_eval_transforms, + create_train_transforms, + get_list, + recursively_read, +) + +__all__ = [ + # Constants + "MEAN", + "STD", + "RESIDUAL_MEAN", + "RESIDUAL_STD", + # Transforms + "PadRandomCrop", + "PadCenterCrop", + "AppendResidual", + "create_train_transforms", + "create_eval_transforms", + "recursively_read", + "get_list", + # Datasets + "RealFakeDataset", + "UniversalFakeDetectDataset", + # Loaders + "create_dataloader", +] diff --git a/detectors/PGC/upstream/data/dataloader.py b/detectors/PGC/upstream/data/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..b3f82180d5a21d3f494fb2bc7f679cb5c1d6b201 --- /dev/null +++ b/detectors/PGC/upstream/data/dataloader.py @@ -0,0 +1,24 @@ +import argparse +import logging + +import torch +from torch.utils.data import DataLoader + +from .train_dataset import RealFakeDataset + +logger = logging.getLogger(__name__) + + +def create_dataloader(opt: argparse.Namespace) -> DataLoader: + + dataset = RealFakeDataset(opt) + logger.info("Dataset size: %d", len(dataset)) + + return DataLoader( + dataset, + batch_size=opt.batch_size, + shuffle=True, + num_workers=opt.num_threads, + pin_memory=True, + drop_last=True, + ) diff --git a/detectors/PGC/upstream/data/eval_dataset.py b/detectors/PGC/upstream/data/eval_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..79b16935bb5fa2e02b335ece8d3055d39bc78c15 --- /dev/null +++ b/detectors/PGC/upstream/data/eval_dataset.py @@ -0,0 +1,136 @@ +import logging +import os +from typing import Dict, List, Optional, Tuple + +from PIL import Image, ImageFile +from torch.utils.data import Dataset + +from .transforms import get_list + +ImageFile.LOAD_TRUNCATED_IMAGES = True + +logger = logging.getLogger(__name__) + + +class _PerSubsetEvalDataset(Dataset): + """Common implementation shared by the per-subset evaluation dataset. + + Subclasses only differ in the names of the *real* and *fake* leaf + directories below ``root_dir//``. + """ + + # Override these in subclasses. + REAL_DIR_NAME: str = "" + FAKE_DIR_NAME: str = "" + BENCHMARK_NAME: str = "Eval" + + def __init__(self, root_dir: str, transform=None): + self.root_dir = root_dir + self.transform = transform + + # Each entry: ``(path, label, subset_name)``. + self.samples: List[Tuple[str, int, str]] = [] + # Mapping ``subset_name -> [global indices]`` (post-sort). + self.subset_indices: Dict[str, List[int]] = {} + + # First-level sub-directories under ``root_dir`` are subsets. + subsets = [ + d + for d in os.listdir(root_dir) + if os.path.isdir(os.path.join(root_dir, d)) + ] + + for subset in subsets: + subset_path = os.path.join(root_dir, subset) + real_list = get_list(subset_path, self.REAL_DIR_NAME) + fake_list = get_list(subset_path, self.FAKE_DIR_NAME) + + logger.info( + "Subset '%s': %d real images (%s), %d fake images (%s)", + subset, + len(real_list), + self.REAL_DIR_NAME, + len(fake_list), + self.FAKE_DIR_NAME, + ) + + for p in real_list: + self.samples.append((p, 0, subset)) # 0 = real + for p in fake_list: + self.samples.append((p, 1, subset)) # 1 = fake + + # Sort so iteration order is stable across runs / machines. + self.samples.sort(key=lambda x: x[0]) + + # Rebuild subset->indices mapping after the global sort. + self.subset_indices = {} + for idx, (_, _, subset) in enumerate(self.samples): + self.subset_indices.setdefault(subset, []).append(idx) + + logger.info( + "Loaded %d images from %d %s subsets", + len(self.samples), + len(subsets), + self.BENCHMARK_NAME, + ) + + # ------------------------------------------------------------------ + def __len__(self) -> int: + return len(self.samples) + + def __getitem__(self, idx: int): + path, label, subset = self.samples[idx] + + # Corrupt-image fallback (only allowed try/except per ROLE.md). + try: + img = Image.open(path).convert("RGB") + except Exception as e: # noqa: BLE001 - intentional broad catch + logger.warning("Failed to load image %s: %s", path, e) + img = Image.new("RGB", (224, 224)) + + if self.transform is not None: + img = self.transform(img) + + return img, label, subset + + # ---- helpers used by test.py ------------------------------------ + def get_subset_names(self) -> List[str]: + """Names of every subset discovered under ``root_dir``.""" + return list(self.subset_indices.keys()) + + def get_subset_indices(self, subset_name: str) -> List[int]: + """Sample indices (within this Dataset) belonging to ``subset_name``.""" + return self.subset_indices.get(subset_name, []) + + +class UniversalFakeDetectDataset(_PerSubsetEvalDataset): + """UniversalFakeDetect benchmark (paper Table 3). + + Layout:: + + root/ + subset_a/ + 0_real/ (label = 0) + 1_fake/ (label = 1) + subset_b/ + 0_real/ + 1_fake/ + ... + """ + + REAL_DIR_NAME = "0_real" + FAKE_DIR_NAME = "1_fake" + BENCHMARK_NAME = "UniversalFakeDetect" + + def __init__(self, root_dir: str, transform=None): + super().__init__(root_dir=root_dir, transform=transform) + + +# Re-export for convenience. +__all__ = [ + "UniversalFakeDetectDataset", +] + + +# Type-narrowing alias used by some external imports. +DatasetType = Optional[_PerSubsetEvalDataset] diff --git a/detectors/PGC/upstream/data/train_dataset.py b/detectors/PGC/upstream/data/train_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..6fc7c7ece8e1c93c0f6d28777c6185887e8eaf64 --- /dev/null +++ b/detectors/PGC/upstream/data/train_dataset.py @@ -0,0 +1,159 @@ +import argparse +import logging +import random +from typing import Dict, List + +from PIL import Image, ImageFile +import torch +from torch.utils.data import Dataset +from tqdm import tqdm + +from .transforms import MEAN, STD, create_train_transforms, get_list + +ImageFile.LOAD_TRUNCATED_IMAGES = True + +logger = logging.getLogger(__name__) + + +class RealFakeDataset(Dataset): + + + def __init__(self, opt: argparse.Namespace): + self.opt = opt + self.data_list: List[Dict] = [] + self.dataset_sources: Dict[str, int] = {} + + if not opt.real_image_dir: + raise ValueError( + "--real_image_dir must be provided with at least one " + "directory (use space-separated paths for multiple sources)." + ) + if not opt.fake_image_dir: + raise ValueError( + "--fake_image_dir must be provided with at least one " + "directory (use space-separated paths for multiple sources)." + ) + + primary_samples = self._load_dataset( + real_image_dirs=opt.real_image_dir, + fake_image_dirs=opt.fake_image_dir, + source_name="primary", + ) + self.data_list.extend(primary_samples) + + for source, count in self.dataset_sources.items(): + logger.info("Loaded %d samples from %s dataset", count, source) + + random.shuffle(self.data_list) + + real_count = sum(1 for s in self.data_list if s["label"] == 0) + fake_count = sum(1 for s in self.data_list if s["label"] == 1) + total_count = len(self.data_list) + real_ratio = real_count / total_count if total_count > 0 else 0 + fake_ratio = fake_count / total_count if total_count > 0 else 0 + + logger.info("=" * 60) + logger.info("DATASET CLASS DISTRIBUTION:") + logger.info(" Total samples: %d", total_count) + logger.info( + " Real (label=0): %d (%.2f%%)", real_count, real_ratio * 100 + ) + logger.info( + " Fake (label=1): %d (%.2f%%)", fake_count, fake_ratio * 100 + ) + logger.info( + " Real/Fake ratio: %.3f", + real_count / fake_count if fake_count > 0 else float("inf"), + ) + logger.info("=" * 60) + + stat_from = "dino" + logger.info("Mean and std stats are from: %s", stat_from) + + self.transform = create_train_transforms( + image_size=opt.cropSize, + mean=MEAN[stat_from], + std=STD[stat_from], + is_crop=True, + ) + + # ------------------------------------------------------------------ + def _load_dataset( + self, + real_image_dirs: List[str], + fake_image_dirs: List[str], + source_name: str, + ) -> List[Dict]: + samples: List[Dict] = [] + self.dataset_sources[source_name] = 0 + + # Real images (potentially multiple cohorts in ``real_image_dirs``). + for real_dir in real_image_dirs: + logger.info("Scanning real images from: %s", real_dir) + real_list = get_list(real_dir) + logger.info( + "Loaded %d real images from %s", len(real_list), real_dir + ) + + for real_path in tqdm( + real_list, desc=f"Loading {source_name} real ({real_dir})" + ): + samples.append( + { + "path": real_path, + "label": 0, # 0 = real + "source": source_name, + } + ) + self.dataset_sources[source_name] += 1 + + # Fake images (potentially multiple generators in fake_image_dirs). + for fake_dir in fake_image_dirs: + logger.info("Scanning fake images from: %s", fake_dir) + fake_list = get_list(fake_dir) + logger.info( + "Loaded %d fake images from %s", len(fake_list), fake_dir + ) + + for fake_path in tqdm( + fake_list, desc=f"Loading {source_name} fake ({fake_dir})" + ): + samples.append( + { + "path": fake_path, + "label": 1, # 1 = fake + "source": source_name, + } + ) + self.dataset_sources[source_name] += 1 + + logger.info( + "Total samples loaded from %s: %d (real + fake across %d real " + "dir(s) and %d fake dir(s))", + source_name, + len(samples), + len(real_image_dirs), + len(fake_image_dirs), + ) + return samples + + # ------------------------------------------------------------------ + def __len__(self) -> int: + return len(self.data_list) + + def __getitem__(self, idx: int) -> Dict: + sample = self.data_list[idx] + + try: + img = Image.open(sample["path"]).convert("RGB") + except Exception as e: + logger.warning("Failed to load image %s: %s", sample["path"], e) + img = Image.new("RGB", (self.opt.cropSize, self.opt.cropSize)) + + img_tensor: torch.Tensor = self.transform(img) + + return { + "image": img_tensor, + "label": sample["label"], + "source": sample["source"], + } diff --git a/detectors/PGC/upstream/data/transforms.py b/detectors/PGC/upstream/data/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..885a6005a87fb7a9d8880d12557f7adf5fcd09fc --- /dev/null +++ b/detectors/PGC/upstream/data/transforms.py @@ -0,0 +1,238 @@ +import logging +import os +from typing import List + +import torch +import torchvision.transforms as transforms +import torchvision.transforms.functional as F + +logger = logging.getLogger(__name__) + +MEAN = { + "imagenet": [0.485, 0.456, 0.406], + "clip": [0.48145466, 0.4578275, 0.40821073], + "dino": [0.485, 0.456, 0.406], +} + +STD = { + "imagenet": [0.229, 0.224, 0.225], + "clip": [0.26862954, 0.26130258, 0.27577711], + "dino": [0.229, 0.224, 0.225], +} + +RESIDUAL_MEAN: List[float] = [0.0, 0.0, 0.0] +RESIDUAL_STD: List[float] = [0.5, 0.5, 0.5] + + +# --------------------------------------------------------------------------- +# Filesystem helpers +# --------------------------------------------------------------------------- +def recursively_read( + rootdir: str, + must_contain: str, + exts=("png", "jpg", "jpeg", "JPEG", "bmp", "webp"), +) -> List[str]: + """Recursively scan ``rootdir`` for image files. + + Args: + rootdir: Root of the search. + must_contain: Optional substring filter applied to the full path. + exts: Allowed file extensions (case-insensitive on the lowercase form). + + Returns: + List of absolute / joined paths to the matching files. + """ + out: List[str] = [] + exts_lc = {e.lower() for e in exts} + for r, _, files in os.walk(rootdir, followlinks=True): + for file in files: + # Defensive split: files without an extension are skipped instead + # of raising IndexError. + parts = file.split(".") + if len(parts) < 2: + continue + ext = parts[-1].lower() + full = os.path.join(r, file) + if ext in exts_lc and must_contain in full: + out.append(full) + return out + + +def get_list(path: str, must_contain: str = "") -> List[str]: + """Convenience wrapper around :func:`recursively_read` with no extras.""" + return recursively_read(path, must_contain) + + +# --------------------------------------------------------------------------- +# Geometry transforms +# --------------------------------------------------------------------------- +class PadRandomCrop: + """Pad the image to ``size`` if needed, then take a random crop. + + Used at training time to preserve original pixel patterns (no resize + distortion that would erase the per-pixel quantization residual). + """ + + def __init__(self, size: int): + self.size = size + + def __call__(self, img): + w, h = img.size + pad_h = max(0, self.size - h) + pad_w = max(0, self.size - w) + + if pad_h > 0 or pad_w > 0: + padding = ( + pad_w // 2, + pad_h // 2, + pad_w - pad_w // 2, + pad_h - pad_h // 2, + ) + img = F.pad(img, padding, fill=0) + + return transforms.RandomCrop(self.size)(img) + + +class PadCenterCrop: + """Pad the image to ``size`` if needed, then take a deterministic centre crop. + + Mirrors :class:`PadRandomCrop` exactly (same padding strategy) so train and + test pipelines differ only in the crop position. Critical for + forensic/PRNU-style features that can be wiped by ``Resize``. + """ + + def __init__(self, size: int): + self.size = size + + def __call__(self, img): + w, h = img.size + pad_h = max(0, self.size - h) + pad_w = max(0, self.size - w) + + if pad_h > 0 or pad_w > 0: + padding = ( + pad_w // 2, + pad_h // 2, + pad_w - pad_w // 2, + pad_h - pad_h // 2, + ) + img = F.pad(img, padding, fill=0) + + return transforms.CenterCrop(self.size)(img) + + +# --------------------------------------------------------------------------- +# Residual transform +# --------------------------------------------------------------------------- +class AppendResidual: + """Append the quantization residual as 3 extra channels. + + The residual is computed on the RGB tensor in ``[0, 1]`` (BEFORE + normalization). Normalization is then applied to the resulting 6-channel + tensor, with different mean/std for the RGB block and the residual block. + + Output: ``[6, H, W]`` where channels ``0..2`` are RGB and channels + ``3..5`` are the residual. + + The residual extractor used here is exactly the one used inside the + model (``models.encoder.residual_extractor``). We import it lazily in + ``__init__`` to keep this module importable when the model package is + not yet on the import path (e.g. during unit tests). + """ + + def __init__(self): + # Lazy import so this module can still be imported when the + # ``models`` package is absent (used by light-weight smoke tests). + from models.encoder.residual_extractor import get_residual_extractor + + self.residual_extractor = get_residual_extractor() + + def __call__(self, img_tensor: torch.Tensor) -> torch.Tensor: + """Compute the residual and concatenate with the RGB tensor. + + Args: + img_tensor: ``[3, H, W]`` RGB tensor in ``[0, 1]``. + + Returns: + ``[6, H, W]`` tensor: ``[RGB โˆฅ residual]``. + """ + assert img_tensor.size(0) == 3, ( + f"Expected 3 channels, got {img_tensor.size(0)}" + ) + assert img_tensor.min() >= 0.0 and img_tensor.max() <= 1.0, ( + f"Input must be in [0, 1], got " + f"range [{img_tensor.min():.3f}, {img_tensor.max():.3f}]" + ) + + residual = self.residual_extractor(img_tensor.unsqueeze(0)).squeeze(0) + residual = residual.to(dtype=img_tensor.dtype) + return torch.cat([img_tensor, residual], dim=0) + + def __repr__(self) -> str: + return self.__class__.__name__ + "(input=[0,1])" + + +# --------------------------------------------------------------------------- +# Compose helpers +# --------------------------------------------------------------------------- +def create_train_transforms( + image_size: int = 224, + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), + is_crop: bool = True, +) -> transforms.Compose: + + if is_crop: + resize_func = PadRandomCrop(image_size) + else: + logger.info("Using Resize to %d x %d", image_size, image_size) + resize_func = transforms.Resize((image_size, image_size)) + + return transforms.Compose( + [ + transforms.RandomHorizontalFlip(), + transforms.RandomApply( + [ + transforms.ColorJitter( + brightness=0.15, + contrast=0.15, + saturation=0.15, + hue=0.05, + ) + ], + p=0.2, + ), + resize_func, + transforms.ToTensor(), + AppendResidual(), + transforms.Normalize( + mean=list(mean) + RESIDUAL_MEAN, + std=list(std) + RESIDUAL_STD, + ), + ] + ) + + +def create_eval_transforms( + image_size: int = 224, + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), +) -> transforms.Compose: + + logger.info( + "[Eval] Using deterministic PadCenterCrop to %d x %d", + image_size, + image_size, + ) + + return transforms.Compose( + [ + PadCenterCrop(image_size), + transforms.ToTensor(), + AppendResidual(), + transforms.Normalize( + mean=list(mean) + RESIDUAL_MEAN, + std=list(std) + RESIDUAL_STD, + ), + ] + ) diff --git a/detectors/PGC/upstream/engine/__init__.py b/detectors/PGC/upstream/engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72ab4895717ee384746ffd5d52b37503c788d89d --- /dev/null +++ b/detectors/PGC/upstream/engine/__init__.py @@ -0,0 +1,6 @@ +"""Training / evaluation engine package.""" + +from .evaluator import evaluate_model +from .trainer import PGCTrainer + +__all__ = ["PGCTrainer", "evaluate_model"] diff --git a/detectors/PGC/upstream/engine/evaluator.py b/detectors/PGC/upstream/engine/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..f69b0c6817c754ea4462ece005946dc40cd406fa --- /dev/null +++ b/detectors/PGC/upstream/engine/evaluator.py @@ -0,0 +1,67 @@ +import logging + +import numpy as np +import torch +from torch.utils.data import DataLoader, Subset + +from utils.metrics import compute_all_metrics, log_metrics + + +logger = logging.getLogger(__name__) + + +def evaluate_model(model, device, dataset, batch_size, num_workers): + + model.eval() + + subset_metrics: dict[str, dict[str, float]] = {} + all_labels: list = [] + all_scores: list = [] + + for subset_name in dataset.get_subset_names(): + subset_indices = dataset.get_subset_indices(subset_name) + subset_dataset = Subset(dataset, subset_indices) + subset_loader = DataLoader( + subset_dataset, + batch_size=batch_size, + shuffle=False, + num_workers=num_workers, + pin_memory=True, + ) + + subset_labels: list = [] + subset_scores: list = [] + + with torch.no_grad(): + for batch in subset_loader: + # Subset-aware datasets may return either + # (image, label, subset_name) or (image, label). + if len(batch) == 3: + images, labels, _ = batch + else: + images, labels = batch + + images = images.to(device) + labels = labels.to(device) + + _features, logits = model(images, return_feature=True) + logits = logits.view(-1) + probs = torch.sigmoid(logits) + + subset_labels.extend(labels.cpu().numpy()) + subset_scores.extend(probs.cpu().numpy()) + all_labels.extend(labels.cpu().numpy()) + all_scores.extend(probs.cpu().numpy()) + + subset_y_true = np.array(subset_labels) + subset_y_score = np.array(subset_scores) + + metrics = compute_all_metrics(subset_y_true, subset_y_score) + subset_metrics[subset_name] = metrics + log_metrics(metrics, subset_name) + + y_true = np.array(all_labels) + y_score = np.array(all_scores) + overall_metrics = compute_all_metrics(y_true, y_score) + + return subset_metrics, overall_metrics diff --git a/detectors/PGC/upstream/engine/trainer.py b/detectors/PGC/upstream/engine/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..49137dd79c82e3109bb79f07ad2f6b7c81a8fd92 --- /dev/null +++ b/detectors/PGC/upstream/engine/trainer.py @@ -0,0 +1,202 @@ +import argparse +import logging +import os + +import torch +import torch.nn as nn + +from models.pgc import PGCNetwork + + +logger = logging.getLogger(__name__) + + +class PGCTrainer: + + def __init__(self, opt: argparse.Namespace): + self.opt = opt + + # -------- Persisted scalar config (no hasattr fallbacks) -------- + self.label_smoothing = float(opt.label_smoothing) + self.accumulation_steps = int(opt.accumulation_steps) + self.max_grad_norm = float(opt.max_grad_norm) + + # -------- Filesystem layout -------- + self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) + os.makedirs(self.save_dir, exist_ok=True) + + # -------- Device -------- + self.device: torch.device = opt.device + + # -------- Build model -------- + self.model: PGCNetwork = PGCNetwork( + dino_variant=opt.dino_variant, + num_classes=1, + lora_rank=int(opt.lora_rank), + lora_alpha=float(opt.lora_alpha), + lora_dropout=float(opt.lora_dropout), + lora_targets=None, # use PGCNetwork's documented default + pretrained_root=opt.dino_pretrained_root, + tau_rgb=float(opt.tau_rgb), + tau_res=float(opt.tau_res), + ) + self.model.to(self.device) + + # -------- Parameter group(s) -------- + params = self.model.get_trainable_params() + total_params = sum(p.numel() for p in self.model.parameters()) + trainable_params = sum(p.numel() for p in params) + logger.info( + "[PGCTrainer] Total params: %s | Trainable: %s (%.2f%%)", + f"{total_params:,}", + f"{trainable_params:,}", + (trainable_params / total_params * 100.0) if total_params else 0.0, + ) + + # -------- Optimizer -------- + if opt.optim == "adam": + self.optimizer = torch.optim.AdamW( + params, + lr=float(opt.lr), + betas=(0.9, 0.999), + weight_decay=float(opt.weight_decay), + ) + elif opt.optim == "sgd": + self.optimizer = torch.optim.SGD( + params, + lr=float(opt.lr), + momentum=0.0, + weight_decay=float(opt.weight_decay), + ) + else: + raise ValueError("opt.optim must be one of {'adam', 'sgd'}") + + # -------- Scheduler (filled in via setup_scheduler) -------- + self.scheduler: torch.optim.lr_scheduler.LRScheduler | None = None + + # -------- Loss -------- + self.loss_fn = nn.BCEWithLogitsLoss() + logger.info( + "[PGCTrainer] BCEWithLogitsLoss + label smoothing (eps=%.3f), " + "grad_clip=%.2f, accumulation=%d", + self.label_smoothing, self.max_grad_norm, self.accumulation_steps, + ) + + # -------- Step counters / live tensors (declared for explicitness) -------- + self.total_steps: int = 0 + self.current_step: int = 0 + self.input_imgs: torch.Tensor | None = None + self.labels: torch.Tensor | None = None + # Most-recent fused feature / logit / loss (populated by forward). + self.feature: torch.Tensor | None = None + self.output: torch.Tensor | None = None + self.loss: torch.Tensor | None = None + + # ------------------------------------------------------------------ # + # Scheduler # + # ------------------------------------------------------------------ # + + def setup_scheduler(self, total_steps: int): + """Create a CosineAnnealingLR scheduler with ``T_max=total_steps``. + + Called from ``train.py`` once the dataloader length is known. + ``eta_min`` is set to ``1%`` of the initial LR. + """ + eta_min = float(self.opt.lr) * 0.01 + self.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + self.optimizer, T_max=int(total_steps), eta_min=eta_min, + ) + logger.info( + "[PGCTrainer] Scheduler ready: CosineAnnealingLR(T_max=%d, eta_min=%.2e)", + int(total_steps), eta_min, + ) + + # ------------------------------------------------------------------ # + # Train / eval mode toggles # + # ------------------------------------------------------------------ # + + def train(self): + """Set the underlying model to training mode.""" + self.model.train() + + def eval(self): + """Set the underlying model to evaluation mode.""" + self.model.eval() + + # ------------------------------------------------------------------ # + # Step API # + # ------------------------------------------------------------------ # + + def set_input(self, batch: dict): + """Move a batch onto the trainer device. + + Args: + batch: dict with keys + * ``"image"`` - ``[B, 6, H, W]`` (RGB ++ residual concat) + * ``"label"`` - ``[B]`` (0=real, 1=fake) + * ``"source"`` - ``List[str]`` (subset names; not used here) + """ + self.input_imgs = batch["image"].to(self.device) + self.labels = batch["label"].to(self.device).float() + + def _forward(self): + """Run a forward pass and store ``self.feature`` / ``self.output``.""" + feature, logits = self.model(self.input_imgs, return_feature=True) + self.feature = feature + # Standardize logits to [B, 1] then to [B] for the BCE call site. + self.output = logits.view(-1, 1) + + def optimize_parameters(self): + """Single training step with grad accumulation + label smoothing.""" + self.current_step += 1 + self.total_steps += 1 + + self._forward() + + # Manual label smoothing: y_smooth = y * (1 - eps) + eps / 2 + labels_smooth = ( + self.labels * (1.0 - self.label_smoothing) + + self.label_smoothing / 2.0 + ) + + # Compute loss; store the unscaled value on self.loss for logging. + loss = self.loss_fn(self.output.squeeze(1), labels_smooth) + self.loss = loss + + # Scale by accumulation count for gradient averaging across micro-batches. + scaled_loss = loss / self.accumulation_steps + scaled_loss.backward() + + if self.current_step % self.accumulation_steps == 0: + torch.nn.utils.clip_grad_norm_( + self.model.parameters(), self.max_grad_norm + ) + self.optimizer.step() + if self.scheduler is not None: + self.scheduler.step() + self.optimizer.zero_grad() + + def finalize_epoch(self): + + if self.current_step % self.accumulation_steps != 0: + torch.nn.utils.clip_grad_norm_( + self.model.parameters(), self.max_grad_norm + ) + self.optimizer.step() + self.optimizer.zero_grad() + + # ------------------------------------------------------------------ # + # Persistence # + # ------------------------------------------------------------------ # + + def save_networks(self, filename: str): + + save_path = os.path.join(self.save_dir, filename) + state = { + "model": self.model.state_dict(), + "optimizer": self.optimizer.state_dict(), + "total_steps": self.total_steps, + "opt": vars(self.opt), + } + torch.save(state, save_path) + logger.info("[PGCTrainer] Saved checkpoint to: %s", save_path) diff --git a/detectors/PGC/upstream/models/__init__.py b/detectors/PGC/upstream/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1945f1e9eac817809b6396ca5f0e7b9c922c427b --- /dev/null +++ b/detectors/PGC/upstream/models/__init__.py @@ -0,0 +1,34 @@ +"""PGC model package. + +Re-exports the top-level :class:`PGCNetwork` together with its sub-components +so external code only needs to know about ``models.*``. +""" + +from .encoder.residual_extractor import ( + QuantizationResidualExtractor, + get_residual_extractor, +) +from .encoder.residual_stream import ResidualStream +from .encoder.rgb_stream import CHANNELS, RgbStream +from .lora.lora import ( + LoRALayer, + LoRALinear, + apply_lora_to_linear_layers, + get_lora_params, +) +from .pgc import PGCNetwork +from .pgcm.peak_calibration import PeakGuidedCalibrationModule + +__all__ = [ + "PGCNetwork", + "RgbStream", + "ResidualStream", + "CHANNELS", + "QuantizationResidualExtractor", + "get_residual_extractor", + "PeakGuidedCalibrationModule", + "LoRALayer", + "LoRALinear", + "apply_lora_to_linear_layers", + "get_lora_params", +] diff --git a/detectors/PGC/upstream/models/encoder/__init__.py b/detectors/PGC/upstream/models/encoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d113eda7e6ad863c8e52a1de69c6cf3ba86963c9 --- /dev/null +++ b/detectors/PGC/upstream/models/encoder/__init__.py @@ -0,0 +1,26 @@ +"""Feature encoder package. + +Re-exports the dual-stream feature encoders described in paper Sec. 3.1 +(Residual Stream + RGB Stream) and the quantization residual extractor +(paper Eq. 1). +""" + +from .residual_extractor import ( + M_YUV, + M_YUV_INV, + QuantizationResidualExtractor, + get_residual_extractor, +) +from .residual_stream import ResidualStream +from .rgb_stream import CHANNELS, RgbStream, resolve_local_dino_path + +__all__ = [ + "M_YUV", + "M_YUV_INV", + "QuantizationResidualExtractor", + "get_residual_extractor", + "ResidualStream", + "CHANNELS", + "RgbStream", + "resolve_local_dino_path", +] diff --git a/detectors/PGC/upstream/models/encoder/residual_extractor.py b/detectors/PGC/upstream/models/encoder/residual_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..03c51f60234a63d722bfdf3885410fd358852893 --- /dev/null +++ b/detectors/PGC/upstream/models/encoder/residual_extractor.py @@ -0,0 +1,56 @@ +import torch +import torch.nn as nn + + +# RGB -> YCbCr (BT.601) transform; matches paper Eq. 1 exactly. +M_YUV = torch.tensor( + [ + [0.299, 0.587, 0.114], + [-0.168736, -0.331264, 0.5], + [0.5, -0.418688, -0.081312], + ], + dtype=torch.float32, +) + +M_YUV_INV = torch.tensor( + [ + [1.0, 0.0, 1.402], + [1.0, -0.344136, -0.714136], + [1.0, 1.772, 0.0], + ], + dtype=torch.float32, +) + + +class QuantizationResidualExtractor(nn.Module): + + def __init__(self): + super().__init__() + self.register_buffer("M_t", M_YUV) + self.register_buffer("M_t_inv", M_YUV_INV) + + def forward(self, x): + """Compute the residual map. + + Args: + x: ``[B, 3, H, W]`` tensor in ``[0, 1]`` range (post-ToTensor). + + Returns: + ``[B, 3, H, W]`` residual tensor, clamped to ``[-1, 1]``. + """ + x_scaled = x * 255.0 + x_permuted = x_scaled.permute(0, 2, 3, 1) # [B, H, W, 3] + + x_yuv = torch.matmul(x_permuted, self.M_t.T) + x_quantized = torch.round(x_yuv) + x_reconstructed = torch.matmul(x_quantized, self.M_t_inv.T) + + residual = x_permuted - x_reconstructed + residual = residual.permute(0, 3, 1, 2) + + residual = torch.clamp(residual, -1.0, 1.0) + return residual + + +def get_residual_extractor(): + return QuantizationResidualExtractor() diff --git a/detectors/PGC/upstream/models/encoder/residual_stream.py b/detectors/PGC/upstream/models/encoder/residual_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..19c384f4a746f5bdc5cdae124970e21988ce90af --- /dev/null +++ b/detectors/PGC/upstream/models/encoder/residual_stream.py @@ -0,0 +1,32 @@ +import torch +import torch.nn as nn + + +class ResidualStream(nn.Module): + + def __init__(self, out_channels: int = 256): + super().__init__() + + self.out_channels = out_channels + + self.block1 = nn.Sequential( + nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1), + nn.BatchNorm2d(64), + nn.ReLU(inplace=True), + ) + self.block2 = nn.Sequential( + nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1), + nn.BatchNorm2d(128), + nn.ReLU(inplace=True), + ) + self.block3 = nn.Sequential( + nn.Conv2d(128, out_channels, kernel_size=3, stride=2, padding=1), + nn.BatchNorm2d(out_channels), + nn.ReLU(inplace=True), + ) + + def forward(self, residual: torch.Tensor) -> torch.Tensor: + x = self.block1(residual) + x = self.block2(x) + x = self.block3(x) + return x diff --git a/detectors/PGC/upstream/models/encoder/rgb_stream.py b/detectors/PGC/upstream/models/encoder/rgb_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc558ace465386c9550f9f4426cddf045967670 --- /dev/null +++ b/detectors/PGC/upstream/models/encoder/rgb_stream.py @@ -0,0 +1,108 @@ +import logging +import os + +import torch +import torch.nn as nn +from transformers import AutoModel + + +logger = logging.getLogger(__name__) + + +# Embedding dimension of every supported DINO variant. +CHANNELS = { + "dinov2-base": 768, + "dinov2-large": 1024, + "dinov2-giant": 1536, + # DINOv3 ViT-B/16 pretrain (lvd1689m). + "dinov3-vitb16-pretrain-lvd1689m": 768, +} + + +def resolve_local_dino_path(name: str, pretrained_root: str) -> str: + + assert pretrained_root is not None, ( + ) + + candidates = [ + pretrained_root, + os.path.join(pretrained_root, name), + ] + for cand in candidates: + if os.path.isdir(cand) and os.path.exists(os.path.join(cand, "config.json")): + logger.info("[DINO] Using local checkpoint at: %s", cand) + return cand + + raise FileNotFoundError( + f"[DINO] Could not find local checkpoint for '{name}'. " + f"Looked under: {pretrained_root}. " + f"Please download the model locally and point pretrained_root to it." + ) + + +def _extract_cls_and_tokens(backbone: nn.Module, rgb: torch.Tensor): + + if hasattr(backbone, "forward_features"): + feats = backbone.forward_features(rgb) + if isinstance(feats, dict): + x_norm = feats.get("x_norm", None) + cls_tok = feats.get("x_norm_clstoken", None) + patch_tok = feats.get("x_norm_patchtokens", None) + + if patch_tok is None and x_norm is not None and x_norm.dim() == 3 and x_norm.size(1) >= 2: + patch_tok = x_norm[:, 1:] + if cls_tok is None and x_norm is not None and x_norm.dim() == 3 and x_norm.size(1) >= 1: + cls_tok = x_norm[:, 0] + + if cls_tok is not None and patch_tok is not None: + return cls_tok, patch_tok + + outputs = backbone(rgb) + if isinstance(outputs, dict): + last_hidden = outputs.get("last_hidden_state", None) + else: + # ModelOutput exposes attributes; fall back to tuple/list as last resort. + last_hidden = getattr(outputs, "last_hidden_state", None) + if last_hidden is None and isinstance(outputs, (tuple, list)) and len(outputs) > 0: + last_hidden = outputs[0] + + if last_hidden is None: + raise RuntimeError( + "DINO backbone output does not contain 'last_hidden_state' (dict/attr/tuple)." + ) + if last_hidden.dim() != 3 or last_hidden.size(1) < 1: + raise RuntimeError( + f"Unexpected DINO hidden state shape: {list(last_hidden.shape)}" + ) + + cls_tok = last_hidden[:, 0] # [B, D] + patch_tok = last_hidden[:, 1:] # [B, N, D] + return cls_tok, patch_tok + + +class RgbStream(nn.Module): + + def __init__(self, name: str, pretrained_root: str): + super().__init__() + + if name not in CHANNELS: + raise ValueError( + f"Unsupported DINO variant '{name}'. " + f"Supported variants: {list(CHANNELS.keys())}" + ) + + self.name = name + self._embed_dim = CHANNELS[name] + + model_path = resolve_local_dino_path(name, pretrained_root) + logger.info("[DINO] Loading backbone '%s' from: %s", name, model_path) + self.backbone = AutoModel.from_pretrained(model_path) + + @property + def embed_dim(self) -> int: + return self._embed_dim + + def forward(self, rgb: torch.Tensor): + """Run the backbone and return ``(f_rgb_cls, f_rgb_tokens)``.""" + cls_tok, patch_tok = _extract_cls_and_tokens(self.backbone, rgb) + return cls_tok, patch_tok diff --git a/detectors/PGC/upstream/models/lora/__init__.py b/detectors/PGC/upstream/models/lora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0b02e16b619b4fe6971f6ca77c5b62ea5a1eded2 --- /dev/null +++ b/detectors/PGC/upstream/models/lora/__init__.py @@ -0,0 +1,17 @@ +"""LoRA primitives package.""" + +from .lora import ( + LoRALayer, + LoRALinear, + apply_lora_to_linear_layers, + get_lora_params, + get_submodule, +) + +__all__ = [ + "LoRALayer", + "LoRALinear", + "apply_lora_to_linear_layers", + "get_lora_params", + "get_submodule", +] diff --git a/detectors/PGC/upstream/models/lora/lora.py b/detectors/PGC/upstream/models/lora/lora.py new file mode 100644 index 0000000000000000000000000000000000000000..f7fd77f40afa44f0fc34065435218fe3de362eb8 --- /dev/null +++ b/detectors/PGC/upstream/models/lora/lora.py @@ -0,0 +1,131 @@ +import math + +import torch +import torch.nn as nn + + +class LoRALayer(nn.Module): + + def __init__(self, in_dim, out_dim, rank=4, alpha=1.0): + super().__init__() + self.alpha = alpha + self.rank = rank + + # A: [r, in_dim], B: [out_dim, r]; effective weight delta = B @ A. + self.lora_A = nn.Parameter(torch.zeros((rank, in_dim))) + self.lora_B = nn.Parameter(torch.zeros((out_dim, rank))) + + # Standard LoRA init: A ~ kaiming, B = 0 so the adapter starts as + # identity (zero perturbation) at the beginning of training. + nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5)) + nn.init.zeros_(self.lora_B) + + def forward(self, x): + # einsum keeps arbitrary leading dimensions intact. + lora_out = torch.einsum("...d, rd -> ...r", x, self.lora_A) + lora_out = torch.einsum("...r, or -> ...o", lora_out, self.lora_B) + return lora_out * (self.alpha / self.rank) + + +class LoRALinear(nn.Module): + + def __init__(self, original_layer, rank=4, alpha=1.0, trainable_orig=False, dropout=0.1): + super().__init__() + self.original_layer = original_layer + + if not trainable_orig: + for param in self.original_layer.parameters(): + param.requires_grad = False + + in_features = original_layer.in_features + out_features = original_layer.out_features + + self.lora = LoRALayer(in_features, out_features, rank, alpha) + # Dropout is applied only on the LoRA branch to regularize the adapter + # without disturbing the frozen path. + self.dropout = nn.Dropout(p=dropout) + + def forward(self, x): + original_output = self.original_layer(x) + lora_output = self.lora(x) + lora_output = self.dropout(lora_output) + + if original_output.shape != lora_output.shape: + raise ValueError( + f"dimension mismatch: original output {original_output.shape}, " + f"LoRA output {lora_output.shape}" + ) + + return original_output + lora_output + + def __getattr__(self, name): + # Forward common ``nn.Linear`` attributes (weight / bias) to the + # underlying layer so external code that introspects them keeps working. + if name == "weight": + return self.original_layer.weight + if name == "bias": + return self.original_layer.bias + return super().__getattr__(name) + + +def apply_lora_to_linear_layers( + model, + rank=4, + alpha=1.0, + target_modules=None, + trainable_orig=False, + dropout=0.1, +): + + for name, module in model.named_modules(): + if target_modules is not None and not any( + target in name for target in target_modules + ): + continue + + if isinstance(module, nn.Linear): + parent_name = name.rsplit(".", 1)[0] if "." in name else "" + child_name = name.rsplit(".", 1)[1] if "." in name else name + parent = model if parent_name == "" else get_submodule(model, parent_name) + + setattr( + parent, + child_name, + LoRALinear(module, rank, alpha, trainable_orig, dropout), + ) + + return model + + +def get_submodule(model, submodule_name): + """Resolve a dotted path (e.g. ``"blocks.0.mlp.fc1"``) to a submodule.""" + + if not submodule_name: + return model + + parts = submodule_name.split(".") + current_module = model + + for part in parts: + if part.isdigit(): + current_module = current_module[int(part)] + else: + current_module = getattr(current_module, part) + + return current_module + + +def get_lora_params(model): + + lora_params = [] + seen = set() + + for _, module in model.named_modules(): + if isinstance(module, LoRALinear): + for p in module.lora.parameters(): + pid = id(p) + if pid not in seen: + seen.add(pid) + lora_params.append(p) + + return lora_params diff --git a/detectors/PGC/upstream/models/pgc.py b/detectors/PGC/upstream/models/pgc.py new file mode 100644 index 0000000000000000000000000000000000000000..59fa5b0e7e9948bc71c2c50bc2c0c296ed696059 --- /dev/null +++ b/detectors/PGC/upstream/models/pgc.py @@ -0,0 +1,148 @@ +import logging + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .encoder.residual_stream import ResidualStream +from .encoder.rgb_stream import RgbStream +from .lora.lora import apply_lora_to_linear_layers, get_lora_params +from .pgcm.peak_calibration import PeakGuidedCalibrationModule + + +logger = logging.getLogger(__name__) + + +# Default LoRA target modules inside a DINO ViT block. +_DEFAULT_LORA_TARGETS = ["attn.qkv", "attn.proj", "mlp.fc1", "mlp.fc2"] + +# Channel dimension of the residual stream output (matches paper). +_RESIDUAL_DIM = 256 + + +class PGCNetwork(nn.Module): + + + def __init__( + self, + dino_variant: str, + num_classes: int = 1, + lora_rank: int = 8, + lora_alpha: float = 1.0, + lora_dropout: float = 0.1, + lora_targets=None, + pretrained_root=None, + tau_rgb: float = 0.5, + tau_res: float = 0.5, + ): + super().__init__() + + # --- (a) Feature Encoding --- + self.rgb_stream = RgbStream(dino_variant, pretrained_root) + self.residual_stream = ResidualStream(out_channels=_RESIDUAL_DIM) + + # --- (b) PGCM --- + self.pgcm = PeakGuidedCalibrationModule( + rgb_dim=self.rgb_stream.embed_dim, + residual_dim=_RESIDUAL_DIM, + tau_rgb=tau_rgb, + tau_res=tau_res, + ) + + # --- (c) Global classifier head --- + in_dim = self.rgb_stream.embed_dim + _RESIDUAL_DIM + self.classifier = nn.Linear(in_dim, num_classes) + nn.init.normal_(self.classifier.weight, 0.0, 0.02) + if self.classifier.bias is not None: + nn.init.zeros_(self.classifier.bias) + + # --- LoRA injection inside the ViT backbone --- + targets = _DEFAULT_LORA_TARGETS if lora_targets is None else list(lora_targets) + logger.info( + "[PGCNetwork] Injecting LoRA (rank=%d, alpha=%.3f, dropout=%.3f, " + "targets=%s) into RGB backbone.", + lora_rank, lora_alpha, lora_dropout, targets, + ) + # Patch matching nn.Linear layers in-place. + self.rgb_stream.backbone = apply_lora_to_linear_layers( + self.rgb_stream.backbone, + rank=lora_rank, + alpha=lora_alpha, + dropout=lora_dropout, + target_modules=targets, + trainable_orig=False, + ) + + # Freeze every backbone parameter, then re-enable ONLY the LoRA params. + # Mirrors the old project: prevents accidental partial unfreezing that + # leads to overfitting. + for p in self.rgb_stream.backbone.parameters(): + p.requires_grad = False + for p in get_lora_params(self.rgb_stream.backbone): + p.requires_grad = True + + # Persist trainable hyperparameters for downstream tooling / logging. + self.dino_variant = dino_variant + self.lora_rank = lora_rank + self.lora_alpha = lora_alpha + self.lora_dropout = lora_dropout + self.lora_targets = targets + + # ------------------------------------------------------------------ # + # Forward # + # ------------------------------------------------------------------ # + + def forward(self, x: torch.Tensor, return_feature: bool = False): + + rgb = x[:, :3, :, :] # [B, 3, H, W] + residual = x[:, 3:, :, :] # [B, 3, H, W] + + # --- RGB stream --- + f_rgb_cls, f_rgb_tokens = self.rgb_stream(rgb) # [B,D],[B,N,D] + + # --- Residual stream --- + f_residual_map = self.residual_stream(residual) # [B,C,Hr,Wr] + f_res_pooled = torch.flatten( + F.adaptive_avg_pool2d(f_residual_map, 1), 1 + ) # [B, C] + + # --- Local calibration bias from PGCM --- + z_local = self.pgcm(f_rgb_tokens, f_residual_map) # [B, 1] + + # --- Global feature + classifier (Eq. 5 LHS) --- + f_global = torch.cat([f_rgb_cls, f_res_pooled], dim=1) # [B, D+C] + # L2-normalize to the unit hypersphere; with small-norm classifier + # weights this keeps Z_global tight around 0 so that Z_local can + # decisively shift the decision (paper Sec. 3.3 design intent). + f_global_normed = F.normalize(f_global, p=2, dim=1) + z_global = self.classifier(f_global_normed) # [B, num_classes] + + # --- Final additive calibration (paper Eq. 5) --- + y_pred = z_global + z_local + + if return_feature: + return f_global, y_pred + return y_pred + + # ------------------------------------------------------------------ # + # Trainable parameter collection # + # ------------------------------------------------------------------ # + + def get_trainable_params(self): + + seen = set() + out = [] + + def _add(params): + for p in params: + if id(p) in seen: + continue + seen.add(id(p)) + out.append(p) + + _add(get_lora_params(self.rgb_stream.backbone)) + _add(self.residual_stream.parameters()) + _add(self.classifier.parameters()) + _add(self.pgcm.parameters()) # includes score heads + lambda_rgb + + return out diff --git a/detectors/PGC/upstream/models/pgcm/__init__.py b/detectors/PGC/upstream/models/pgcm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2e029449ea7928c0e3ec19c44653fb888c742898 --- /dev/null +++ b/detectors/PGC/upstream/models/pgcm/__init__.py @@ -0,0 +1,5 @@ +"""Peak-Guided Calibration Module (PGCM) package.""" + +from .peak_calibration import PeakGuidedCalibrationModule + +__all__ = ["PeakGuidedCalibrationModule"] diff --git a/detectors/PGC/upstream/models/pgcm/peak_calibration.py b/detectors/PGC/upstream/models/pgcm/peak_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..62e7eb9f722c3a021ab3ef9f9fef45a523d915fd --- /dev/null +++ b/detectors/PGC/upstream/models/pgcm/peak_calibration.py @@ -0,0 +1,74 @@ +import torch +import torch.nn as nn + + +class PeakGuidedCalibrationModule(nn.Module): + + def __init__( + self, + rgb_dim: int, + residual_dim: int, + tau_rgb: float = 0.5, + tau_res: float = 0.5, + ): + super().__init__() + + # Phi_Linear: maps each [D]-dim patch token to a scalar score. + self.rgb_score_head = nn.Linear(rgb_dim, 1) + nn.init.zeros_(self.rgb_score_head.weight) + nn.init.zeros_(self.rgb_score_head.bias) + + # Phi_Conv: 1x1 conv reducing residual feature map to a 1-channel score map. + self.residual_score_head = nn.Conv2d( + residual_dim, 1, kernel_size=1, stride=1, padding=0 + ) + nn.init.zeros_(self.residual_score_head.weight) + if self.residual_score_head.bias is not None: + nn.init.zeros_(self.residual_score_head.bias) + + # Learnable scalar modulating the RGB aggregate (paper Eq. 4). + self.lambda_rgb = nn.Parameter(torch.tensor(1.0)) + + # Fixed temperatures (paper hyper-parameters, not learned). + if tau_rgb <= 0.0 or tau_res <= 0.0: + raise ValueError( + f"tau_rgb and tau_res must be > 0, got {tau_rgb} / {tau_res}" + ) + self.tau_rgb = float(tau_rgb) + self.tau_res = float(tau_res) + + @staticmethod + def peak_aggregation(scores: torch.Tensor, tau: float) -> torch.Tensor: + + if scores.dim() != 2: + raise ValueError(f"Expected [B, N] scores, got {list(scores.shape)}") + + n = scores.size(1) + if n == 0: + # Empty patch grid: aggregate is zero (no evidence). + return scores.new_zeros((scores.size(0), 1)) + + if tau <= 0.0: + raise ValueError(f"tau must be > 0, got {tau}") + + log_n = scores.new_tensor(float(n)).log() + z = tau * (torch.logsumexp(scores / tau, dim=1) - log_n) + return z.unsqueeze(1) + + def forward( + self, + f_rgb_tokens: torch.Tensor, + f_residual_map: torch.Tensor, + ) -> torch.Tensor: + + # ---- RGB stream: per-patch scores ---- + s_rgb = self.rgb_score_head(f_rgb_tokens).squeeze(-1) # [B, N] + z_rgb = self.peak_aggregation(s_rgb, self.tau_rgb) # [B, 1] + + # ---- Residual stream: per-spatial-location scores ---- + s_res = self.residual_score_head(f_residual_map).flatten(1) # [B, Hr*Wr] + z_res = self.peak_aggregation(s_res, self.tau_res) # [B, 1] + + # ---- Fusion (paper Eq. 4) ---- + z_local = z_res + self.lambda_rgb * z_rgb + return z_local diff --git a/detectors/PGC/upstream/test.py b/detectors/PGC/upstream/test.py new file mode 100644 index 0000000000000000000000000000000000000000..aa7feea53890cdf195eae032e542f8cc613d7479 --- /dev/null +++ b/detectors/PGC/upstream/test.py @@ -0,0 +1,63 @@ +import torch + +from data.eval_dataset import UniversalFakeDetectDataset +from data.transforms import MEAN, STD, create_eval_transforms +from engine.evaluator import evaluate_model +from models.pgc import PGCNetwork +from utils.cli import build_test_parser, parse_devices +from utils.logging_utils import log_test_config, setup_logging +from utils.metrics import compute_mean_metrics, log_metrics + + +def main(): + # ---------------- CLI parsing & global setup ---------------- + parser = build_test_parser() + args = parser.parse_args() + + devices, device = parse_devices(args.devices) + args.devices = devices + + logger_inst, log_path = setup_logging(args.checkpoints_dir, args.name, log_type='test') + logger_inst.info('Logging to file: %s', log_path) + log_test_config(logger_inst, args) + logger_inst.info('Using device: %s', device) + + # ---------------- Build dataset + transform ---------------- + transform = create_eval_transforms( + image_size=args.cropSize, mean=MEAN['dino'], std=STD['dino'], + ) + logger_inst.info('Loading test dataset: %s', args.test_root) + dataset = UniversalFakeDetectDataset(args.test_root, transform=transform) + + # ---------------- Build & load model ---------------- + model = PGCNetwork( + dino_variant=args.dino_variant, + lora_rank=args.lora_rank, + lora_alpha=args.lora_alpha, + lora_dropout=args.lora_dropout, + lora_targets=['attn.qkv', 'attn.proj', 'mlp.fc1', 'mlp.fc2'], + pretrained_root=args.dino_pretrained_root, + tau_rgb=args.tau_rgb, + tau_res=args.tau_res, + ) + logger_inst.info('Loading checkpoint: %s', args.checkpoint) + state = torch.load(args.checkpoint, map_location=device) + model.load_state_dict(state['model']) + model.to(device).eval() + + # ---------------- Evaluation ---------------- + logger_inst.info('Starting evaluation...') + subset_metrics, _overall_micro = evaluate_model( + model=model, + device=device, + dataset=dataset, + batch_size=args.batch_size, + num_workers=args.num_workers, + ) + mean_metrics = compute_mean_metrics(subset_metrics) + log_metrics(mean_metrics, 'Overall test set mean') + logger_inst.info('Evaluation completed. Subsets evaluated: %d', len(subset_metrics)) + + +if __name__ == '__main__': + main() diff --git a/detectors/PGC/upstream/train.py b/detectors/PGC/upstream/train.py new file mode 100644 index 0000000000000000000000000000000000000000..1dac3502aedb8bbdbbf76eb5406f52384445b455 --- /dev/null +++ b/detectors/PGC/upstream/train.py @@ -0,0 +1,159 @@ +import logging +import time + +import numpy as np + +from data.dataloader import create_dataloader +from data.eval_dataset import UniversalFakeDetectDataset +from data.transforms import MEAN, STD, create_eval_transforms +from engine.evaluator import evaluate_model +from engine.trainer import PGCTrainer +from utils.cli import build_train_parser, finalize_opt +from utils.logging_utils import log_training_config, setup_logging +from utils.metrics import compute_mean_metrics, log_metrics +from utils.seed import set_seed + + +logger = logging.getLogger(__name__) + + +def _build_test_datasets(opt, eval_transform): + test_datasets = {} + if opt.test_root is not None: + test_datasets['Universal'] = UniversalFakeDetectDataset( + opt.test_root, transform=eval_transform, + ) + return test_datasets + + +def _evaluate_all_datasets(trainer, opt, test_datasets, logger_inst): + all_mean_accs = [] + all_mean_aps = [] + for ds_name, ds in test_datasets.items(): + logger_inst.info('>>> Evaluating on %s dataset', ds_name) + subset_metrics, overall = evaluate_model( + model=trainer.model, + device=trainer.device, + dataset=ds, + batch_size=opt.eval_batch_size, + num_workers=opt.eval_num_threads, + ) + mean_metrics = compute_mean_metrics(subset_metrics) + # Macro-mean ACC / AP across subsets; fall back to overall when NaN. + ds_mean_acc = mean_metrics.get('acc', float('nan')) + if np.isnan(ds_mean_acc): + ds_mean_acc = overall.get('acc', float('-inf')) + ds_mean_ap = mean_metrics.get('ap', float('nan')) + if np.isnan(ds_mean_ap): + ds_mean_ap = overall.get('ap', float('-inf')) + all_mean_accs.append(ds_mean_acc) + all_mean_aps.append(ds_mean_ap) + log_metrics(mean_metrics, f' {ds_name} mean') + + def _aggregate(values): + valid = [v for v in values if not np.isnan(v) and v != float('-inf')] + if len(valid) == 0: + return float('-inf') + return float(np.mean(valid)) + + return _aggregate(all_mean_accs), _aggregate(all_mean_aps) + + +def _format_checkpoint_name(step: int, acc: float, ap: float) -> str: + def _percent(value: float) -> int: + if np.isnan(value) or value == float('-inf') or value == float('inf'): + return 0 + return int(round(value * 100)) + + return f'step{step}_acc{_percent(acc)}_ap{_percent(ap)}.pth' + + +def main(): + # ---------------- CLI parsing & global setup ---------------- + parser = build_train_parser() + opt = parser.parse_args() + opt_message = finalize_opt(opt) # writes opt.txt, sets opt.device + opt.isTrain + set_seed(opt.seed) + + logger_inst, log_path = setup_logging(opt.checkpoints_dir, opt.name, log_type='train') + logger_inst.info('Logging to file: %s', log_path) + logger_inst.info('\n%s', opt_message) + log_training_config(logger_inst, opt) + + # ---------------- Build trainer + dataloaders ---------------- + trainer = PGCTrainer(opt) + data_loader = create_dataloader(opt) + + eval_transform = create_eval_transforms( + image_size=opt.cropSize, mean=MEAN['dino'], std=STD['dino'], + ) + test_datasets = _build_test_datasets(opt, eval_transform) + if len(test_datasets) == 0: + logger_inst.info('No test datasets provided; skipping per-step evaluation.') + + total_steps = opt.niter * len(data_loader) + trainer.setup_scheduler(total_steps) + logger_inst.info( + 'Total training steps: %d (epochs=%d, batches/epoch=%d)', + total_steps, opt.niter, len(data_loader), + ) + + # ---------------- Training loop ---------------- + best_mean_ap = float('-inf') + start_time = time.time() + + for epoch in range(opt.niter): + for batch in data_loader: + trainer.set_input(batch) + trainer.optimize_parameters() + + if trainer.total_steps % 100 == 0: + elapsed = time.time() - start_time + logger_inst.info( + 'Step: %d | Loss: %.4f | Avg Time/Step: %.4fs', + trainer.total_steps, + trainer.loss.detach().item(), + elapsed / trainer.total_steps, + ) + + if len(test_datasets) > 0 and trainer.total_steps % opt.eval_every_steps == 0: + logger_inst.info('=' * 80) + logger_inst.info('Evaluating model at step %d', trainer.total_steps) + logger_inst.info('=' * 80) + + trainer.eval() + overall_acc, overall_map = _evaluate_all_datasets( + trainer, opt, test_datasets, logger_inst, + ) + logger_inst.info( + 'Overall mean ACC: %.4f | Overall mean AP: %.4f', + overall_acc, overall_map, + ) + + if overall_map > best_mean_ap: + best_mean_ap = overall_map + logger_inst.info( + 'New best model (mean AP=%.4f); saving best.pth', overall_map, + ) + trainer.save_networks('best.pth') + + + ckpt_name = _format_checkpoint_name( + trainer.total_steps, overall_acc, overall_map, + ) + logger_inst.info( + 'Saving evaluation checkpoint: %s ' + '(step=%d, mean ACC=%.4f, mean AP=%.4f)', + ckpt_name, trainer.total_steps, overall_acc, overall_map, + ) + trainer.save_networks(ckpt_name) + + trainer.train() + + trainer.finalize_epoch() + + logger_inst.info('Training finished. Best mean AP: %.4f', best_mean_ap) + + +if __name__ == '__main__': + main() diff --git a/detectors/PGC/upstream/utils/__init__.py b/detectors/PGC/upstream/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d1d4af24c2c0a065d44de08b978cc0520c42f36 --- /dev/null +++ b/detectors/PGC/upstream/utils/__init__.py @@ -0,0 +1,63 @@ +"""Project-wide utilities for the PGC pipeline. + +Re-exports the symbols the entry points (:mod:`train` and :mod:`test`) +import directly: + +- CLI: :func:`build_train_parser`, :func:`build_test_parser`, + :func:`parse_devices`, :func:`finalize_opt`, :func:`cli_message_for_opt` +- Logging: :func:`setup_logging`, :func:`log_training_config`, + :func:`log_test_config` +- Metrics: :func:`compute_accuracy`, :func:`compute_real_accuracy`, + :func:`compute_fake_accuracy`, :func:`compute_average_precision`, + :func:`compute_auc`, :func:`compute_all_metrics`, + :func:`compute_mean_metrics`, :func:`log_metrics` +- Reproducibility: :func:`set_seed` +""" + +from .cli import ( + build_test_parser, + build_train_parser, + cli_message_for_opt, + finalize_opt, + parse_devices, +) +from .logging_utils import ( + log_test_config, + log_training_config, + setup_logging, +) +from .metrics import ( + compute_accuracy, + compute_all_metrics, + compute_auc, + compute_average_precision, + compute_fake_accuracy, + compute_mean_metrics, + compute_real_accuracy, + log_metrics, +) +from .seed import set_seed + +__all__ = [ + # CLI + "build_train_parser", + "build_test_parser", + "cli_message_for_opt", + "finalize_opt", + "parse_devices", + # Logging + "setup_logging", + "log_training_config", + "log_test_config", + # Metrics + "compute_accuracy", + "compute_real_accuracy", + "compute_fake_accuracy", + "compute_average_precision", + "compute_auc", + "compute_all_metrics", + "compute_mean_metrics", + "log_metrics", + # Reproducibility + "set_seed", +] diff --git a/detectors/PGC/upstream/utils/cli.py b/detectors/PGC/upstream/utils/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..6818da969f95fad2414cf5c2b765d004bc8c8572 --- /dev/null +++ b/detectors/PGC/upstream/utils/cli.py @@ -0,0 +1,401 @@ +import argparse +import os +from typing import List, Tuple + +import torch + +# Choices for ``--dino_variant``. Centralised so train and test cannot drift. +DINO_CHOICES = [ + "dinov2-base", + "dinov2-large", + "dinov2-giant", + "dinov3-vitb16-pretrain-lvd1689m", +] + +# Choices for ``--optim``. +OPTIM_CHOICES = ["adam", "sgd"] + + +def build_train_parser() -> argparse.ArgumentParser: + """Construct the training CLI parser. + + Every option used anywhere in the training pipeline is registered here + with a sensible default; downstream modules access them directly via + attribute lookup. + """ + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + description="PGC (Peak-Guided Calibration) training CLI", + ) + + # ----- Identity / I/O ------------------------------------------------- + parser.add_argument( + "--name", + type=str, + default="pgc_train", + help="Experiment name (also used as log filename stem).", + ) + parser.add_argument( + "--checkpoints_dir", + type=str, + default="checkpoints", + help="Directory under which logs and checkpoints are written.", + ) + parser.add_argument( + "--devices", + type=str, + default="3", + help=( + "CUDA devices, e.g. '0' or '0,1'; '-1' for CPU. " + "RTX 4090 #3 is the test box." + ), + ) + parser.add_argument( + "--num_threads", + type=int, + default=8, + help="Number of DataLoader worker processes for training.", + ) + parser.add_argument( + "--batch_size", + type=int, + default=32, + help="Training batch size.", + ) + + # ----- DINO backbone & LoRA ------------------------------------------- + parser.add_argument( + "--dino_variant", + type=str, + default="dinov2-large", + choices=DINO_CHOICES, + help="DINO backbone variant.", + ) + parser.add_argument( + "--dino_pretrained_root", + type=str, + default=None, + help=( + "Root directory containing local DINO checkpoints. " + "When set, the loader expects subfolders named after the variant. " + "Required for training; entry-point validates explicitly." + ), + ) + parser.add_argument( + "--lora_rank", + type=int, + default=8, + help="LoRA rank for adapter layers.", + ) + parser.add_argument( + "--lora_alpha", + type=float, + default=1.0, + help="LoRA scaling factor (alpha / rank determines effective scale).", + ) + parser.add_argument( + "--lora_dropout", + type=float, + default=0.1, + help="Dropout probability inside LoRA adapter layers.", + ) + + # ----- Training data --------------------------------------------------- + # ``--real_image_dir`` and ``--fake_image_dir`` both accept *one or more* + # root directories (``nargs='+'``). ``RealFakeDataset`` scans every + # supplied directory, concatenates the samples and performs a global + # ``random.shuffle`` so that every mini-batch can freely mix sources. + parser.add_argument( + "--real_image_dir", + type=str, + nargs="+", + default=None, + help=( + "One or more root directories of real training images. " + "Example: --real_image_dir /path/A /path/B. All directories are " + "scanned recursively and the resulting samples are merged + " + "shuffled before training." + ), + ) + parser.add_argument( + "--fake_image_dir", + type=str, + nargs="+", + default=None, + help=( + "One or more root directories of fake / generated training " + "images. Example: --fake_image_dir /path/A /path/B. All " + "directories are scanned recursively and the resulting samples " + "are merged + shuffled before training." + ), + ) + parser.add_argument( + "--cropSize", + type=int, + default=224, + help="Pad-then-crop input resolution (square).", + ) + + # ----- Mid-training evaluation ---------------------------------------- + parser.add_argument( + "--test_root", + type=str, + default=None, + help=( + "Optional root directory of the evaluation dataset " + "(UniversalFakeDetect layout: ``//{0_real,1_fake}``). " + "If supplied the trainer evaluates on it periodically." + ), + ) + parser.add_argument( + "--eval_batch_size", + type=int, + default=32, + help="Batch size used during mid-training evaluation.", + ) + parser.add_argument( + "--eval_num_threads", + type=int, + default=8, + help="DataLoader workers for mid-training evaluation.", + ) + + # ----- Optimization ---------------------------------------------------- + parser.add_argument( + "--niter", + type=int, + default=100, + help="Total number of training epochs.", + ) + parser.add_argument( + "--lr", + type=float, + default=5e-5, + help="Initial learning rate.", + ) + parser.add_argument( + "--optim", + type=str, + default="adam", + choices=OPTIM_CHOICES, + help="Optimizer family.", + ) + parser.add_argument( + "--accumulation_steps", + type=int, + default=4, + help="Gradient accumulation steps.", + ) + parser.add_argument( + "--weight_decay", + type=float, + default=0.05, + help="L2 regularization strength.", + ) + parser.add_argument( + "--label_smoothing", + type=float, + default=0.1, + help="Label-smoothing epsilon for binary cross-entropy.", + ) + + # ----- PGCM (Peak-Guided Calibration Module) hyper-parameters --------- + parser.add_argument( + "--tau_rgb", + type=float, + default=0.5, + help="Temperature for the RGB-stream peak aggregation in PGCM.", + ) + parser.add_argument( + "--tau_res", + type=float, + default=0.5, + help="Temperature for the residual-stream peak aggregation in PGCM.", + ) + + # ----- Stability / reproducibility ------------------------------------ + parser.add_argument( + "--max_grad_norm", + type=float, + default=1.0, + help="Maximum L2 norm for gradient clipping (0 to disable).", + ) + parser.add_argument( + "--seed", + type=int, + default=42, + help="Random seed for Python, NumPy and PyTorch.", + ) + + # ----- Bookkeeping ----------------------------------------------------- + parser.add_argument( + "--eval_every_steps", + type=int, + default=200, + help=( + "Run mid-training evaluation every N optimization steps. " + "A checkpoint named " + "``step{N}_acc{int}_ap{int}.pth`` is also saved right after " + "each such evaluation (in addition to the best-AP ``best.pth``)." + ), + ) + + # Internal flag used by ``finalize_opt`` to know which parser produced + # the namespace. Not exposed as a CLI option (no ``add_argument``). + parser.set_defaults(isTrain=True) + + return parser + + +def build_test_parser() -> argparse.ArgumentParser: + """Construct the inference / evaluation CLI parser.""" + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + description="PGC (Peak-Guided Calibration) test CLI", + ) + + parser.add_argument( + "--checkpoint", + type=str, + required=True, + help="Path to the trained model checkpoint (.pth).", + ) + parser.add_argument( + "--test_root", + type=str, + required=True, + help="Root directory of the evaluation dataset.", + ) + parser.add_argument( + "--checkpoints_dir", + type=str, + default="checkpoints", + help="Directory under which the test log file is written.", + ) + parser.add_argument( + "--name", + type=str, + default="pgc_test", + help="Experiment name used to derive the test log filename.", + ) + parser.add_argument( + "--batch_size", + type=int, + default=32, + help="Evaluation batch size.", + ) + parser.add_argument( + "--num_workers", + type=int, + default=8, + help="DataLoader worker processes for evaluation.", + ) + parser.add_argument( + "--devices", + type=str, + default="3", + help=( + "CUDA devices, e.g. '0' or '0,1'; '-1' for CPU. " + "RTX 4090 #3 is the test box." + ), + ) + + parser.add_argument( + "--cropSize", + type=int, + default=224, + help="Pad-then-crop input resolution (must match training).", + ) + parser.add_argument( + "--dino_variant", + type=str, + default="dinov2-large", + choices=DINO_CHOICES, + help="DINO backbone variant (must match training).", + ) + parser.add_argument( + "--lora_rank", + type=int, + default=8, + help="LoRA rank (must match training).", + ) + parser.add_argument( + "--lora_alpha", + type=float, + default=1.0, + help="LoRA alpha (must match training).", + ) + parser.add_argument( + "--lora_dropout", + type=float, + default=0.1, + help="LoRA dropout (must match training).", + ) + parser.add_argument( + "--dino_pretrained_root", + type=str, + default=None, + help="Root directory containing local DINO checkpoints.", + ) + parser.add_argument( + "--tau_rgb", + type=float, + default=0.5, + help="PGCM RGB-stream temperature (must match training).", + ) + parser.add_argument( + "--tau_res", + type=float, + default=0.5, + help="PGCM residual-stream temperature (must match training).", + ) + + parser.set_defaults(isTrain=False) + + return parser + + +def parse_devices(devices_str: str) -> Tuple[List[int], torch.device]: + + str_ids = [s for s in devices_str.split(",") if s.strip() != ""] + parsed_ids = [int(x) for x in str_ids] + valid_ids = [i for i in parsed_ids if i >= 0] + + if torch.cuda.is_available() and len(valid_ids) > 0: + return valid_ids, torch.device(f"cuda:{valid_ids[0]}") + return [], torch.device("cpu") + + +def cli_message_for_opt( + parser: argparse.ArgumentParser, opt: argparse.Namespace +) -> str: + + message = "----------------- Options ---------------\n" + for k, v in sorted(vars(opt).items()): + if k.startswith("_"): + continue + default = parser.get_default(k) + comment = f"\t[default: {default}]" if v != default else "" + message += "{:>25}: {:<30}{}\n".format(str(k), str(v), comment) + message += "----------------- End -------------------" + return message + + +def finalize_opt(opt: argparse.Namespace) -> str: + + parser = build_train_parser() if opt.isTrain else build_test_parser() + + message = cli_message_for_opt(parser, opt) + + expr_dir = os.path.join(opt.checkpoints_dir, opt.name) + os.makedirs(expr_dir, exist_ok=True) + with open(os.path.join(expr_dir, "opt.txt"), "wt") as opt_file: + opt_file.write(message + "\n") + + devices_list, device = parse_devices(opt.devices) + opt.devices = devices_list + opt.device = device + if torch.cuda.is_available() and len(devices_list) > 0: + torch.cuda.set_device(devices_list[0]) + + return message diff --git a/detectors/PGC/upstream/utils/logging_utils.py b/detectors/PGC/upstream/utils/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..720dde37b93f15dc1a9029a32ab5e95696fd171b --- /dev/null +++ b/detectors/PGC/upstream/utils/logging_utils.py @@ -0,0 +1,100 @@ + +import logging +import os +from typing import Tuple + + +def setup_logging( + checkpoints_dir: str, + exp_name: str, + level: int = logging.INFO, + log_type: str = "train", +) -> Tuple[logging.Logger, str]: + + os.makedirs(checkpoints_dir, exist_ok=True) + + if log_type == "test": + log_file = os.path.join(checkpoints_dir, f"{exp_name}_test.log") + else: + log_file = os.path.join(checkpoints_dir, f"{exp_name}.log") + + root_logger = logging.getLogger() + root_logger.setLevel(level) + + if root_logger.handlers: + root_logger.handlers.clear() + + formatter = logging.Formatter( + "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + ) + + file_handler = logging.FileHandler(log_file) + file_handler.setLevel(level) + file_handler.setFormatter(formatter) + + stream_handler = logging.StreamHandler() + stream_handler.setLevel(level) + stream_handler.setFormatter(formatter) + + root_logger.addHandler(file_handler) + root_logger.addHandler(stream_handler) + + return root_logger, log_file + + +def log_training_config(logger: logging.Logger, opt) -> None: + """Log the training configuration in a structured, human-readable form. + + All field accesses are direct: every attribute below is guaranteed to be + populated by :func:`utils.cli.build_train_parser`. + """ + logger.info("==== Training configuration ====") + logger.info("Name: %s", opt.name) + logger.info("Checkpoints dir: %s", opt.checkpoints_dir) + logger.info("Devices: %s", opt.devices) + logger.info("Batch size: %d", opt.batch_size) + logger.info("Learning rate: %.6f", opt.lr) + logger.info("Optimizer: %s", opt.optim) + logger.info("Weight decay: %.4f", opt.weight_decay) + logger.info("Label smoothing: %.2f", opt.label_smoothing) + logger.info("Number of epochs: %d", opt.niter) + logger.info("Crop size: %d", opt.cropSize) + logger.info("DINO variant: %s", opt.dino_variant) + logger.info("LoRA rank: %d", opt.lora_rank) + logger.info("LoRA alpha: %.2f", opt.lora_alpha) + logger.info("LoRA dropout: %.2f", opt.lora_dropout) + logger.info("Real image dirs (%d):", len(opt.real_image_dir)) + for idx, real_dir in enumerate(opt.real_image_dir): + logger.info(" [%d] %s", idx, real_dir) + logger.info("Fake image dirs (%d):", len(opt.fake_image_dir)) + for idx, fake_dir in enumerate(opt.fake_image_dir): + logger.info(" [%d] %s", idx, fake_dir) + logger.info("Test root: %s", opt.test_root) + logger.info("DINO pretrained root: %s", opt.dino_pretrained_root) + logger.info("PGCM tau (RGB): %.4f", opt.tau_rgb) + logger.info("PGCM tau (Residual): %.4f", opt.tau_res) + logger.info("Accumulation steps: %d", opt.accumulation_steps) + logger.info("Max grad norm: %.4f", opt.max_grad_norm) + logger.info("Seed: %d", opt.seed) + + +def log_test_config(logger: logging.Logger, args) -> None: + """Log the test configuration in a structured, human-readable form. + + All attribute accesses are direct (guaranteed by + :func:`utils.cli.build_test_parser`). + """ + logger.info("==== Test configuration ====") + logger.info("Checkpoint: %s", args.checkpoint) + logger.info("Test root: %s", args.test_root) + logger.info("Batch size: %d", args.batch_size) + logger.info("Num workers: %d", args.num_workers) + logger.info("Devices: %s", args.devices) + logger.info("Crop size: %d", args.cropSize) + logger.info("DINO variant: %s", args.dino_variant) + logger.info("LoRA rank: %d", args.lora_rank) + logger.info("LoRA alpha: %.2f", args.lora_alpha) + logger.info("LoRA dropout: %.2f", args.lora_dropout) + logger.info("DINO pretrained root: %s", args.dino_pretrained_root) + logger.info("PGCM tau (RGB): %.4f", args.tau_rgb) + logger.info("PGCM tau (Residual): %.4f", args.tau_res) diff --git a/detectors/PGC/upstream/utils/metrics.py b/detectors/PGC/upstream/utils/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..0314fdd5c0bae78af1957e5ef10ac6da70ddf780 --- /dev/null +++ b/detectors/PGC/upstream/utils/metrics.py @@ -0,0 +1,139 @@ +import logging +from typing import Dict + +import numpy as np +from sklearn.metrics import ( + accuracy_score, + average_precision_score, + roc_auc_score, +) + + +logger = logging.getLogger(__name__) + + +def compute_accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float: + """Compute plain (overall) accuracy.""" + return float(accuracy_score(y_true, y_pred)) + + +def compute_real_accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float: + """Accuracy on real samples (label = 0). + + Returns NaN when y_true contains no real samples. + """ + mask = (y_true == 0) + if mask.sum() == 0: + return float("nan") + return float((y_pred[mask] == 0).mean()) + + +def compute_fake_accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float: + """Accuracy on fake samples (label = 1). + + Returns NaN when y_true contains no fake samples. + """ + mask = (y_true == 1) + if mask.sum() == 0: + return float("nan") + return float((y_pred[mask] == 1).mean()) + + +def compute_average_precision(y_true: np.ndarray, y_score: np.ndarray) -> float: + """Compute average precision (AP). + + Returns NaN if only one class is present in ``y_true`` (AP is undefined + in that case). + """ + if np.unique(y_true).size < 2: + return float("nan") + return float(average_precision_score(y_true, y_score)) + + +def compute_auc(y_true: np.ndarray, y_score: np.ndarray) -> float: + """Compute ROC AUC. + + Returns NaN if only one class is present, or if scikit-learn raises a + ValueError (degenerate cases such as all-identical scores). + """ + if np.unique(y_true).size < 2: + return float("nan") + try: + return float(roc_auc_score(y_true, y_score)) + except ValueError: + return float("nan") + + +def compute_all_metrics( + y_true: np.ndarray, y_score: np.ndarray, threshold: float = 0.5 +) -> Dict[str, float]: + """Compute the full metric bundle (acc, real_acc, fake_acc, ap, auc). + + Args: + y_true: Ground-truth labels in {0, 1}. 0 = real, 1 = fake. + y_score: Predicted "fake" probability for each sample. + threshold: Probability threshold used to derive hard predictions for + the accuracy-style metrics. Defaults to 0.5. + + Returns: + Dict with keys ``acc``, ``real_acc``, ``fake_acc``, ``ap``, ``auc``. + When ``y_true`` is empty, every value is NaN. + """ + if y_true.size == 0: + return { + "acc": float("nan"), + "real_acc": float("nan"), + "fake_acc": float("nan"), + "ap": float("nan"), + "auc": float("nan"), + } + + y_pred = (y_score >= threshold).astype(np.int32) + + return { + "acc": compute_accuracy(y_true, y_pred), + "real_acc": compute_real_accuracy(y_true, y_pred), + "fake_acc": compute_fake_accuracy(y_true, y_pred), + "ap": compute_average_precision(y_true, y_score), + "auc": compute_auc(y_true, y_score), + } + + +def compute_mean_metrics( + metrics_per_subset: Dict[str, Dict[str, float]], +) -> Dict[str, float]: + """Compute macro-mean metrics across subsets (each subset weighs equally). + + Note: + If any subset has NaN for a metric (e.g., AP/AUC when only one class + is present), the corresponding mean becomes NaN as well. This is + intentional and matches the original implementation. + """ + metric_names = ["acc", "real_acc", "fake_acc", "ap", "auc"] + mean_metrics: Dict[str, float] = {} + + for metric_name in metric_names: + values = [ + m.get(metric_name, float("nan")) for m in metrics_per_subset.values() + ] + if values: + mean_metrics[metric_name] = float(np.mean(values)) + else: + mean_metrics[metric_name] = float("nan") + + return mean_metrics + + +def log_metrics(metrics: Dict[str, float], prefix: str = "") -> None: + + if prefix: + prefix = f"{prefix} - " + + logger.info( + f"{prefix}ACC: %.4f | Real_ACC: %.4f | Fake_ACC: %.4f | AP: %.4f | AUC: %.4f", + metrics.get("acc", float("nan")), + metrics.get("real_acc", float("nan")), + metrics.get("fake_acc", float("nan")), + metrics.get("ap", float("nan")), + metrics.get("auc", float("nan")), + ) diff --git a/detectors/PGC/upstream/utils/seed.py b/detectors/PGC/upstream/utils/seed.py new file mode 100644 index 0000000000000000000000000000000000000000..ed80ef5f9eecd325798d2c81aa510e6127e1047d --- /dev/null +++ b/detectors/PGC/upstream/utils/seed.py @@ -0,0 +1,15 @@ +import random + +import numpy as np +import torch + + +def set_seed(seed: int) -> None: + + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False diff --git a/detectors/R50_TF/__pycache__/dataset.cpython-310.pyc b/detectors/R50_TF/__pycache__/dataset.cpython-310.pyc deleted file mode 100644 index 6c5c95f9e55daf8380f684667d5e09b1f6d1e84d..0000000000000000000000000000000000000000 Binary files a/detectors/R50_TF/__pycache__/dataset.cpython-310.pyc and /dev/null differ diff --git a/detectors/R50_TF/__pycache__/networks.cpython-310.pyc b/detectors/R50_TF/__pycache__/networks.cpython-310.pyc index 7f489f9eca04368007d0a9ffce269534031ecbd7..c3e191d4079f8c98c53342d5d52641535058698c 100644 Binary files a/detectors/R50_TF/__pycache__/networks.cpython-310.pyc and b/detectors/R50_TF/__pycache__/networks.cpython-310.pyc differ diff --git a/detectors/R50_TF/__pycache__/parser.cpython-310.pyc b/detectors/R50_TF/__pycache__/parser.cpython-310.pyc deleted file mode 100644 index 191b3de4fdbe5fb1b586c0356a921135589e4fec..0000000000000000000000000000000000000000 Binary files a/detectors/R50_TF/__pycache__/parser.cpython-310.pyc and /dev/null differ diff --git a/detectors/R50_nodown/__pycache__/parser.cpython-310.pyc b/detectors/R50_nodown/__pycache__/parser.cpython-310.pyc deleted file mode 100644 index 219216103853b96f2df7267915787e313cec91de..0000000000000000000000000000000000000000 Binary files a/detectors/R50_nodown/__pycache__/parser.cpython-310.pyc and /dev/null differ diff --git a/detectors/R50_nodown/networks/__pycache__/__init__.cpython-310.pyc b/detectors/R50_nodown/networks/__pycache__/__init__.cpython-310.pyc index 353695416df7e3579d8f1f5ece1906aaaa57cd1a..8813438f4fa32e917de7f4d54f11cf8ab507c1f5 100644 Binary files a/detectors/R50_nodown/networks/__pycache__/__init__.cpython-310.pyc and b/detectors/R50_nodown/networks/__pycache__/__init__.cpython-310.pyc differ diff --git a/detectors/R50_nodown/networks/__pycache__/resnet_mod.cpython-310.pyc b/detectors/R50_nodown/networks/__pycache__/resnet_mod.cpython-310.pyc index 8118e766ecc58dab7ddc909dce2aee43547a20a9..51487b2eced09cd758dce531c4736ee539314bef 100644 Binary files a/detectors/R50_nodown/networks/__pycache__/resnet_mod.cpython-310.pyc and b/detectors/R50_nodown/networks/__pycache__/resnet_mod.cpython-310.pyc differ diff --git a/detectors/R50_nodown/utils/__pycache__/__init__.cpython-310.pyc b/detectors/R50_nodown/utils/__pycache__/__init__.cpython-310.pyc deleted file mode 100644 index 8a57bc3013222ed8ce71c4485f4d09e0388c7a2c..0000000000000000000000000000000000000000 Binary files a/detectors/R50_nodown/utils/__pycache__/__init__.cpython-310.pyc and /dev/null differ diff --git a/detectors/R50_nodown/utils/__pycache__/dataset.cpython-310.pyc b/detectors/R50_nodown/utils/__pycache__/dataset.cpython-310.pyc deleted file mode 100644 index 7903678031e8f0165e793c04be418bd520a6b162..0000000000000000000000000000000000000000 Binary files a/detectors/R50_nodown/utils/__pycache__/dataset.cpython-310.pyc and /dev/null differ diff --git a/detectors/R50_nodown/utils/__pycache__/processing.cpython-310.pyc b/detectors/R50_nodown/utils/__pycache__/processing.cpython-310.pyc deleted file mode 100644 index 7f47b8da283d8c7f50a7216955c2b559118aff5d..0000000000000000000000000000000000000000 Binary files a/detectors/R50_nodown/utils/__pycache__/processing.cpython-310.pyc and /dev/null differ diff --git a/detectors/R50_nodown/utils/__pycache__/training.cpython-310.pyc b/detectors/R50_nodown/utils/__pycache__/training.cpython-310.pyc deleted file mode 100644 index 9981de2663cdac2868363e5a76915623cf377c84..0000000000000000000000000000000000000000 Binary files a/detectors/R50_nodown/utils/__pycache__/training.cpython-310.pyc and /dev/null differ diff --git a/download_weights.py b/download_weights.py index 24cdf869cf0f55fbf3d7fd29a3cce8bee5ee2d0d..f0578e868cecffb2da8df3dee4c56ce400c656e9 100644 --- a/download_weights.py +++ b/download_weights.py @@ -1,66 +1,37 @@ """ Download model weights for Hugging Face Spaces deployment. -This script downloads model weights on first run if they're not present. -""" -import os -import urllib.request -import ssl - -# Bypass SSL verification for downloads -try: - _create_unverified_https_context = ssl._create_unverified_context -except AttributeError: - pass -else: - ssl._create_default_https_context = _create_unverified_https_context +R50_TF, R50_nodown, CLIP-D, P2G and NPR ship their weights via Git LFS. +PGC, ForensicConcept and MDMF use the official pre-trained weights and +backbones (about 4 GB), which are fetched from their original sources and +checksum-verified on first start. +""" +import subprocess +import sys +from pathlib import Path -def download_file(url, dest_path): - """Download a file from URL to destination path.""" - os.makedirs(os.path.dirname(dest_path), exist_ok=True) - - if os.path.exists(dest_path): - print(f"โœ“ {dest_path} already exists") - return - - print(f"Downloading {os.path.basename(dest_path)}...") - try: - urllib.request.urlretrieve(url, dest_path) - print(f"โœ“ Downloaded {dest_path}") - except Exception as e: - print(f"โœ— Failed to download {dest_path}: {e}") - +ROOT = Path(__file__).resolve().parent -# Model weights URLs (update these with actual URLs) -WEIGHTS_URLS = { - "R50_TF": "https://drive.google.com/uc?export=download&id=YOUR_GOOGLE_DRIVE_ID", # Replace - "R50_nodown": "https://drive.google.com/uc?export=download&id=YOUR_GOOGLE_DRIVE_ID", # Replace - "CLIP-D": "https://drive.google.com/uc?export=download&id=YOUR_GOOGLE_DRIVE_ID", # Replace - "P2G": "https://drive.google.com/uc?export=download&id=YOUR_GOOGLE_DRIVE_ID", # Replace - "NPR": "https://drive.google.com/uc?export=download&id=YOUR_GOOGLE_DRIVE_ID", # Replace +REQUIRED = { + "PGC": ["checkpoint/pretrained/weights/best.pt", "checkpoint/backbones/dinov2-large/model.safetensors"], + "ForensicConcept": ["checkpoint/pretrained/weights/best.pt", "checkpoint/backbones/ViT-L-14.pt", + "upstream/codebooks/cleandift_codebook.npy"], + "MDMF": ["checkpoint/pretrained/weights/best.pt", "checkpoint/backbones/dinov2-large/config.json"], } def download_all_weights(): - """Download all model weights if not present.""" - print("Checking model weights...") - - for model_name, url in WEIGHTS_URLS.items(): - dest_path = f"detectors/{model_name}/checkpoint/pretrained/weights/best.pt" - - # Skip if URL not configured - if "YOUR_GOOGLE_DRIVE_ID" in url: - print(f"โš  Skipping {model_name}: URL not configured") + for method, files in REQUIRED.items(): + base = ROOT / "detectors" / method + if all((base / f).exists() for f in files): + print(f"โœ“ {method} weights present") continue - - download_file(url, dest_path) - - # Download P2G classes.pkl - classes_url = "https://github.com/laitifranz/Prompt2Guard/raw/main/src/utils/classes.pkl" - classes_path = "detectors/P2G/src/utils/classes.pkl" - download_file(classes_url, classes_path) - - print("\nWeight check complete!") + print(f"Downloading official weights for {method}...") + try: + subprocess.run([sys.executable, str(ROOT / "support" / "setup_recent_weights.py"), method], + check=True, cwd=ROOT) + except Exception as e: + print(f"โœ— Failed to set up {method}: {e}") if __name__ == "__main__": diff --git a/requirements.txt b/requirements.txt index 36cc1cc681f68da8767694557cb45704bc96f8af..e1dd9ad671c6bee037b59b96a4dce51898138933 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ # ML / DL Frameworks torch>=2.5.0 torchvision>=0.20.0 -transformers +transformers>=4.57,<5 # PGC official weights need the transformers 4.x DINOv2 key names # ML/DL Helpers einops==0.8.0 @@ -12,7 +12,7 @@ opencv-python-headless==4.10.0.84 pandas==2.2.3 scikit-image==0.22.0 scikit-learn==1.5.2 -numpy<2.0 +numpy<2 matplotlib # MLOps & Infrastructure @@ -21,7 +21,10 @@ wandb==0.16.6 # Utilities PyYAML==6.0.2 tqdm==4.67.1 -albumentations +albumentations>=1.4.24,<2 +kornia>=0.8,<0.9 +scipy +huggingface_hub ftfy open-clip-torch diff --git a/support/__pycache__/detect.cpython-310.pyc b/support/__pycache__/detect.cpython-310.pyc index 9090c38125c4fde18644e1432b3f08530d09f904..f0783e5a95b98341d3d9684df436ad17def92545 100644 Binary files a/support/__pycache__/detect.cpython-310.pyc and b/support/__pycache__/detect.cpython-310.pyc differ diff --git a/support/__pycache__/detect_utils.cpython-310.pyc b/support/__pycache__/detect_utils.cpython-310.pyc index 1a80cf7318e01408f995058f09d3868decad57c1..52b5f6dadd6a5a31ec81c796b035405bce2da783 100644 Binary files a/support/__pycache__/detect_utils.cpython-310.pyc and b/support/__pycache__/detect_utils.cpython-310.pyc differ diff --git a/support/detect.py b/support/detect.py index 4b928ac2268b848cc5186ab947f84580abe23572..35b92033b6c8dac50a0b9195739adfeeed367c7b 100644 --- a/support/detect.py +++ b/support/detect.py @@ -3,28 +3,9 @@ import json import sys import yaml import subprocess +import shlex from datetime import datetime -def get_gpus(): - from numpy import argwhere, asarray, diff - import re - smi = os.popen('nvidia-smi').readlines() - div = re.compile('[+]-{3,}[+]|[|]={3,}[|]') - dividers = argwhere([div.match(line) != None for line in smi])[-2:, 0] - processes = [line for line in smi[dividers[0]+1:dividers[1]] if ' C ' in line] - free = list(set([process.split()[1] for process in processes]) ^ set([str(0), str(1)])) - - udiv = re.compile('[|]={3,}[+]={3,}[+]={3,}[|]') - ldiv = re.compile('[+]-{3,}[+]-{3,}[+]-{3,}[+]') - divider_up = argwhere([udiv.match(line) != None for line in smi])[0,0] - divider_down = argwhere([ldiv.match(line) != None for line in smi])[-1, 0] - - gpus = [line for line in smi[divider_up+1:divider_down] if '%' in line and 'MiB' in line] - gpus = [gpu.split('|')[2].replace(' ', '').replace('MiB', '').split('/') for gpu in gpus] - memory = diff(asarray(gpus).astype(int), axis=1).squeeze() - - return free, memory - def load_config(config_path): """Load configuration from YAML file.""" with open(config_path, 'r') as f: @@ -47,17 +28,10 @@ def run_detect(args): global_config = config.get('global', {}) # Set device - if hasattr(args, 'device') and args.device: - device = args.device - else: - device = global_config.get('device_override') - - if not device or device == "null": - _, memory = get_gpus() - if len(memory) > 0: - device = f"cuda:{memory.argmax()}" - else: - device = "cpu" + device = args.device or global_config.get('device_override') or 'auto' + if device in ('null', '', 'auto') and not args.dry_run: + import torch + device = 'cuda:0' if torch.cuda.is_available() else 'cpu' # Set up output path for results if not args.output: @@ -75,23 +49,25 @@ def run_detect(args): if not os.path.exists(detect_script): raise FileNotFoundError(f"Detector {args.detector} does not support single image detection") - cmd_args = [ - sys.executable, - detect_script, - f'--image "{args.image}"', - f'--device {device}', - f'--output "{args.output}"' - ] + cmd_args = [sys.executable, detect_script, '--image', os.path.abspath(args.image), + '--device', device, '--output', os.path.abspath(args.output)] # Add model path if specified if args.weights: - cmd_args.append(f'--model "{args.weights}"') + cmd_args.extend(['--model', args.weights]) + if args.detector in ('PGC', 'ForensicConcept', 'MDMF') and args.batch_size: + cmd_args.extend(['--batch_size', str(args.batch_size)]) - cmd = ' '.join(cmd_args) + cmd = shlex.join(cmd_args) print(f"Running detection with {args.detector}...") - if not args.dry_run: - subprocess.run(cmd, shell=True)#, check=True) + if args.dry_run: + print(cmd) + else: + os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True) + subprocess.run(cmd_args, check=True) + if not os.path.isfile(args.output): + raise RuntimeError(f"Detector completed without writing a result: {args.output}") # Print results if available if os.path.exists(args.output): @@ -99,6 +75,10 @@ def run_detect(args): result = json.load(f) print("\nDetection Results:") print(f"Prediction: {result['prediction']}") - print(f"Confidence: {result['confidence']:.4f}") + if 'fake_score' not in result: + result['fake_score'] = result['confidence'] + with open(args.output, 'w') as handle: + json.dump(result, handle, indent=2) + print(f"Fake score: {result['fake_score']:.4f}") print(f"Time: {result['elapsed_time']:.3f}s") - print(f"\nFull results saved to: {args.output}") \ No newline at end of file + print(f"\nFull results saved to: {args.output}") diff --git a/support/detect_utils.py b/support/detect_utils.py index a9a8250a6e05eb53ec1837a43e155c7d1d0e6376..319122e05644b5958c9804c2a54e74c3fe8db2b7 100644 --- a/support/detect_utils.py +++ b/support/detect_utils.py @@ -54,11 +54,10 @@ def save_result(result, output_path): """Save detection result to JSON file. Args: - result (dict): Detection result dictionary + result (dict): Detection result to save output_path (str): Path to save the JSON file """ - if os.path.dirname(output_path): - os.makedirs(os.path.dirname(output_path), exist_ok=True) + os.makedirs(os.path.dirname(output_path), exist_ok=True) with open(output_path, 'w') as f: json.dump(result, f, indent=2) diff --git a/support/recent_common.py b/support/recent_common.py new file mode 100644 index 0000000000000000000000000000000000000000..218ab8231094bd8f63eca8a336cea382587b23ab --- /dev/null +++ b/support/recent_common.py @@ -0,0 +1,92 @@ +"""Shared CLI and reporting helpers for the 2026 detector adapters.""" + +import argparse +import csv +import json +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + + +def parser(method, task): + p = argparse.ArgumentParser(description=f"{method} {task}") + p.add_argument("--name", default="pretrained") + p.add_argument("--device", default="auto") + p.add_argument("--batch_size", type=int, default=4) + p.add_argument("--num_threads", type=int, default=0) + if task == "detect": + p.add_argument("--image", required=True) + p.add_argument("--model", default=None) + p.add_argument("--output") + else: + p.add_argument("--task", default=task) + p.add_argument("--data_root", required=True) + p.add_argument("--split_file", required=True) + p.add_argument("--data_keys", required=True) + p.add_argument("--epochs", type=int, default=1) + p.add_argument("--max_steps", type=int, default=0) + return p + + +def device_for(spec): + import torch + if spec in (None, "auto"): + spec = "cuda:0" if torch.cuda.is_available() else "cpu" + device = torch.device(spec) + if device.type == "cuda" and not torch.cuda.is_available(): + raise RuntimeError(f"Requested {spec}, but CUDA is unavailable") + if device.type == "mps" and not torch.backends.mps.is_available(): + raise RuntimeError("Requested MPS, but it is unavailable") + return device + + +def validate_inputs(args, task): + if task == "detect": + if not Path(args.image).is_file(): + raise FileNotFoundError(f"Image not found: {args.image}") + else: + if not Path(args.data_root).is_dir(): + raise FileNotFoundError(f"Dataset directory not found: {args.data_root}") + if not Path(args.split_file).is_file(): + raise FileNotFoundError(f"Split file not found: {args.split_file}") + if args.batch_size < 1: + raise ValueError("--batch_size must be at least 1") + + +def checkpoint(method, name): + path = ROOT / "detectors" / method / "checkpoint" / name / "weights" / "best.pt" + if not path.is_file(): + raise FileNotFoundError(f"Checkpoint missing: {path}. Run support/setup_recent_weights.py or train first.") + return path + + +def detection_result(method, image, raw_score, fake_score, elapsed, output=None): + result = {"detector": method, "image": str(Path(image).resolve()), + "prediction": "fake" if fake_score >= 0.5 else "real", + "fake_score": float(fake_score), "confidence": float(max(fake_score, 1 - fake_score)), + "raw_score": float(raw_score), "elapsed_time": float(elapsed)} + path = Path(output) if output else ROOT / "detection_results" / method / "detect" / (Path(image).stem + ".json") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result, indent=2)) + return result + + +def write_results(method, name, keys, rows): + directory = ROOT / "detectors" / method / "results" / name / keys.replace(":", "-").replace("&", "_") + directory.mkdir(parents=True, exist_ok=True) + with (directory / "results.csv").open("w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=["path", "label", "raw_score", "fake_score", "prediction", "elapsed_time"]) + writer.writeheader() + writer.writerows(rows) + print(f"Wrote {len(rows)} rows to {directory / 'results.csv'}") + + +def timed_score(score_fn, path): + start = time.perf_counter() + raw, fake = score_fn(path) + return raw, fake, time.perf_counter() - start diff --git a/support/recent_data.py b/support/recent_data.py new file mode 100644 index 0000000000000000000000000000000000000000..704449be61730d8a89978fa35121d58b93f6f952 --- /dev/null +++ b/support/recent_data.py @@ -0,0 +1,76 @@ +"""Resolve DeepShield split IDs into labeled image paths for recent detectors.""" + +import json +import os +from pathlib import Path + + +GENERATOR_KEYS = { + "gan1": "StyleGAN", "gan2": "StyleGAN2", "gan3": "StyleGAN3", + "sd15": "StableDiffusion1.5", "sd2": "StableDiffusion2", + "sd3": "StableDiffusion3", "sdXL": "StableDiffusionXL", + "flux": "FLUX.1", "realFFHQ": "FFHQ", "realFORLAB": "FORLAB", +} +SOCIAL_KEYS = {"pre": "PreSocial", "fb": "Facebook", "tl": "Telegram", "tw": "X"} +EXTENSIONS = (".png", ".jpg", ".jpeg", ".webp", ".bmp") + + +def _selected(keys): + pairs = [] + for item in keys.split("&"): + generator, social = item.split(":", 1) + generators = GENERATOR_KEYS.values() if generator == "all" else ( + ["FFHQ", "FORLAB"] if generator == "real" else [GENERATOR_KEYS[generator]] + ) + socials = SOCIAL_KEYS.values() if social == "all" else ( + [SOCIAL_KEYS[k] for k in ("fb", "tl", "tw")] if social == "shr" else [SOCIAL_KEYS[social]] + ) + pairs.extend((g, s) for g in generators for s in socials) + return set(pairs) + + +def samples(data_root, split_file, split, keys): + """Return (absolute path, 0-real/1-fake) without crossing split boundaries.""" + root = Path(data_root).expanduser().resolve() + if not root.is_dir(): + raise FileNotFoundError(f"Dataset directory not found: {root}") + with open(split_file, encoding="utf-8") as handle: + ids = set(json.load(handle)[split]) + selected = _selected(keys) + found = [] + for social_dir in root.iterdir(): + if not social_dir.is_dir(): + continue + for label_dir in social_dir.iterdir(): + if label_dir.name not in ("Real", "Fake") or not label_dir.is_dir(): + continue + for current, _, filenames in os.walk(label_dir, followlinks=True): + for filename in filenames: + path = Path(current) / filename + if not path.is_file() or path.suffix.lower() not in EXTENSIONS: + continue + rel = path.relative_to(label_dir) + if (rel.parts[0], social_dir.name) not in selected: + continue + if rel.with_suffix("").as_posix() in ids: + found.append((path.resolve(), int(label_dir.name == "Fake"))) + if not found: + raise ValueError(f"No {split} images matched {keys!r} under {root}") + return sorted(found, key=lambda item: str(item[0])) + + +def stage(root, split, entries): + """Create an ImageFolder-compatible view with links to the original images.""" + root = Path(root) + counts = {0: 0, 1: 0} + for path, label in entries: + target = root / split / ("1_fake" if label else "0_real") / f"{counts[label]:08d}{path.suffix.lower()}" + target.parent.mkdir(parents=True, exist_ok=True) + if target.is_symlink() and target.resolve() == path: + counts[label] += 1 + continue + if target.exists() or target.is_symlink(): + target.unlink() + target.symlink_to(path) + counts[label] += 1 + return root / split diff --git a/support/setup_recent_weights.py b/support/setup_recent_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..1cb2d5647158a3a12d55acae172b5ebaa0c70fe1 --- /dev/null +++ b/support/setup_recent_weights.py @@ -0,0 +1,125 @@ +"""Fetch pinned published detector checkpoints and their original backbones.""" + +import argparse +import hashlib +import json +import shutil +import urllib.request +from pathlib import Path + +from huggingface_hub import hf_hub_download, snapshot_download + + +ROOT = Path(__file__).resolve().parents[1] +PGC_REV = "86424d6502f143c84a9df91f8336d2da07d0e235" +FC_REV = "ee3ed528de85ed44b4fcb4657e1df44955ed463c" +DINO_REV = "47b73eefe95e8d44ec3623f8890bd894b6ea2d6c" +MDMF_REV = "22d03f49d877b8a01d730284b5f73df555f5656f" +MDMF_SHA256 = "b9ae92006dcc837066eec8c8a9a26133f64281d6f6713e9eb6e0ccdc213f76dc" +CODEBOOK_SHA256 = "0a7cd9555750c5f08b1db0a5a2dc0d866ef195fcd05210bffe53b2c82cdc87ab" +CLIP_URL = "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt" +UPSTREAM_REVISIONS = { + "PGC": "0c9b10f3b89964b804ad6097e61709f74e827fbf", + "ForensicConcept": "1a57fbcd5212a113341b7377f307897509e13f0d", + "MDMF": MDMF_REV, +} + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + h.update(chunk) + return h.hexdigest() + + +def copy_verified(source, target, expected=None): + target.parent.mkdir(parents=True, exist_ok=True) + if not target.is_file() or (expected and digest(target) != expected and Path(source) != target): + shutil.copyfile(source, target) + if target.stat().st_size == 0: + raise ValueError(f"Empty weight file: {target}") + checksum = digest(target) + if expected and checksum != expected: + raise ValueError(f"Checksum mismatch for {target}: {checksum}") + return checksum + + +def hf_file(repo, revision, file, target): + source = hf_hub_download(repo_id=repo, revision=revision, filename=file) + return copy_verified(Path(source), target, digest(source)) + + +def download(url, target, expected=None): + target.parent.mkdir(parents=True, exist_ok=True) + if not target.is_file() or (expected and digest(target) != expected): + temporary = target.with_suffix(target.suffix + ".part") + urllib.request.urlretrieve(url, temporary) + temporary.replace(target) + return copy_verified(target, target, expected) + + +def dino_backbone(method): + primary = ROOT / "detectors" / "PGC" / "checkpoint" / "backbones" / "dinov2-large" + if not (primary / "config.json").is_file() or not (primary / "model.safetensors").is_file(): + source = Path(snapshot_download(repo_id="facebook/dinov2-large", revision=DINO_REV, + allow_patterns=["config.json", "preprocessor_config.json", "model.safetensors"])) + primary.mkdir(parents=True, exist_ok=True) + for file in source.iterdir(): + if file.is_file(): + copy_verified(file, primary / file.name, digest(file)) + if not (primary / "model.safetensors").is_file(): + raise FileNotFoundError(f"DINOv2 model weights missing under {primary}") + if method == "MDMF": + link = ROOT / "detectors" / "MDMF" / "checkpoint" / "backbones" / "dinov2-large" + link.parent.mkdir(parents=True, exist_ok=True) + if not link.exists(): + link.symlink_to(primary, target_is_directory=True) + return {str(p.relative_to(ROOT)): digest(p) for p in primary.iterdir() if p.is_file()} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("method", choices=["PGC", "ForensicConcept", "MDMF", "all"]) + args = parser.parse_args() + methods = ["PGC", "ForensicConcept", "MDMF"] if args.method == "all" else [args.method] + for method in methods: + base = ROOT / "detectors" / method / "checkpoint" + files = {} + if method in ("PGC", "MDMF"): + files.update(dino_backbone(method)) + if method == "PGC": + path = base / "pretrained" / "weights" / "best.pt" + files[str(path.relative_to(ROOT))] = hf_file("xiaoyuzhou68/PGC_ckpt", PGC_REV, + "PGC_train_progan_sdv1_4_ckpt.pth", path) + source = f"https://huggingface.co/xiaoyuzhou68/PGC_ckpt/tree/{PGC_REV}" + license_name = "Apache-2.0" + elif method == "ForensicConcept": + path = base / "pretrained" / "weights" / "best.pt" + files[str(path.relative_to(ROOT))] = hf_file("ethan225/ForensicConcept", FC_REV, + "weights/detectors/clip_vitl14_codebook_stage2.pth", path) + clip = base / "backbones" / "ViT-L-14.pt" + files[str(clip.relative_to(ROOT))] = download(CLIP_URL, clip, + "b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836") + codebook = ROOT / "detectors" / method / "upstream" / "codebooks" / "cleandift_codebook.npy" + codebook_url = (f"https://raw.githubusercontent.com/EthanAdamm/FORENSICCONCEPT/" + f"{UPSTREAM_REVISIONS[method]}/assets/codebooks/cleandift_codebook.npy") + files[str(codebook.relative_to(ROOT))] = download(codebook_url, codebook, CODEBOOK_SHA256) + source = f"https://huggingface.co/ethan225/ForensicConcept/tree/{FC_REV}" + license_name = "Apache-2.0 detector; MIT OpenAI CLIP backbone" + else: + path = base / "pretrained" / "weights" / "best.pt" + url = f"https://raw.githubusercontent.com/ZBox1005/MDMF/{MDMF_REV}/checkpoints/model.pth" + files[str(path.relative_to(ROOT))] = download(url, path, MDMF_SHA256) + source = f"https://github.com/ZBox1005/MDMF/tree/{MDMF_REV}" + license_name = "MIT" + record = {"method": method, "source": source, "upstream_code_revision": UPSTREAM_REVISIONS[method], + "license": license_name, + "backbone": f"facebook/dinov2-large@{DINO_REV}" if method != "ForensicConcept" else CLIP_URL, + "sha256": files} + (base / "weights-manifest.json").write_text(json.dumps(record, indent=2) + "\n") + print(f"Verified {method}: {len(files)} files; manifest: {base / 'weights-manifest.json'}") + + +if __name__ == "__main__": + main()