AMontiB commited on
Commit
c55595d
·
1 Parent(s): 84d58e0

Add utilities and CLI for PGC pipeline

Browse files

- Introduced project-wide utilities in `detectors/PGC/upstream/utils/__init__.py` for easier access to common functions.
- Implemented CLI argument parsers in `detectors/PGC/upstream/utils/cli.py` for training and testing configurations.
- Added logging utilities in `detectors/PGC/upstream/utils/logging_utils.py` to facilitate structured logging of training and testing configurations.
- Created metrics computation functions in `detectors/PGC/upstream/utils/metrics.py` for evaluating model performance.
- Implemented seed setting functionality in `detectors/PGC/upstream/utils/seed.py` to ensure reproducibility.
- Developed shared CLI and reporting helpers in `support/recent_common.py` for detector adapters.
- Resolved image paths for recent detectors in `support/recent_data.py` to facilitate dataset handling.
- Added functionality to fetch and verify weights in `support/setup_recent_weights.py` for model checkpoints.

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +11 -0
  2. README.md +6 -5
  3. README_HF.md +6 -5
  4. __pycache__/app.cpython-310.pyc +0 -0
  5. app.py +31 -73
  6. configs/ForensicConcept.yaml +15 -0
  7. configs/MDMF.yaml +15 -0
  8. configs/PGC.yaml +15 -0
  9. detectors/CLIP-D/__pycache__/parser.cpython-310.pyc +0 -0
  10. detectors/CLIP-D/networks/__pycache__/__init__.cpython-310.pyc +0 -0
  11. detectors/CLIP-D/networks/__pycache__/openclipnet.cpython-310.pyc +0 -0
  12. detectors/CLIP-D/networks/__pycache__/resnet_mod.cpython-310.pyc +0 -0
  13. detectors/CLIP-D/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  14. detectors/CLIP-D/utils/__pycache__/dataset.cpython-310.pyc +0 -0
  15. detectors/CLIP-D/utils/__pycache__/processing.cpython-310.pyc +0 -0
  16. detectors/CLIP-D/utils/__pycache__/training.cpython-310.pyc +0 -0
  17. detectors/ForensicConcept/detect.py +4 -0
  18. detectors/ForensicConcept/run.py +134 -0
  19. detectors/ForensicConcept/test.py +4 -0
  20. detectors/ForensicConcept/train.py +4 -0
  21. detectors/ForensicConcept/upstream/LICENSE +201 -0
  22. detectors/ForensicConcept/upstream/THIRD_PARTY_NOTICES.md +30 -0
  23. detectors/ForensicConcept/upstream/aug_utils_train/__init__.py +1 -0
  24. detectors/ForensicConcept/upstream/aug_utils_train/distortions.py +192 -0
  25. detectors/ForensicConcept/upstream/aug_utils_train/utils_data.py +113 -0
  26. detectors/ForensicConcept/upstream/aug_utils_train/utils_distortions.py +281 -0
  27. detectors/ForensicConcept/upstream/codebooks/README.md +13 -0
  28. detectors/ForensicConcept/upstream/codebooks/cleandift_codebook.npy +3 -0
  29. detectors/ForensicConcept/upstream/config_loader.py +619 -0
  30. detectors/ForensicConcept/upstream/configs/clip_codebook.yaml +85 -0
  31. detectors/ForensicConcept/upstream/configs/clip_lora.yaml +68 -0
  32. detectors/ForensicConcept/upstream/configs/dinov3_concept.yaml +88 -0
  33. detectors/ForensicConcept/upstream/configs/dinov3_lora.yaml +76 -0
  34. detectors/ForensicConcept/upstream/data/__init__.py +580 -0
  35. detectors/ForensicConcept/upstream/data/datasets.py +967 -0
  36. detectors/ForensicConcept/upstream/models/__init__.py +23 -0
  37. detectors/ForensicConcept/upstream/models/clip/__init__.py +2 -0
  38. detectors/ForensicConcept/upstream/models/clip/bpe_simple_vocab_16e6.txt.gz +3 -0
  39. detectors/ForensicConcept/upstream/models/clip/clip.py +248 -0
  40. detectors/ForensicConcept/upstream/models/clip/loratorch/__init__.py +4 -0
  41. detectors/ForensicConcept/upstream/models/clip/loratorch/layers.py +584 -0
  42. detectors/ForensicConcept/upstream/models/clip/loratorch/utils.py +60 -0
  43. detectors/ForensicConcept/upstream/models/clip/model.py +775 -0
  44. detectors/ForensicConcept/upstream/models/clip/simple_tokenizer.py +132 -0
  45. detectors/ForensicConcept/upstream/models/clip_models.py +276 -0
  46. detectors/ForensicConcept/upstream/networks/__init__.py +0 -0
  47. detectors/ForensicConcept/upstream/networks/base_model.py +273 -0
  48. detectors/ForensicConcept/upstream/networks/dinov3_detector.py +753 -0
  49. detectors/ForensicConcept/upstream/networks/trainer.py +513 -0
  50. detectors/ForensicConcept/upstream/options/__init__.py +0 -0
.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ # Downloaded at startup by download_weights.py (official sources)
4
+ detectors/PGC/checkpoint/
5
+ detectors/ForensicConcept/checkpoint/
6
+ detectors/MDMF/checkpoint/backbones/
7
+ detectors/MDMF/checkpoint/pretrained/weights/best.pt
8
+ detectors/MDMF/checkpoint/pretrained/weights/*.part
9
+ detectors/*/checkpoint/weights-manifest.json
10
+ detection_results/
11
+ .venv/
README.md CHANGED
@@ -27,12 +27,15 @@ This demonstrator is designed as an open-source contribution to the community. W
27
 
28
  ## 🛠️ Available Detectors
29
 
30
- * **ALL**: Runs all available detectors sequentially. Produces a Weighted Majority Vote verdict based on confident predictions (> 0.6) and generates a Confidence Plot.
31
  * **R50_TF**: ResNet-50 based detector trained on the TrueFake dataset.
32
  * **R50_nodown**: ResNet-50 without downsampling operations.
33
  * **CLIP-D**: CLIP-based deepfake detector.
34
  * **P2G**: Prompt2Guard: Conditioned prompt-optimization for continual deepfake detection.
35
  * **NPR**: Neural Posterior Regularization.
 
 
 
36
 
37
  ## 🚀 Usage Guide
38
 
@@ -46,13 +49,11 @@ This demonstrator is designed as an open-source contribution to the community. W
46
  * **Elapsed Time**: The time the model needed to make the prediction (excluding preprocessing or model building).
47
 
48
  **Understanding the Results produced by "ALL":**
49
- * Produces a **Weighted Majority Vote** verdict (Real/Fake).
50
- * 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.
51
- * 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.
52
 
53
  ## 🧠 Training Data Overview
54
 
55
- All open-source models featured in this Space have been pretrained using the **[DeepShield dataset](https://zenodo.org/records/15648378)**:
56
  * **Fake Images:** Generated using StyleGAN 2 and Stable Diffusion XL.
57
  * **Real Images:** Sourced from the FFHQ Dataset and the FORLAB Dataset.
58
 
 
27
 
28
  ## 🛠️ Available Detectors
29
 
30
+ * **ALL**: Runs all available detectors sequentially. Shows the result of each detector and generates a Confidence Plot.
31
  * **R50_TF**: ResNet-50 based detector trained on the TrueFake dataset.
32
  * **R50_nodown**: ResNet-50 without downsampling operations.
33
  * **CLIP-D**: CLIP-based deepfake detector.
34
  * **P2G**: Prompt2Guard: Conditioned prompt-optimization for continual deepfake detection.
35
  * **NPR**: Neural Posterior Regularization.
36
+ * **PGC**: Peak-guided calibration on DINOv2-L (official pre-trained weights).
37
+ * **ForensicConcept**: CLIP ViT-L/14 with a forensic concept codebook (official pre-trained weights).
38
+ * **MDMF**: Local distribution shift (MMD) on DINOv2-L patch embeddings (official pre-trained weights; reference bank and threshold computed on DeepShield data).
39
 
40
  ## 🚀 Usage Guide
41
 
 
49
  * **Elapsed Time**: The time the model needed to make the prediction (excluding preprocessing or model building).
50
 
51
  **Understanding the Results produced by "ALL":**
52
+ * 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.
 
 
53
 
54
  ## 🧠 Training Data Overview
55
 
56
+ R50_TF, R50_nodown, CLIP-D, P2G and NPR have been pretrained using the **[DeepShield dataset](https://zenodo.org/records/15648378)**:
57
  * **Fake Images:** Generated using StyleGAN 2 and Stable Diffusion XL.
58
  * **Real Images:** Sourced from the FFHQ Dataset and the FORLAB Dataset.
59
 
README_HF.md CHANGED
@@ -27,12 +27,15 @@ This demonstrator is designed as an open-source contribution to the community. W
27
 
28
  ## 🛠️ Available Detectors
29
 
30
- * **ALL**: Runs all available detectors sequentially. Produces a Weighted Majority Vote verdict based on confident predictions (> 0.6) and generates a Confidence Plot.
31
  * **R50_TF**: ResNet-50 based detector trained on the TrueFake dataset.
32
  * **R50_nodown**: ResNet-50 without downsampling operations.
33
  * **CLIP-D**: CLIP-based deepfake detector.
34
  * **P2G**: Prompt2Guard: Conditioned prompt-optimization for continual deepfake detection.
35
  * **NPR**: Neural Posterior Regularization.
 
 
 
36
 
37
  ## 🚀 Usage Guide
38
 
@@ -46,13 +49,11 @@ This demonstrator is designed as an open-source contribution to the community. W
46
  * **Elapsed Time**: The time the model needed to make the prediction (excluding preprocessing or model building).
47
 
48
  **Understanding the Results produced by "ALL":**
49
- * Produces a **Weighted Majority Vote** verdict (Real/Fake).
50
- * 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.
51
- * 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.
52
 
53
  ## 🧠 Training Data Overview
54
 
55
- All open-source models featured in this Space have been pretrained using the **[DeepShield dataset](https://zenodo.org/records/15648378)**:
56
  * **Fake Images:** Generated using StyleGAN 2 and Stable Diffusion XL.
57
  * **Real Images:** Sourced from the FFHQ Dataset and the FORLAB Dataset.
58
 
 
27
 
28
  ## 🛠️ Available Detectors
29
 
30
+ * **ALL**: Runs all available detectors sequentially. Shows the result of each detector and generates a Confidence Plot.
31
  * **R50_TF**: ResNet-50 based detector trained on the TrueFake dataset.
32
  * **R50_nodown**: ResNet-50 without downsampling operations.
33
  * **CLIP-D**: CLIP-based deepfake detector.
34
  * **P2G**: Prompt2Guard: Conditioned prompt-optimization for continual deepfake detection.
35
  * **NPR**: Neural Posterior Regularization.
36
+ * **PGC**: Peak-guided calibration on DINOv2-L (official pre-trained weights).
37
+ * **ForensicConcept**: CLIP ViT-L/14 with a forensic concept codebook (official pre-trained weights).
38
+ * **MDMF**: Local distribution shift (MMD) on DINOv2-L patch embeddings (official pre-trained weights; reference bank and threshold computed on DeepShield data).
39
 
40
  ## 🚀 Usage Guide
41
 
 
49
  * **Elapsed Time**: The time the model needed to make the prediction (excluding preprocessing or model building).
50
 
51
  **Understanding the Results produced by "ALL":**
52
+ * 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.
 
 
53
 
54
  ## 🧠 Training Data Overview
55
 
56
+ R50_TF, R50_nodown, CLIP-D, P2G and NPR have been pretrained using the **[DeepShield dataset](https://zenodo.org/records/15648378)**:
57
  * **Fake Images:** Generated using StyleGAN 2 and Stable Diffusion XL.
58
  * **Real Images:** Sourced from the FFHQ Dataset and the FORLAB Dataset.
59
 
__pycache__/app.cpython-310.pyc DELETED
Binary file (13.4 kB)
 
app.py CHANGED
@@ -32,15 +32,8 @@ if os.environ.get("SPACE_ID"):
32
  print(f"Warning: Could not download weights: {e}")
33
 
34
  # Available detectors based on launcher.py
35
- DETECTORS = ['ALL', 'R50_TF', 'R50_nodown', 'CLIP-D', 'P2G', 'NPR']
36
 
37
- DETECTOR_WEIGHTS = {
38
- 'CLIP-D': 0.30,
39
- 'R50_TF': 0.25,
40
- 'R50_nodown': 0.20,
41
- 'P2G': 0.15,
42
- 'NPR': 0.10
43
- }
44
 
45
  def process_image(image_path):
46
  """
@@ -88,6 +81,7 @@ def run_single_detection(image_path, detector_name):
88
  output=output_path,
89
  weights='pretrained', # Use default/pretrained
90
  device='cpu', # Force CPU
 
91
  dry_run=False,
92
  verbose=False
93
  )
@@ -144,76 +138,43 @@ def predict(image_path, detector_name):
144
  if not results:
145
  return "Error: No results obtained from detectors.", None
146
 
147
- votes_real = 0.0
148
- votes_fake = 0.0
149
- total_weight_used = 0.0
150
  confidences = []
151
  labels = []
152
  colors = []
153
-
 
154
  for det, res in results:
155
  pred = res.get('prediction', 'Unknown')
156
- raw_conf = res.get('confidence', 0.0)
157
-
158
- # Calculate display confidence (confidence of the prediction)
 
159
  if pred == 'fake':
160
  score = raw_conf
161
  color = 'red'
162
  else:
163
  score = 1 - raw_conf
164
  color = 'green'
165
-
166
  labels.append(det)
167
  confidences.append(score)
168
  colors.append(color)
169
-
170
- # Weighted Voting logic
171
- # Only count vote if confidence > 0.6
172
- if score > 0.6:
173
- weight = DETECTOR_WEIGHTS.get(det, 0.0)
174
- if pred == 'fake':
175
- votes_fake += weight * score
176
- total_weight_used += weight
177
- elif pred == 'real':
178
- votes_real += weight * score
179
- total_weight_used += weight
180
-
181
- # Majority Voting
182
- if votes_real > votes_fake:
183
- verdict = "REAL"
184
- elif votes_fake > votes_real:
185
- verdict = "FAKE"
186
- else:
187
- verdict = "UNCERTAIN"
188
-
189
- # Calculate weighted average confidence
190
- if total_weight_used > 0:
191
- weighted_conf = (votes_real + votes_fake) / total_weight_used
192
- else:
193
- weighted_conf = 0.0
194
-
195
- # Explanation
196
- if verdict == "REAL":
197
- 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."
198
- elif verdict == "FAKE":
199
- 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."
200
- else:
201
- explanation = f"The result is uncertain. The detectors produced unconsistent results. The weighted confidence is {weighted_conf:.4f}."
202
-
203
  # Plotting
204
  fig, ax = plt.subplots(figsize=(10, 5))
205
  bars = ax.bar(labels, confidences, color=colors)
206
  ax.set_ylim(0, 1.05)
207
  ax.set_ylabel('Confidence')
208
  ax.set_title('Detector Confidence Scores')
209
- ax.axhline(y=0.6, color='gray', linestyle='--', alpha=0.5, label='Vote Threshold (0.6)')
210
 
211
  # Add custom legend for colors
212
  from matplotlib.patches import Patch
213
  legend_elements = [
214
  Patch(facecolor='green', label='Real'),
215
- Patch(facecolor='red', label='Fake'),
216
- ax.lines[0] # The threshold line
217
  ]
218
  ax.legend(handles=legend_elements)
219
 
@@ -233,7 +194,7 @@ def predict(image_path, detector_name):
233
 
234
  if res:
235
  prediction = res.get('prediction', 'Unknown')
236
- confidence = res.get('confidence', 0.0)
237
  elapsed_time = res.get('elapsed_time', 0.0)
238
 
239
  if prediction == 'fake':
@@ -290,10 +251,8 @@ with demo:
290
  * **Elapsed Time**: The time the model needed to make the prediction (excluding preprocessing or model building).
291
 
292
  ### The "ALL" Option
293
- * Runs all available detectors (R50_TF, R50_nodown, CLIP-D, P2G, NPR) sequentially on the input image.
294
- * 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.
295
- * You can find the specific weights used for each model in the **"⚖️ Weight Details"** menu below.
296
- * Also generates a **Confidence Plot** visualizing each model's score and a textual **Explanation** of the consensus.
297
  * In the plot, **Green** bars indicate a **Real** prediction, while **Red** bars indicate a **Fake** prediction.
298
  """)
299
 
@@ -318,24 +277,11 @@ with demo:
318
  )
319
  plot_output = gr.Plot(label="Confidence Scores")
320
 
321
- with gr.Accordion("⚖️ Weight Details", open=False):
322
- gr.Markdown(f"""
323
- ### **Detector Weights**
324
- 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.
325
- | Detector | Weight |
326
- | :--- | :---: |
327
- | **CLIP-D** | {DETECTOR_WEIGHTS['CLIP-D']:.2f} |
328
- | **R50_TF** | {DETECTOR_WEIGHTS['R50_TF']:.2f} |
329
- | **R50_nodown** | {DETECTOR_WEIGHTS['R50_nodown']:.2f} |
330
- | **P2G** | {DETECTOR_WEIGHTS['P2G']:.2f} |
331
- | **NPR** | {DETECTOR_WEIGHTS['NPR']:.2f} |
332
- """)
333
-
334
  with gr.Accordion("📚 Model Details", open=False):
335
  gr.Markdown("""
336
  ### **ALL**
337
- * **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).
338
- * **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.
339
 
340
  ### **R50_TF**
341
  * **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:
361
  * **Description**: Focuses on Neighboring Pixel Relationships (NPR) to capture generalized structural artifacts stemming from up-sampling operations in generative networks.
362
  * **Paper**: [Rethinking the Up-Sampling Operations in CNN-based Generative Network for Generalizable Deepfake Detection](https://arxiv.org/abs/2312.10461)
363
  * **Code**: [GitHub Repository](https://github.com/chuangchuangtan/NPR-DeepfakeDetection)
 
 
 
 
 
 
 
 
 
 
 
 
364
  """)
365
 
366
  gr.Markdown("""
 
32
  print(f"Warning: Could not download weights: {e}")
33
 
34
  # Available detectors based on launcher.py
35
+ DETECTORS = ['ALL', 'R50_TF', 'R50_nodown', 'CLIP-D', 'P2G', 'NPR', 'PGC', 'ForensicConcept', 'MDMF']
36
 
 
 
 
 
 
 
 
37
 
38
  def process_image(image_path):
39
  """
 
81
  output=output_path,
82
  weights='pretrained', # Use default/pretrained
83
  device='cpu', # Force CPU
84
+ batch_size=1,
85
  dry_run=False,
86
  verbose=False
87
  )
 
138
  if not results:
139
  return "Error: No results obtained from detectors.", None
140
 
 
 
 
141
  confidences = []
142
  labels = []
143
  colors = []
144
+ lines = []
145
+
146
  for det, res in results:
147
  pred = res.get('prediction', 'Unknown')
148
+ # fake_score = probability of fake for every detector (support/detect.py fills it in)
149
+ raw_conf = res.get('fake_score', res.get('confidence', 0.0))
150
+
151
+ # Display confidence (confidence of the prediction)
152
  if pred == 'fake':
153
  score = raw_conf
154
  color = 'red'
155
  else:
156
  score = 1 - raw_conf
157
  color = 'green'
158
+
159
  labels.append(det)
160
  confidences.append(score)
161
  colors.append(color)
162
+ lines.append(f"{det}: {pred} (confidence {score:.4f})")
163
+
164
+ explanation = "Results of each detector:\n" + "\n".join(lines)
165
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  # Plotting
167
  fig, ax = plt.subplots(figsize=(10, 5))
168
  bars = ax.bar(labels, confidences, color=colors)
169
  ax.set_ylim(0, 1.05)
170
  ax.set_ylabel('Confidence')
171
  ax.set_title('Detector Confidence Scores')
 
172
 
173
  # Add custom legend for colors
174
  from matplotlib.patches import Patch
175
  legend_elements = [
176
  Patch(facecolor='green', label='Real'),
177
+ Patch(facecolor='red', label='Fake')
 
178
  ]
179
  ax.legend(handles=legend_elements)
180
 
 
194
 
195
  if res:
196
  prediction = res.get('prediction', 'Unknown')
197
+ confidence = res.get('fake_score', res.get('confidence', 0.0))
198
  elapsed_time = res.get('elapsed_time', 0.0)
199
 
200
  if prediction == 'fake':
 
251
  * **Elapsed Time**: The time the model needed to make the prediction (excluding preprocessing or model building).
252
 
253
  ### The "ALL" Option
254
+ * Runs all available detectors (R50_TF, R50_nodown, CLIP-D, P2G, NPR, PGC, ForensicConcept, MDMF) sequentially on the input image.
255
+ * Lists the prediction and confidence of each detector and generates a **Confidence Plot** visualizing each model's score. No aggregated verdict is produced.
 
 
256
  * In the plot, **Green** bars indicate a **Real** prediction, while **Red** bars indicate a **Fake** prediction.
257
  """)
258
 
 
277
  )
278
  plot_output = gr.Plot(label="Confidence Scores")
279
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  with gr.Accordion("📚 Model Details", open=False):
281
  gr.Markdown("""
282
  ### **ALL**
283
+ * **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).
284
+ * **Results**: Shows the prediction of each detector and a **Confidence Plot** with each model's score (no aggregated verdict).
285
 
286
  ### **R50_TF**
287
  * **Description**: A ResNet50 architecture modified to exclude downsampling at the first layer. It uses "learned prototypes" in the classification head for robust detection.
 
307
  * **Description**: Focuses on Neighboring Pixel Relationships (NPR) to capture generalized structural artifacts stemming from up-sampling operations in generative networks.
308
  * **Paper**: [Rethinking the Up-Sampling Operations in CNN-based Generative Network for Generalizable Deepfake Detection](https://arxiv.org/abs/2312.10461)
309
  * **Code**: [GitHub Repository](https://github.com/chuangchuangtan/NPR-DeepfakeDetection)
310
+
311
+ ### **PGC**
312
+ * **Description**: Peak-guided calibration on a DINOv2-L backbone. Uses the **official pre-trained weights** released by the authors (not trained on DeepShield).
313
+ * **Weights**: [xiaoyuzhou68/PGC_ckpt](https://huggingface.co/xiaoyuzhou68/PGC_ckpt)
314
+
315
+ ### **ForensicConcept**
316
+ * **Description**: CLIP ViT-L/14 with a forensic concept codebook. Uses the **official pre-trained weights** released by the authors (not trained on DeepShield).
317
+ * **Weights**: [ethan225/ForensicConcept](https://huggingface.co/ethan225/ForensicConcept) · **Code**: [GitHub Repository](https://github.com/EthanAdamm/FORENSICCONCEPT)
318
+
319
+ ### **MDMF**
320
+ * **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.
321
+ * **Code**: [GitHub Repository](https://github.com/ZBox1005/MDMF)
322
  """)
323
 
324
  gr.Markdown("""
configs/ForensicConcept.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ global:
2
+ dataset_path: <PATH_TO_DATASET>
3
+ device_override: cpu
4
+ split_file: ./split.json
5
+ num_threads: 0
6
+ dry_run: false
7
+ only_list: false
8
+ detector_args: []
9
+ training:
10
+ - data: gan2:pre&sdXL:pre&realFFHQ:pre&realFORLAB:pre
11
+ testing:
12
+ - all:pre
13
+ - all:fb
14
+ - all:tl
15
+ - all:tw
configs/MDMF.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ global:
2
+ dataset_path: <PATH_TO_DATASET>
3
+ device_override: cpu
4
+ split_file: ./split.json
5
+ num_threads: 0
6
+ dry_run: false
7
+ only_list: false
8
+ detector_args: []
9
+ training:
10
+ - data: gan2:pre&sdXL:pre&realFFHQ:pre&realFORLAB:pre
11
+ testing:
12
+ - all:pre
13
+ - all:fb
14
+ - all:tl
15
+ - all:tw
configs/PGC.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ global:
2
+ dataset_path: <PATH_TO_DATASET>
3
+ device_override: cpu
4
+ split_file: ./split.json
5
+ num_threads: 0
6
+ dry_run: false
7
+ only_list: false
8
+ detector_args: []
9
+ training:
10
+ - data: gan2:pre&sdXL:pre&realFFHQ:pre&realFORLAB:pre
11
+ testing:
12
+ - all:pre
13
+ - all:fb
14
+ - all:tl
15
+ - all:tw
detectors/CLIP-D/__pycache__/parser.cpython-310.pyc DELETED
Binary file (1.3 kB)
 
detectors/CLIP-D/networks/__pycache__/__init__.cpython-310.pyc CHANGED
Binary files a/detectors/CLIP-D/networks/__pycache__/__init__.cpython-310.pyc and b/detectors/CLIP-D/networks/__pycache__/__init__.cpython-310.pyc differ
 
detectors/CLIP-D/networks/__pycache__/openclipnet.cpython-310.pyc CHANGED
Binary files a/detectors/CLIP-D/networks/__pycache__/openclipnet.cpython-310.pyc and b/detectors/CLIP-D/networks/__pycache__/openclipnet.cpython-310.pyc differ
 
detectors/CLIP-D/networks/__pycache__/resnet_mod.cpython-310.pyc CHANGED
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
 
detectors/CLIP-D/utils/__pycache__/__init__.cpython-310.pyc DELETED
Binary file (2.26 kB)
 
detectors/CLIP-D/utils/__pycache__/dataset.cpython-310.pyc DELETED
Binary file (5.22 kB)
 
detectors/CLIP-D/utils/__pycache__/processing.cpython-310.pyc DELETED
Binary file (3.5 kB)
 
detectors/CLIP-D/utils/__pycache__/training.cpython-310.pyc DELETED
Binary file (4.21 kB)
 
detectors/ForensicConcept/detect.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from run import main
2
+
3
+ if __name__ == "__main__":
4
+ main("detect")
detectors/ForensicConcept/run.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DeepShield adapter for the official ForensicConcept CLIP codebook model."""
2
+
3
+ import shutil
4
+ import sys
5
+ import tempfile
6
+ import time
7
+ from pathlib import Path
8
+
9
+ HERE = Path(__file__).resolve().parent
10
+ ROOT = HERE.parents[1]
11
+ sys.path[:0] = [str(ROOT), str(HERE / "upstream")]
12
+
13
+ import torch
14
+ from PIL import Image
15
+ from torchvision import transforms
16
+ from torch.utils.data import DataLoader
17
+
18
+ from config_loader import ConfigLoader
19
+ from data import get_dataset
20
+ from networks.trainer import Trainer
21
+ from support.recent_common import checkpoint, detection_result, device_for, parser, timed_score, validate_inputs, write_results
22
+ from support.recent_data import samples, stage
23
+
24
+
25
+ def configuration(name, device, batch_size, threads, *, train, dataroot=None, checkpoint_path=None):
26
+ config = ConfigLoader(str(HERE / "upstream" / "configs" / "clip_codebook.yaml"))
27
+ backbone = HERE / "checkpoint" / "backbones" / "ViT-L-14.pt"
28
+ codebook = HERE / "upstream" / "codebooks" / "cleandift_codebook.npy"
29
+ if not backbone.is_file():
30
+ raise FileNotFoundError(f"CLIP backbone missing: {backbone}; run support/setup_recent_weights.py ForensicConcept")
31
+ if not codebook.is_file():
32
+ raise FileNotFoundError(f"Codebook missing: {codebook}")
33
+ config.set("models.pretrained.clip_model", str(backbone))
34
+ config.set("models.checkpoints_dir", str(HERE / "checkpoint"))
35
+ config.set("training.clip_codebook_path", str(codebook))
36
+ config.set("training.name", name)
37
+ config.set("training.gpu_ids", device.index if device.type == "cuda" else -1)
38
+ config.set("training.batch_size", batch_size)
39
+ config.set("testing.batch_size", batch_size)
40
+ config.set("system.num_threads", threads)
41
+ config.set("training.continue_train", not train)
42
+ config.set("training.epoch", str(checkpoint_path) if checkpoint_path else "best")
43
+ config.set("logging.tensorboard", False)
44
+ if dataroot:
45
+ config.set("data.train_dataroot", str(dataroot))
46
+ config.set("data.train_split", "train")
47
+ return config
48
+
49
+
50
+ def load(name, device, batch_size, threads):
51
+ path = checkpoint("ForensicConcept", name)
52
+ config = configuration(name, device, batch_size, threads, train=False, checkpoint_path=path)
53
+ opt = config.to_namespace(is_train=False)
54
+ opt.local_rank = -1
55
+ return Trainer(opt).model.eval().to(device)
56
+
57
+
58
+ def eval_transform():
59
+ # The released CLIP codebook configuration uses legacy_preprocess=true.
60
+ # Its eval path is resize -> center crop -> ImageNet normalization.
61
+ return transforms.Compose([transforms.Resize((224, 224)), transforms.CenterCrop(224),
62
+ transforms.ToTensor(), transforms.Normalize([.485, .456, .406], [.229, .224, .225])])
63
+
64
+
65
+ def main(task):
66
+ args = parser("ForensicConcept", task).parse_args()
67
+ validate_inputs(args, task)
68
+ device = device_for(args.device)
69
+ name = args.model or args.name if task == "detect" else args.name
70
+ if task == "train":
71
+ entries = samples(args.data_root, args.split_file, "train", args.data_keys)
72
+ if {label for _, label in entries} != {0, 1}:
73
+ raise ValueError("ForensicConcept training needs real and fake images")
74
+ with tempfile.TemporaryDirectory(prefix="forensicconcept-") as temporary:
75
+ stage(temporary, "train", entries)
76
+ config = configuration(name, device, args.batch_size, args.num_threads,
77
+ train=True, dataroot=temporary)
78
+ opt = config.to_namespace(is_train=True)
79
+ opt.dataroot = str(Path(temporary) / "train")
80
+ opt.local_rank = -1
81
+ data = get_dataset(opt)
82
+ loader = DataLoader(data, batch_size=args.batch_size, shuffle=True,
83
+ num_workers=args.num_threads)
84
+ trainer = Trainer(opt)
85
+ for epoch in range(args.epochs):
86
+ trainer.train()
87
+ for step, batch in enumerate(loader):
88
+ trainer.set_input(batch)
89
+ trainer.optimize_parameters()
90
+ print(f"epoch={epoch + 1} step={step + 1} loss={trainer.loss.item():.5f}")
91
+ if args.max_steps and step + 1 >= args.max_steps:
92
+ break
93
+ trainer.save_networks("best")
94
+ source = Path(trainer.save_dir) / "model_epoch_best.pth"
95
+ target = HERE / "checkpoint" / name / "weights" / "best.pt"
96
+ target.parent.mkdir(parents=True, exist_ok=True)
97
+ shutil.copy2(source, target)
98
+ print(f"Saved {target}")
99
+ return
100
+
101
+ model = load(name, device, args.batch_size, args.num_threads)
102
+ transform = eval_transform()
103
+
104
+ @torch.inference_mode()
105
+ def score(path):
106
+ with Image.open(path) as image:
107
+ tensor = transform(image.convert("RGB")).unsqueeze(0).to(device)
108
+ output = model(tensor)
109
+ raw = float(output["logits"].flatten()[0].item())
110
+ return raw, float(torch.sigmoid(torch.tensor(raw)).item())
111
+
112
+ if task == "detect":
113
+ image = Path(args.image)
114
+ if not image.is_file():
115
+ raise FileNotFoundError(image)
116
+ raw, fake, elapsed = timed_score(score, image)
117
+ detection_result("ForensicConcept", image, raw, fake, elapsed, args.output)
118
+ else:
119
+ rows = []
120
+ entries = samples(args.data_root, args.split_file, "test", args.data_keys)
121
+ with torch.inference_mode():
122
+ for offset in range(0, len(entries), args.batch_size):
123
+ chunk = entries[offset:offset + args.batch_size]
124
+ tensors = []
125
+ for path, _ in chunk:
126
+ with Image.open(path) as image:
127
+ tensors.append(transform(image.convert("RGB")))
128
+ start = time.perf_counter()
129
+ logits = model(torch.stack(tensors).to(device))["logits"].flatten().cpu()
130
+ elapsed = (time.perf_counter() - start) / len(chunk)
131
+ for (path, label), raw, fake in zip(chunk, logits.tolist(), torch.sigmoid(logits).tolist()):
132
+ rows.append({"path": str(path), "label": label, "raw_score": raw,
133
+ "fake_score": fake, "prediction": int(fake >= .5), "elapsed_time": elapsed})
134
+ write_results("ForensicConcept", name, args.data_keys, rows)
detectors/ForensicConcept/test.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from run import main
2
+
3
+ if __name__ == "__main__":
4
+ main("test")
detectors/ForensicConcept/train.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from run import main
2
+
3
+ if __name__ == "__main__":
4
+ main("train")
detectors/ForensicConcept/upstream/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 ForensicConcept Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
detectors/ForensicConcept/upstream/THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party notices
2
+
3
+ This release contains modified or adapted code from the following projects.
4
+ The project-level license for this repository does not replace these notices.
5
+
6
+ ## OpenAI CLIP
7
+
8
+ Files under `models/clip/` include code and tokenizer data adapted from
9
+ [OpenAI CLIP](https://github.com/openai/CLIP). OpenAI CLIP is distributed
10
+ under the MIT License. The required notice is reproduced in
11
+ `LICENSES/CLIP-MIT.txt`.
12
+
13
+ ## LoRA
14
+
15
+ Files under `models/clip/loratorch/` contain a reconstructed LoRA
16
+ implementation based on [Microsoft LoRA](https://github.com/microsoft/LoRA),
17
+ with additional project-specific modifications. Microsoft LoRA is distributed
18
+ under the MIT License. The required notice is reproduced in
19
+ `LICENSES/LORA-MIT.txt`.
20
+
21
+ ## DINOv3
22
+
23
+ DINOv3 source code and pretrained weights are not included in this release.
24
+ They are external dependencies and remain subject to the license and model
25
+ terms published by the [official DINOv3 repository](https://github.com/facebookresearch/dinov3).
26
+
27
+ ## Python dependencies
28
+
29
+ Packages installed from `requirements.txt` retain their own licenses. This
30
+ notice does not modify or replace those licenses.
detectors/ForensicConcept/upstream/aug_utils_train/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .utils_data import distort_images
detectors/ForensicConcept/upstream/aug_utils_train/distortions.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision.io.image import decode_jpeg, encode_jpeg
3
+ import numpy as np
4
+ import math
5
+ import kornia
6
+ from .utils_distortions import fspecial, filter2D, curves, imscatter, mapmm
7
+ from torch.nn import functional as F
8
+
9
+ def gaussian_blur(x: torch.Tensor, blur_sigma: int = 0.1) -> torch.Tensor:
10
+ fs = 2 * math.ceil(2 * blur_sigma) + 1
11
+ h = fspecial('gaussian', (fs, fs), blur_sigma)
12
+ h = torch.from_numpy(h).float()
13
+
14
+ if len(x.shape) == 3:
15
+ x = x.unsqueeze(0)
16
+
17
+ y = filter2D(x, h.unsqueeze(0)).squeeze(0)
18
+ return y
19
+
20
+
21
+ def lens_blur(x: torch.Tensor, radius: int) -> torch.Tensor:
22
+ h = fspecial('disk', radius)
23
+ h = torch.from_numpy(h).float()
24
+
25
+ if len(x.shape) == 3:
26
+ x = x.unsqueeze(0)
27
+
28
+ y = filter2D(x, h.unsqueeze(0)).squeeze(0)
29
+ return y
30
+
31
+
32
+ def color_saturation(x: torch.Tensor, factor: int) -> torch.Tensor:
33
+ x = x[[2, 1, 0], ...]
34
+ hsv = kornia.color.rgb_to_hsv(x)
35
+ hsv[1, ...] *= factor
36
+ y = kornia.color.hsv_to_rgb(hsv)
37
+ return y[[2, 1, 0], ...]
38
+
39
+
40
+ def color_shift(x: torch.Tensor, amount: int) -> torch.Tensor:
41
+ def perc(x, perc):
42
+ xs = torch.sort(x)
43
+ i = len(xs) * perc / 100.
44
+ i = max(min(i, len(xs)), 1)
45
+ v = xs[round(i - 1)]
46
+ return v
47
+
48
+ gray = kornia.color.rgb_to_grayscale(x)
49
+ gradxy = kornia.filters.spatial_gradient(gray.unsqueeze(0), 'diff')
50
+ e = torch.sum(gradxy ** 2, 2) ** 0.5
51
+
52
+ fs = 2 * math.ceil(2 * 4) + 1
53
+ h = fspecial('gaussian', (fs, fs), 4)
54
+ h = torch.from_numpy(h).float()
55
+
56
+ e = filter2D(e, h.unsqueeze(0))
57
+
58
+ mine = torch.min(e)
59
+ maxe = torch.max(e)
60
+
61
+ if mine < maxe:
62
+ e = (e - mine) / (maxe - mine)
63
+
64
+ percdev = [1, 1]
65
+ valuehi = perc(e, 100 - percdev[1])
66
+ valuelo = 1 - perc(1 - e, 100 - percdev[0])
67
+
68
+ e = torch.max(torch.min(e, valuehi), valuelo)
69
+
70
+ channel = 1
71
+ g = x[channel, :, :]
72
+ a = np.random.random((1, 2))
73
+ amount_shift = np.round(a / (np.sum(a ** 2) ** 0.5) * amount)[0].astype(int)
74
+
75
+ y = F.pad(g, (amount_shift[0], amount_shift[0]), mode='replicate')
76
+ y = F.pad(y.transpose(1, 0), (amount_shift[1], amount_shift[1]), mode='replicate').transpose(1, 0)
77
+ y = torch.roll(y, (amount_shift[0], amount_shift[1]), dims=(0, 1))
78
+
79
+ if amount_shift[1] != 0:
80
+ y = y[amount_shift[1]:-amount_shift[1], ...]
81
+ if amount_shift[0] != 0:
82
+ y = y[..., amount_shift[0]:-amount_shift[0]]
83
+
84
+ yblend = y * e + x[channel, ...] * (1 - e)
85
+ x[channel, ...] = yblend
86
+
87
+ return x
88
+
89
+
90
+ def jpeg(x: torch.Tensor, quality: int) -> torch.Tensor:
91
+ x_loc = x.clone()
92
+ x_loc *= 255.
93
+ x_loc = x_loc.clamp(0, 255)
94
+ y = encode_jpeg(x_loc.byte().cpu(), quality=quality)
95
+ y = (decode_jpeg(y) / 255.).to(torch.float32)
96
+ return y
97
+
98
+
99
+ def white_noise(x: torch.Tensor, var: float, clip: bool = True, rounds: bool = False) -> torch.Tensor:
100
+ noise = torch.randn(*x.size(), dtype=x.dtype) * math.sqrt(var)
101
+
102
+ y = x + noise
103
+
104
+ if clip and rounds:
105
+ y = torch.clip((y * 255.0).round(), 0, 255) / 255.
106
+ elif clip:
107
+ y = torch.clip(y, 0, 1)
108
+ elif rounds:
109
+ y = (y * 255.0).round() / 255.
110
+ return y
111
+
112
+
113
+ def impulse_noise(x: torch.Tensor, d: float, s_vs_p: float = 0.5) -> torch.Tensor:
114
+ num_sp = int(d * x.shape[0] * x.shape[1] * x.shape[2])
115
+
116
+ coords = np.concatenate((np.random.randint(0, 3, (num_sp, 1)),
117
+ np.random.randint(0, x.shape[1], (num_sp, 1)),
118
+ np.random.randint(0, x.shape[2], (num_sp, 1))), 1)
119
+
120
+ num_salt = int(s_vs_p * num_sp)
121
+
122
+ coords_salt = coords[:num_salt].transpose(1, 0)
123
+ coords_pepper = coords[num_salt:].transpose(1, 0)
124
+
125
+ x[tuple(coords_salt)] = 1
126
+ x[tuple(coords_pepper)] = 0
127
+
128
+ return x
129
+
130
+
131
+ def brighten(x: torch.Tensor, amount: float) -> torch.Tensor:
132
+ x = x[[2, 1, 0]]
133
+ lab = kornia.color.rgb_to_lab(x)
134
+
135
+ l = lab[0, ...] / 100.
136
+ l_ = curves(l, 0.5 + amount / 2)
137
+ lab[0, ...] = l_ * 100.
138
+
139
+ y = curves(x, 0.5 + amount / 2)
140
+
141
+ j = torch.clamp(kornia.color.lab_to_rgb(lab), 0, 1)
142
+
143
+ y = (2 * y + j) / 3
144
+
145
+ return y[[2, 1, 0]]
146
+
147
+
148
+ def darken(x: torch.Tensor, amount: float, dolab: bool = False) -> torch.Tensor:
149
+ x = x[[2, 1, 0], :, :]
150
+ lab = kornia.color.rgb_to_lab(x)
151
+ if dolab:
152
+ l = lab[0, ...] / 100.
153
+ l_ = curves(l, 0.5 + amount / 2)
154
+ lab[0, ...] = l_ * 100.
155
+
156
+ y = curves(x, 0.5 - amount / 2)
157
+
158
+ if dolab:
159
+ j = torch.clamp(kornia.color.lab_to_rgb(lab), 0, 1)
160
+ y = (2 * y + j) / 3
161
+
162
+ return y[[2, 1, 0]]
163
+
164
+
165
+ def jitter(x: torch.Tensor, amount: float) -> torch.Tensor:
166
+ y = imscatter(x, amount, 5)
167
+ return y
168
+
169
+
170
+ def quantization(x: torch.Tensor, levels: int) -> torch.Tensor:
171
+ image = kornia.color.rgb_to_grayscale(x) * 255
172
+ image = image.cpu().numpy()
173
+ num_classes = levels
174
+
175
+ # minimum variance thresholding
176
+ hist, bins = np.histogram(image, num_classes, [0, 255])
177
+
178
+ return_thresholds = np.zeros(num_classes - 1)
179
+ for i in range(num_classes - 1):
180
+ return_thresholds[i] = bins[i + 1]
181
+
182
+ # quantize image with thresholds
183
+ bins = torch.tensor([0] + return_thresholds.tolist() + [256])
184
+ bins = bins.type(torch.int)
185
+ image = torch.bucketize(x.contiguous() * 255., bins).to(torch.float32)
186
+ image = mapmm(image)
187
+ return image
188
+
189
+
190
+ def linear_contrast_change(x: torch.Tensor, amount: float) -> torch.Tensor:
191
+ y = curves(x, [0.25 - amount / 4, 0.75 + amount / 4])
192
+ return y
detectors/ForensicConcept/upstream/aug_utils_train/utils_data.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from .distortions import *
3
+ import random
4
+
5
+ distortion_groups = {
6
+ "blur": ["gausblur", "lensblur"],
7
+ "color_distortion": ["colorshift", "colorsat"],
8
+ "jpeg": ["jpeg"],
9
+ "noise": ["whitenoise", "impulsenoise"],
10
+ "brightness_change": ["brighten", "darken"],
11
+ "spatial_distortion": ["jitter", "quantization"],
12
+ "sharpness_contrast": ["lincontrchange"],
13
+ }
14
+
15
+ distortion_groups_mapping = {
16
+ "gausblur": "blur",
17
+ "lensblur": "blur",
18
+ "colorshift": "color_distortion",
19
+ "colorsat": "color_distortion",
20
+ "jpeg": "jpeg",
21
+ "whitenoise": "noise",
22
+ "impulsenoise": "noise",
23
+ "brighten": "brightness_change",
24
+ "darken": "brightness_change",
25
+ "jitter": "spatial_distortion",
26
+ "quantization": "spatial_distortion",
27
+ "lincontrchange": "sharpness_contrast",
28
+ }
29
+
30
+ distortion_range = {
31
+ "gausblur": [0.1, 0.5, 1, 2, 5],
32
+ "lensblur": [1, 2, 4, 6, 8],
33
+ "colorshift": [1, 3, 6, 8, 12],
34
+ "colorsat": [0.4, 0.2, 0.1, 0, -0.4],
35
+ "jpeg": [43, 36, 24, 7, 4],
36
+ "whitenoise": [0.001, 0.002, 0.003, 0.005, 0.01],
37
+ "impulsenoise": [0.001, 0.005, 0.01, 0.02, 0.03],
38
+ "brighten": [0.1, 0.2, 0.4, 0.7, 1.1],
39
+ "darken": [0.05, 0.1, 0.2, 0.4, 0.8],
40
+ "jitter": [0.05, 0.1, 0.2, 0.5, 1],
41
+ "quantization": [20, 16, 13, 10, 7],
42
+ "lincontrchange": [0., 0.15, -0.4, 0.3, -0.6],
43
+ }
44
+
45
+ distortion_functions = {
46
+ "gausblur": gaussian_blur,
47
+ "lensblur": lens_blur,
48
+ "colorshift": color_shift,
49
+ "colorsat": color_saturation,
50
+ "jpeg": jpeg,
51
+ "whitenoise": white_noise,
52
+ "impulsenoise": impulse_noise,
53
+ "brighten": brighten,
54
+ "darken": darken,
55
+ "jitter": jitter,
56
+ "quantization": quantization,
57
+ "lincontrchange": linear_contrast_change
58
+ }
59
+
60
+
61
+ def distort_images(image: torch.Tensor, distort_functions: list = None, distort_values: list = None,
62
+ max_distortions: int = 3, num_levels: int = 5) -> torch.Tensor:
63
+ """
64
+ Args:
65
+ image (Tensor of size [3,H,W] and value range [0,1]): image to distort
66
+ distort_functions (list): list of the distortion functions to apply to the image. If None, the functions are randomly chosen.
67
+ distort_values (list): list of the values of the distortion functions to apply to the image. If None, the values are randomly chosen.
68
+ max_distortions (int): maximum number of distortions to apply to the image
69
+ num_levels (int): number of levels of distortion that can be applied to the image
70
+
71
+ Returns:
72
+ image (Tensor): distorted image
73
+ distort_functions (list): list of the distortion functions applied to the image
74
+ distort_values (list): list of the values of the distortion functions applied to the image
75
+ """
76
+ image_loc = image.clone()
77
+ if distort_functions is None or distort_values is None:
78
+ distort_functions, distort_values = get_distortions_composition(max_distortions, num_levels)
79
+
80
+ for distortion, value in zip(distort_functions, distort_values):
81
+ image_loc = distortion(image_loc, value)
82
+ image_loc = image_loc.to(torch.float32)
83
+ image_loc = torch.clip(image_loc, 0, 1)
84
+
85
+ return image_loc, distort_functions, distort_values
86
+
87
+
88
+ def get_distortions_composition(max_distortions: int = 3, num_levels: int = 5):
89
+ """
90
+ Args:
91
+ max_distortions (int): maximum number of distortions to apply to the image
92
+ num_levels (int): number of levels of distortion that can be applied to the image
93
+
94
+ Returns:
95
+ distort_functions (list): list of the distortion functions to apply to the image
96
+ distort_values (list): list of the values of the distortion functions to apply to the image
97
+ """
98
+ MEAN = 0
99
+ STD = 2.5
100
+
101
+ num_distortions = random.randint(1, max_distortions)
102
+ groups = random.sample(list(distortion_groups.keys()), num_distortions)
103
+ distortions = [random.choice(distortion_groups[group]) for group in groups]
104
+ distort_functions = [distortion_functions[dist] for dist in distortions]
105
+
106
+ probabilities = [1 / (STD * np.sqrt(2 * np.pi)) * np.exp(-((i - MEAN) ** 2) / (2 * STD ** 2))
107
+ for i in range(num_levels)] # probabilities according to a gaussian distribution
108
+ normalized_probabilities = [prob / sum(probabilities)
109
+ for prob in probabilities] # normalize probabilities
110
+ distort_values = [np.random.choice(distortion_range[dist][:num_levels], p=normalized_probabilities) for dist
111
+ in distortions]
112
+
113
+ return distort_functions, distort_values
detectors/ForensicConcept/upstream/aug_utils_train/utils_distortions.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ from typing import Union, Tuple
4
+ import torch
5
+ from torch.nn import functional as F
6
+ import scipy
7
+
8
+ def sign(x: float) -> int:
9
+ return 1 if x >= 0 else -1
10
+
11
+
12
+ def mapmm(x: torch.Tensor) -> torch.Tensor:
13
+ minx = torch.min(x)
14
+ maxx = torch.max(x)
15
+ if minx < maxx:
16
+ x = (x - minx) / (maxx - minx)
17
+ return x
18
+
19
+
20
+ def fspecial(filter_type: str, p2: Union[int, Tuple[int, int]], p3: Union[int, float] = None) -> np.ndarray:
21
+ if filter_type == 'gaussian':
22
+ m, n = [(ss - 1.) / 2. for ss in p2]
23
+ y, x = np.ogrid[-m:m + 1, -n:n + 1]
24
+ h = np.exp(-(x * x + y * y) / (2. * p3 * p3))
25
+ h[h < np.finfo(h.dtype).eps * h.max()] = 0
26
+ sumh = h.sum()
27
+ if sumh != 0:
28
+ h /= sumh
29
+
30
+ return h
31
+
32
+ elif filter_type == 'disk':
33
+ rad = p2
34
+ crad = math.ceil(rad - 0.5)
35
+
36
+ x, y = np.ogrid[-rad: rad + 1, -rad: rad + 1]
37
+ y = np.tile(y.transpose(), y.shape[1])
38
+ x = np.tile(x, x.shape[0]).transpose()
39
+
40
+ y = np.abs(y)
41
+ x = np.abs(x)
42
+
43
+ maxxy = np.maximum(x, y)
44
+ minxy = np.minimum(x, y)
45
+
46
+ r1 = (rad ** 2 - (maxxy + 0.5) ** 2)
47
+ r2 = (rad ** 2 - (minxy - 0.5) ** 2)
48
+
49
+ if (r1 > 0).all():
50
+ warn_m1 = r1 ** 0.5
51
+ else:
52
+ warn_m1 = 0
53
+ if (r2 > 0).all():
54
+ warn_m2 = r2 ** 0.5
55
+ else:
56
+ warn_m2 = 0
57
+
58
+ m1 = (rad ** 2 < (maxxy + 0.5) ** 2 + (minxy - 0.5) ** 2) * (minxy - 0.5) + (
59
+ rad ** 2 >= (maxxy + 0.5) ** 2 + (minxy - 0.5) ** 2) * warn_m1
60
+ m2 = (rad ** 2 > (maxxy - 0.5) ** 2 + (minxy + 0.5) ** 2) * (minxy + 0.5) + (
61
+ rad ** 2 <= (maxxy - 0.5) ** 2 + (minxy + 0.5) ** 2) * warn_m2
62
+
63
+ sgrid = (rad ** 2 * (0.5 * (np.arcsin(m2 / rad) - np.arcsin(m1 / rad)) +
64
+ 0.25 * (np.sin(2 * np.arcsin(m2 / rad)) - np.sin(2 * np.arcsin(m1 / rad)))) - (
65
+ maxxy - 0.5) * (m2 - m1) + (m1 - minxy + 0.5)) * np.logical_or(
66
+ np.logical_and((rad ** 2 < (maxxy + 0.5) ** 2 + (minxy + 0.5) ** 2),
67
+ (rad ** 2 > (maxxy - 0.5) ** 2 + (minxy - 0.5) ** 2)),
68
+ np.logical_and(np.logical_and(minxy == 0, maxxy - 0.5 < rad), maxxy + 0.5 >= rad))
69
+
70
+ sgrid = sgrid + ((maxxy + 0.5) ** 2 + (minxy + 0.5) ** 2 < rad ** 2)
71
+ sgrid[crad, crad] = np.minimum(math.pi * rad ** 2, math.pi / 2)
72
+ if (crad > 0) and (rad > crad - 0.5) and (rad ** 2 < (crad - 0.5) ** 2 + 0.25):
73
+ m1 = np.sqrt(rad ** 2 - (crad - 0.5) ** 2)
74
+ m1n = m1 / rad
75
+ sg0 = 2 * (rad ** 2 * (0.5 * np.arcsin(m1n) + 0.25 * np.sin(2 * np.arcsin(m1n))) - m1 * (crad - 0.5))
76
+ sgrid[2 * crad, crad] = sg0
77
+ sgrid[crad, 2 * crad] = sg0
78
+ sgrid[crad, 0] = sg0
79
+ sgrid[0, crad] = sg0
80
+ sgrid[2 * crad, crad] = sgrid[2 * crad, crad] - sg0
81
+ sgrid[crad, 2 * crad] = sgrid[crad, 2 * crad] - sg0
82
+ sgrid[crad, 2] = sgrid[crad, 2] - sg0
83
+ sgrid[2, crad] = sgrid[2, crad + 1] - sg0
84
+
85
+ sgrid[crad, crad] = np.minimum(sgrid[crad, crad], 1)
86
+ h = sgrid / np.sum(sgrid)
87
+ return h
88
+
89
+ else:
90
+ raise NotImplementedError(f"Filter type {filter_type} not implemented")
91
+
92
+
93
+ def filter2D(img: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
94
+ """PyTorch version of cv2.filter2D
95
+ Args:
96
+ img (Tensor): (b, c, h, w)
97
+ kernel (Tensor): (b, k, k)
98
+ """
99
+ img = img.float()
100
+ k1 = kernel.size(-2)
101
+ k2 = kernel.size(-1)
102
+
103
+ b, c, h, w = img.size()
104
+ if k1 % 2 == 1 or k2 % 2 == 1:
105
+ img = F.pad(img, (k2 // 2, k2 // 2, k1 // 2, k1 // 2), mode='replicate')
106
+ else:
107
+ raise ValueError('Wrong kernel size')
108
+
109
+ ph, pw = img.size()[-2:]
110
+
111
+ if kernel.size(0) == 1:
112
+ # apply the same kernel to all batch images
113
+ img = img.view(b * c, 1, ph, pw)
114
+ kernel = kernel.view(1, 1, k1, k2)
115
+ return F.conv2d(img, kernel, padding=0).view(b, c, h, w)
116
+ else:
117
+ img = img.view(1, b * c, ph, pw)
118
+ kernel = kernel.view(b, 1, k1, k2).repeat(1, c, 1, 1).view(b * c, 1, k1, k2)
119
+ return F.conv2d(img, kernel, groups=b * c).view(b, c, h, w)
120
+
121
+
122
+ def curves(xx: torch.Tensor, coef: float) -> torch.Tensor:
123
+ if type(coef) == list:
124
+ coef = [[0.3, 0.5, 0.7],
125
+ [coef[0], 0.5, coef[1]]]
126
+ else:
127
+ coef = [[0.5], [coef]]
128
+
129
+ x = np.array([0] + [p for p in coef[0]] + [1])
130
+ y = np.array([0] + [p for p in coef[1]] + [1])
131
+
132
+ cs = spline(x, y)
133
+
134
+ yy = ppval(cs, xx)
135
+
136
+ yy = torch.clamp(yy, 0, 1)
137
+
138
+ return yy
139
+
140
+
141
+ def spline(x: np.ndarray, y: np.ndarray) -> np.ndarray:
142
+ n = x.shape[0]
143
+ dd = 1
144
+ dx = np.diff(x)
145
+ divdif = np.diff(y) / dx
146
+
147
+ if n == 3:
148
+ y[1:3] = divdif
149
+ y[2] = np.diff(divdif.T).T / (x[2] - x[0])
150
+ y[1] -= y[2] * dx[0]
151
+ dlk = y[[2, 1, 0]].shape[0]
152
+ l = x[[0, 2]].shape[0] - 1
153
+ dl = np.prod(dd) * l
154
+ k = np.fix(dlk / dl + 100 * 2.2204e-16)
155
+
156
+ pp = (x[[0, 2]], y[[2, 1, 0]], l, int(k), dd)
157
+
158
+ elif n > 3:
159
+ b = np.zeros(n)
160
+ b[1:n - 1] = 3 * (dx[1:n] * divdif[0:n - 2] + dx[0:n - 2] * divdif[1:n])
161
+
162
+ x31 = x[2] - x[0]
163
+ xn = x[n - 1] - x[n - 3]
164
+
165
+ b[0] = ((dx[0] + 2 * x31) * dx[1] * divdif[0] + dx[0] ** 2 * divdif[1]) / x31
166
+ b[n - 1] = (dx[n - 2] ** 2 * divdif[n - 3] + (2 * xn + dx[n - 2]) * dx[n - 3] * divdif[n - 2]) / xn;
167
+
168
+ dxt = dx.T
169
+ c = np.zeros((3, 5))
170
+ c[0, :] = [x31] + list(dxt[0:n - 2]) + [0]
171
+ c[1, :] = [dxt[1]] + list(2 * (dxt[1:n - 1] + dxt[0:n - 2])) + [dxt[n - 3]]
172
+ c[2, :] = [0] + list(dxt[1:n - 1]) + [xn]
173
+
174
+ c = scipy.sparse.dia_matrix((c, [-1, 0, 1]), shape=(5, 5))
175
+ c = scipy.sparse.csc_matrix(c)
176
+ ic = scipy.sparse.linalg.inv(c)
177
+ s = b * ic
178
+
179
+ n = x.shape[0]
180
+ d = 1
181
+ dxd = dx
182
+
183
+ dzzdx = (divdif - s[0:n - 1]) / dxd
184
+ dzdxdx = (s[1:n] - divdif) / dxd
185
+
186
+ coefs = np.vstack(((dzdxdx - dzzdx) / dxd, 2 * dzzdx - dzdxdx, s[0:n - 1], y[0:n - 1])).T
187
+
188
+ pp = (x, coefs, x.shape[0], x.shape[0], d)
189
+ else:
190
+ raise ValueError('x.shape[0] must be >= 3')
191
+
192
+ return pp
193
+
194
+
195
+ def ppval(pp: np.ndarray, xx: torch.Tensor) -> torch.Tensor:
196
+ lx = torch.numel(xx)
197
+ xs = xx.reshape(1, lx)
198
+ b, c, l, k, dd = pp
199
+ b = torch.as_tensor(b, device=xx.device)
200
+ ranges = b.clone()
201
+ ranges[0] = -torch.inf
202
+ ranges[-1] = torch.inf
203
+ index = histc(xs, ranges)
204
+
205
+ xs = xs - b[index]
206
+
207
+ c = torch.as_tensor(c, device=xx.device)
208
+
209
+ if len(c.shape) == 1:
210
+ v = c[0]
211
+ for i in range(1, k):
212
+ v = xs * v + c[i]
213
+ else:
214
+ v = c[index, 0]
215
+
216
+ for i in range(1, k - 1):
217
+ v = xs * v + c[index, i]
218
+ v = v.view(xx.shape)
219
+ return v
220
+
221
+
222
+ def histc(x: torch.Tensor, binranges: torch.Tensor) -> torch.Tensor:
223
+ indices = torch.bucketize(x, binranges)
224
+ return torch.remainder(indices, len(binranges)) - 1
225
+
226
+
227
+ def imscatter(x: torch.Tensor, amount: float, iterations=1) -> torch.Tensor:
228
+ y = x
229
+ for i in range(iterations):
230
+ shiftmap = torch.randn((2, x.shape[1], x.shape[2]), device=x.device) * amount
231
+
232
+ sy = shiftmap[0, :, :]
233
+ sx = shiftmap[1, :, :]
234
+
235
+ m_sx = torch.ceil(torch.abs(torch.max(sx))).to(torch.int32)
236
+ m_sy = torch.ceil(torch.abs(torch.max(sy))).to(torch.int32)
237
+
238
+ y = F.pad(y, (m_sy, m_sy), mode='replicate')
239
+ y = F.pad(y.transpose(2, 1), (m_sx, m_sx), mode='replicate').transpose(2, 1)
240
+
241
+ sy = F.pad(sy, (m_sy, m_sy), mode='replicate')
242
+ sy = F.pad(sy.transpose(1, 0), (m_sx, m_sx), mode='replicate').transpose(1, 0)
243
+ sx = F.pad(sx, (m_sy, m_sy), mode='replicate')
244
+ sx = F.pad(sx.transpose(1, 0), (m_sx, m_sx), mode='replicate').transpose(1, 0)
245
+
246
+ xx, yy = torch.as_tensor(np.mgrid[0:y.shape[1], 0:y.shape[2]], device=x.device)
247
+
248
+ z = torch.zeros_like(y)
249
+ bx = (xx - sx)
250
+ by = (yy - sy)
251
+ for i in range(3):
252
+ j = bilinear_interpolate_torch(y[i, ...], by, bx)
253
+ z[i, :, :] = j
254
+
255
+ y = z[:, m_sy:m_sy + x.shape[1], m_sx:m_sx + x.shape[2]]
256
+ return y
257
+
258
+
259
+ def bilinear_interpolate_torch(im: torch.Tensor, x: torch.Tensor, y: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
260
+ dtype_long = torch.LongTensor
261
+
262
+ x0 = torch.floor(x).type(dtype_long).to(im.device)
263
+ x1 = x0 + 1
264
+
265
+ y0 = torch.floor(y).type(dtype_long).to(im.device)
266
+ y1 = y0 + 1
267
+
268
+ x0 = torch.clamp(x0, 0, im.shape[1] - 1)
269
+ x1 = torch.clamp(x1, 0, im.shape[1] - 1)
270
+ y0 = torch.clamp(y0, 0, im.shape[0] - 1)
271
+ y1 = torch.clamp(y1, 0, im.shape[0] - 1)
272
+
273
+ Ia = im[y0, x0]
274
+ Ib = im[y1, x0]
275
+ Ic = im[y0, x1]
276
+ Id = im[y1, x1]
277
+
278
+ R1 = Ia * (x1 - x) / (x1 - x0 + eps) + Ic * (x - x0) / (x1 - x0 + eps)
279
+ R2 = Ib * (x1 - x) / (x1 - x0 + eps) + Id * (x - x0) / (x1 - x0 + eps)
280
+ P = R1 * (y1 - y) / (y1 - y0 + eps) + R2 * (y - y0) / (y1 - y0 + eps)
281
+ return P
detectors/ForensicConcept/upstream/codebooks/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLIP codebook
2
+
3
+ `cleandift_codebook.npy` contains the raw cluster centers used by the
4
+ stage-2 CLIP detector in `configs/clip_codebook.yaml`. The model L2-normalizes
5
+ the centers at load time through `clip_codebook_l2: true`.
6
+
7
+ - Shape: `200 x 1280`
8
+ - Dtype: `float32`
9
+ - SHA-256: `0a7cd9555750c5f08b1db0a5a2dc0d866ef195fcd05210bffe53b2c82cdc87ab`
10
+
11
+ The stage-2 detector checkpoint stores the normalized matrix as the persistent
12
+ `codebook_head.codebook` buffer. The external raw centers are retained for
13
+ stage-2 training and for tracing how the injected codebook was produced.
detectors/ForensicConcept/upstream/codebooks/cleandift_codebook.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a7cd9555750c5f08b1db0a5a2dc0d866ef195fcd05210bffe53b2c82cdc87ab
3
+ size 1024128
detectors/ForensicConcept/upstream/config_loader.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration loader for AIGC Detection project.
3
+ Loads configuration from YAML files and provides easy access to parameters.
4
+ """
5
+
6
+ import yaml
7
+ import os
8
+ import argparse
9
+ from typing import Dict, Any, Optional
10
+
11
+
12
+ ROBUSTNESS_PRESETS = {
13
+ 'jpeg_q75': {
14
+ 'type': 'jpeg',
15
+ 'params': {'jpeg_quality': 75},
16
+ },
17
+ 'jpeg_q70': {
18
+ 'type': 'jpeg',
19
+ 'params': {'jpeg_quality': 70},
20
+ },
21
+ 'gaussian_blur_sigma1': {
22
+ 'type': 'gaussian_blur',
23
+ 'params': {'gaussian_blur_sigma': 1.0},
24
+ },
25
+ 'gaussian_blur_sigma2': {
26
+ 'type': 'gaussian_blur',
27
+ 'params': {'gaussian_blur_sigma': 2.0},
28
+ },
29
+ 'gaussian_noise_std01': {
30
+ 'type': 'gaussian_noise',
31
+ 'params': {'gaussian_noise_std': 0.1},
32
+ },
33
+ 'gaussian_noise_std02': {
34
+ 'type': 'gaussian_noise',
35
+ 'params': {'gaussian_noise_std': 0.2},
36
+ },
37
+ 'downsample_scale05': {
38
+ 'type': 'downsample',
39
+ 'params': {'downsample_scale': 0.5},
40
+ },
41
+ 'color_jitter_brightness02': {
42
+ 'type': 'color_jitter',
43
+ 'params': {
44
+ 'cj_brightness': 0.2,
45
+ 'cj_contrast': 0.0,
46
+ 'cj_saturation': 0.0,
47
+ 'cj_hue': 0.0,
48
+ },
49
+ },
50
+ 'color_jitter_contrast02': {
51
+ 'type': 'color_jitter',
52
+ 'params': {
53
+ 'cj_brightness': 0.0,
54
+ 'cj_contrast': 0.2,
55
+ 'cj_saturation': 0.0,
56
+ 'cj_hue': 0.0,
57
+ },
58
+ },
59
+ }
60
+
61
+ ROBUSTNESS_PARAM_DEFAULTS = {
62
+ 'jpeg_quality': 75,
63
+ 'gaussian_blur_sigma': 1.0,
64
+ 'gaussian_noise_std': 0.1,
65
+ 'downsample_scale': 0.5,
66
+ 'cj_brightness': 0.0,
67
+ 'cj_contrast': 0.0,
68
+ 'cj_saturation': 0.0,
69
+ 'cj_hue': 0.0,
70
+ }
71
+
72
+
73
+ def _coerce_robustness_params(raw_params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
74
+ raw = dict(raw_params or {})
75
+ return {
76
+ 'jpeg_quality': int(raw.get('jpeg_quality', ROBUSTNESS_PARAM_DEFAULTS['jpeg_quality']) or ROBUSTNESS_PARAM_DEFAULTS['jpeg_quality']),
77
+ 'gaussian_blur_sigma': float(raw.get('gaussian_blur_sigma', ROBUSTNESS_PARAM_DEFAULTS['gaussian_blur_sigma']) or ROBUSTNESS_PARAM_DEFAULTS['gaussian_blur_sigma']),
78
+ 'gaussian_noise_std': float(raw.get('gaussian_noise_std', ROBUSTNESS_PARAM_DEFAULTS['gaussian_noise_std']) or ROBUSTNESS_PARAM_DEFAULTS['gaussian_noise_std']),
79
+ 'downsample_scale': float(raw.get('downsample_scale', ROBUSTNESS_PARAM_DEFAULTS['downsample_scale']) or ROBUSTNESS_PARAM_DEFAULTS['downsample_scale']),
80
+ 'cj_brightness': float(raw.get('cj_brightness', ROBUSTNESS_PARAM_DEFAULTS['cj_brightness']) or ROBUSTNESS_PARAM_DEFAULTS['cj_brightness']),
81
+ 'cj_contrast': float(raw.get('cj_contrast', ROBUSTNESS_PARAM_DEFAULTS['cj_contrast']) or ROBUSTNESS_PARAM_DEFAULTS['cj_contrast']),
82
+ 'cj_saturation': float(raw.get('cj_saturation', ROBUSTNESS_PARAM_DEFAULTS['cj_saturation']) or ROBUSTNESS_PARAM_DEFAULTS['cj_saturation']),
83
+ 'cj_hue': float(raw.get('cj_hue', ROBUSTNESS_PARAM_DEFAULTS['cj_hue']) or ROBUSTNESS_PARAM_DEFAULTS['cj_hue']),
84
+ }
85
+
86
+
87
+ def _resolve_robustness_entry(entry: Optional[Dict[str, Any]]) -> Dict[str, Any]:
88
+ item = dict(entry or {})
89
+ preset = str(item.get('preset', '') or '').strip().lower()
90
+ robustness_type = str(item.get('type', '') or '').strip().lower()
91
+ params = _coerce_robustness_params(item)
92
+
93
+ if preset:
94
+ preset_cfg = ROBUSTNESS_PRESETS.get(preset)
95
+ if preset_cfg is None:
96
+ valid = ', '.join(sorted(ROBUSTNESS_PRESETS.keys()))
97
+ raise ValueError(f"Unknown testing.robustness.preset='{preset}'. Valid presets: {valid}")
98
+ robustness_type = preset_cfg['type']
99
+ params.update(preset_cfg['params'])
100
+
101
+ return {
102
+ 'preset': preset,
103
+ 'type': robustness_type,
104
+ 'params': params,
105
+ }
106
+
107
+
108
+ class ConfigLoader:
109
+ """
110
+ Configuration loader that handles YAML configuration files.
111
+ """
112
+
113
+ def __init__(self, config_path: Optional[str] = None):
114
+ """
115
+ Initialize the configuration loader.
116
+
117
+ Args:
118
+ config_path: Path to the YAML configuration file
119
+ """
120
+ self.config_path = config_path
121
+ self.config = {}
122
+
123
+ if config_path:
124
+ self.load_config(config_path)
125
+
126
+ def load_config(self, config_path: str) -> Dict[str, Any]:
127
+ """
128
+ Load configuration from a YAML file.
129
+
130
+ Args:
131
+ config_path: Path to the YAML configuration file
132
+
133
+ Returns:
134
+ Dictionary containing the configuration
135
+ """
136
+ if not os.path.exists(config_path):
137
+ raise FileNotFoundError(f"Configuration file not found: {config_path}")
138
+
139
+ with open(config_path, 'r', encoding='utf-8') as f:
140
+ self.config = yaml.safe_load(f)
141
+
142
+ return self.config
143
+
144
+ def get(self, key: str, default: Any = None) -> Any:
145
+ """
146
+ Get a configuration value using dot notation.
147
+
148
+ Args:
149
+ key: Key in dot notation (e.g., 'data.train_dataroot')
150
+ default: Default value if key not found
151
+
152
+ Returns:
153
+ Configuration value
154
+ """
155
+ keys = key.split('.')
156
+ value = self.config
157
+
158
+ for k in keys:
159
+ if isinstance(value, dict) and k in value:
160
+ value = value[k]
161
+ else:
162
+ return default
163
+
164
+ return value
165
+
166
+ def set(self, key: str, value: Any):
167
+ """
168
+ Set a configuration value using dot notation.
169
+
170
+ Args:
171
+ key: Key in dot notation (e.g., 'data.train_dataroot')
172
+ value: Value to set
173
+ """
174
+ keys = key.split('.')
175
+ config = self.config
176
+
177
+ for k in keys[:-1]:
178
+ if k not in config:
179
+ config[k] = {}
180
+ config = config[k]
181
+
182
+ config[keys[-1]] = value
183
+
184
+ def update_from_args(self, args: argparse.Namespace):
185
+ """
186
+ Update configuration with command line arguments.
187
+
188
+ Args:
189
+ args: Parsed command line arguments
190
+ """
191
+ # Update paths if provided
192
+ if hasattr(args, 'train_dataroot') and args.train_dataroot:
193
+ self.set('data.train_dataroot', args.train_dataroot)
194
+ if hasattr(args, 'test_dataroot') and args.test_dataroot:
195
+ self.set('data.test_dataroot', args.test_dataroot)
196
+ if hasattr(args, 'checkpoints_dir') and args.checkpoints_dir:
197
+ self.set('models.checkpoints_dir', args.checkpoints_dir)
198
+
199
+ # Update training parameters if provided
200
+ if hasattr(args, 'lr') and args.lr:
201
+ self.set('training.lr', args.lr)
202
+ if hasattr(args, 'batch_size') and args.batch_size:
203
+ self.set('training.batch_size', args.batch_size)
204
+ if hasattr(args, 'niter') and args.niter:
205
+ self.set('training.niter', args.niter)
206
+ if hasattr(args, 'gpu_ids') and args.gpu_ids:
207
+ self.set('training.gpu_ids', args.gpu_ids)
208
+ if hasattr(args, 'name') and args.name:
209
+ self.set('training.name', args.name)
210
+
211
+ def get_testing_robustness(self) -> Dict[str, Any]:
212
+ """
213
+ Resolve test-time robustness preprocessing from config.
214
+
215
+ Supports either:
216
+ 1) `testing.robustness.preset` for one-click selection, or
217
+ 2) `testing.robustness.type` + explicit params, or
218
+ 3) `testing.robustness.chain` for sequential perturbations.
219
+ """
220
+ robustness_cfg = self.get('testing.robustness', {}) or {}
221
+ if not isinstance(robustness_cfg, dict):
222
+ robustness_cfg = {}
223
+ chain_cfg = robustness_cfg.get('chain', self.get('testing.robustness_chain', [])) or []
224
+ if not isinstance(chain_cfg, list):
225
+ raise ValueError("testing.robustness.chain must be a list of robustness entries.")
226
+
227
+ resolved_chain = []
228
+ for idx, entry in enumerate(chain_cfg):
229
+ if not isinstance(entry, dict):
230
+ raise ValueError(f"testing.robustness.chain[{idx}] must be a mapping.")
231
+ resolved = _resolve_robustness_entry(entry)
232
+ if not resolved['type']:
233
+ raise ValueError(f"testing.robustness.chain[{idx}] must define preset or type.")
234
+ resolved_chain.append(resolved)
235
+
236
+ single_entry = _resolve_robustness_entry({
237
+ 'preset': robustness_cfg.get('preset', self.get('testing.robustness_preset', '')),
238
+ 'type': robustness_cfg.get('type', self.get('testing.robustness_type', '')),
239
+ 'jpeg_quality': robustness_cfg.get('jpeg_quality', self.get('testing.robustness_jpeg_quality', ROBUSTNESS_PARAM_DEFAULTS['jpeg_quality'])),
240
+ 'gaussian_blur_sigma': robustness_cfg.get('gaussian_blur_sigma', self.get('testing.robustness_gaussian_blur_sigma', ROBUSTNESS_PARAM_DEFAULTS['gaussian_blur_sigma'])),
241
+ 'gaussian_noise_std': robustness_cfg.get('gaussian_noise_std', self.get('testing.robustness_gaussian_noise_std', ROBUSTNESS_PARAM_DEFAULTS['gaussian_noise_std'])),
242
+ 'downsample_scale': robustness_cfg.get('downsample_scale', self.get('testing.robustness_downsample_scale', ROBUSTNESS_PARAM_DEFAULTS['downsample_scale'])),
243
+ 'cj_brightness': robustness_cfg.get('cj_brightness', self.get('testing.robustness_cj_brightness', ROBUSTNESS_PARAM_DEFAULTS['cj_brightness'])),
244
+ 'cj_contrast': robustness_cfg.get('cj_contrast', self.get('testing.robustness_cj_contrast', ROBUSTNESS_PARAM_DEFAULTS['cj_contrast'])),
245
+ 'cj_saturation': robustness_cfg.get('cj_saturation', self.get('testing.robustness_cj_saturation', ROBUSTNESS_PARAM_DEFAULTS['cj_saturation'])),
246
+ 'cj_hue': robustness_cfg.get('cj_hue', self.get('testing.robustness_cj_hue', ROBUSTNESS_PARAM_DEFAULTS['cj_hue'])),
247
+ })
248
+
249
+ if resolved_chain:
250
+ primary = resolved_chain[0]
251
+ else:
252
+ primary = single_entry
253
+
254
+ return {
255
+ 'preset': primary['preset'],
256
+ 'type': primary['type'],
257
+ 'params': primary['params'],
258
+ 'chain': resolved_chain,
259
+ }
260
+
261
+ def create_directories(self):
262
+ """
263
+ Create necessary directories based on configuration.
264
+ """
265
+ # Create output directories
266
+ dirs_to_create = [self.get('models.checkpoints_dir')]
267
+
268
+ for dir_path in dirs_to_create:
269
+ if dir_path:
270
+ os.makedirs(dir_path, exist_ok=True)
271
+
272
+ def to_namespace(self, is_train: bool = True) -> argparse.Namespace:
273
+ """
274
+ Convert configuration to argparse Namespace for compatibility.
275
+
276
+ Returns:
277
+ Namespace containing all configuration parameters
278
+ """
279
+ namespace = argparse.Namespace()
280
+
281
+ # Set common parameters for compatibility with existing code
282
+ namespace.dataroot = self.get('data.train_dataroot')
283
+ extra_train_roots = self.get('data.extra_train_roots', [])
284
+ if isinstance(extra_train_roots, str):
285
+ extra_train_roots = [p.strip() for p in extra_train_roots.split(',') if p.strip()]
286
+ if extra_train_roots is None:
287
+ extra_train_roots = []
288
+ namespace.extra_train_roots = list(extra_train_roots)
289
+ namespace.test_dataroot = self.get('data.test_dataroot')
290
+ namespace.train_split = self.get('data.train_split', 'train')
291
+ namespace.val_split = self.get('data.val_split', 'val')
292
+ namespace.checkpoints_dir = self.get('models.checkpoints_dir')
293
+ namespace.arch = self.get('training.arch', 'res50')
294
+ namespace.trainmode = self.get('training.trainmode', 'lora')
295
+ namespace.modelname = self.get('training.modelname', 'CLIP:ViT-L/14@336px')
296
+ namespace.lr = self.get('training.lr', 0.0001)
297
+ namespace.lr_decay_factor = self.get('training.lr_decay_factor', 0.9)
298
+ namespace.lr_min = self.get('training.lr_min', 1e-6)
299
+ namespace.weight_decay = self.get('training.weight_decay', 0.0)
300
+ namespace.max_grad_norm = self.get('training.max_grad_norm', 0.0)
301
+ namespace.lr_plateau_patience = self.get('training.lr_plateau_patience', 0)
302
+ namespace.lr_plateau_delta = self.get('training.lr_plateau_delta', 0.0)
303
+ namespace.lr_plateau_warmup = self.get('training.lr_plateau_warmup', 0)
304
+ namespace.batch_size = self.get('training.batch_size', 16)
305
+ namespace.niter = self.get('training.niter', 1000)
306
+ namespace.delr_freq = self.get('training.delr_freq', 20)
307
+ namespace.loss_freq = self.get('training.loss_freq', 400)
308
+ namespace.data_aug = self.get('training.data_aug', True)
309
+ namespace.use_testshift_like_aug = self.get('training.use_testshift_like_aug', False)
310
+ namespace.use_testshift_like_aug_eval = self.get('testing.use_testshift_like_aug_eval', False)
311
+ namespace.testshift_like_apply_prob = self.get('training.testshift_like_apply_prob', 1.0)
312
+ namespace.testshift_like_max_groups = self.get('training.testshift_like_max_groups', 3)
313
+ namespace.use_aug_utils_train = self.get('training.use_aug_utils_train', False)
314
+ namespace.aug_utils_prob = self.get('training.aug_utils_prob', 1.0)
315
+ namespace.aug_utils_max_distortions = self.get('training.aug_utils_max_distortions', 3)
316
+ namespace.aug_utils_num_levels = self.get('training.aug_utils_num_levels', 5)
317
+ namespace.augmix_js_enable = self.get('training.augmix_js_enable', False)
318
+ namespace.augmix_js_weight = self.get('training.augmix_js_weight', 12.0)
319
+ namespace.augmix_width = self.get('training.augmix_width', 3)
320
+ namespace.augmix_depth = self.get('training.augmix_depth', -1)
321
+ namespace.augmix_alpha = self.get('training.augmix_alpha', 1.0)
322
+ namespace.augmix_num_views = self.get('training.augmix_num_views', 2)
323
+ namespace.augmix_js_eps = self.get('training.augmix_js_eps', 1.0e-7)
324
+ namespace.loadSize = self.get('training.loadSize', 224)
325
+ namespace.cropSize = self.get('training.cropSize', 224)
326
+ namespace.gpu_ids = self.get('training.gpu_ids', '0')
327
+ namespace.name = self.get('training.name', 'AIGC_Detection')
328
+ namespace.resume_name = self.get('training.resume_name', None)
329
+
330
+ namespace.freeze_backbone = self.get('training.freeze_backbone', True)
331
+ namespace.trainable_blocks = self.get('training.trainable_blocks', 0)
332
+ namespace.head_hidden_dim = self.get('training.head_hidden_dim', None)
333
+ namespace.head_dropout = self.get('training.head_dropout', 0.1)
334
+ namespace.use_lora = self.get('training.use_lora', False)
335
+ namespace.lora_rank = self.get('training.lora_rank', 4)
336
+ namespace.lora_alpha = self.get('training.lora_alpha', 8)
337
+ namespace.lora_dropout = self.get('training.lora_dropout', 0.0)
338
+ namespace.lora_bias = self.get('training.lora_bias', 'none')
339
+ target_modules = self.get('training.lora_target_modules', None)
340
+ if isinstance(target_modules, str):
341
+ target_modules = [m.strip() for m in target_modules.split(',') if m.strip()]
342
+ namespace.lora_target_modules = target_modules
343
+ namespace.lora_target_last_n = self.get('training.lora_target_last_n', None)
344
+
345
+ namespace.dinov3_variant = self.get('training.dinov3_variant', 'vitl16')
346
+ namespace.dinov3_backend = self.get('training.dinov3_backend', 'official')
347
+ namespace.dinov3_repo_path = self.get('training.dinov3_repo_path', None)
348
+ namespace.dinov3_max_blocks = self.get('training.dinov3_max_blocks', None)
349
+ namespace.dinov3_weights = self.get('training.dinov3_weights', None)
350
+ namespace.dinov3_disable_rope_train_jitter = self.get(
351
+ 'training.dinov3_disable_rope_train_jitter',
352
+ False,
353
+ )
354
+ namespace.dinov3_accel_backend = self.get('training.dinov3_accel_backend', 'none')
355
+ namespace.dinov3_accel_compile = self.get('training.dinov3_accel_compile', False)
356
+ namespace.dinov3_accel_checkpointing = self.get('training.dinov3_accel_checkpointing', True)
357
+ namespace.dinov3_accel_checkpointing_full = self.get('training.dinov3_accel_checkpointing_full', False)
358
+ namespace.dinov3_accel_cudagraphs = self.get('training.dinov3_accel_cudagraphs', False)
359
+ namespace.dinov3_accel_preserve_loaded_weights = self.get(
360
+ 'training.dinov3_accel_preserve_loaded_weights',
361
+ True,
362
+ )
363
+ namespace.dinov3_accel_param_dtype = self.get('training.dinov3_accel_param_dtype', None)
364
+ namespace.dinov3_accel_reduce_dtype = self.get('training.dinov3_accel_reduce_dtype', None)
365
+ namespace.deepspeed_config_path = self.get('training.deepspeed_config_path', None)
366
+ namespace.deepspeed_zero_stage = self.get('training.deepspeed_zero_stage', 2)
367
+ namespace.deepspeed_grad_accum_steps = self.get('training.deepspeed_grad_accum_steps', None)
368
+ namespace.deepspeed_offload_optimizer_device = self.get(
369
+ 'training.deepspeed_offload_optimizer_device', 'none'
370
+ )
371
+ namespace.deepspeed_offload_param_device = self.get('training.deepspeed_offload_param_device', 'none')
372
+ namespace.full_finetune_enable = self.get('training.full_finetune_enable', False)
373
+ namespace.full_finetune_precision = self.get('training.full_finetune_precision', 'fp32')
374
+ namespace.full_finetune_grad_accum_steps = self.get('training.full_finetune_grad_accum_steps', 1)
375
+ namespace.full_finetune_gradient_checkpointing = self.get(
376
+ 'training.full_finetune_gradient_checkpointing',
377
+ False,
378
+ )
379
+ namespace.dinov3_use_concept_head = self.get('training.dinov3_use_concept_head', False)
380
+ namespace.dinov3_concept_matrix_path = self.get('training.dinov3_concept_matrix_path', None)
381
+ namespace.dinov3_concept_mapping_trainable = self.get('training.dinov3_concept_mapping_trainable', False)
382
+ namespace.dinov3_concept_mapping_bias = self.get('training.dinov3_concept_mapping_bias', False)
383
+ namespace.dinov3_concept_head_hidden_dim = self.get('training.dinov3_concept_head_hidden_dim', None)
384
+ namespace.dinov3_concept_head_dropout = self.get('training.dinov3_concept_head_dropout', None)
385
+ namespace.dinov3_concept_sparsity_ratio = self.get('training.dinov3_concept_sparsity_ratio', 0.0)
386
+ concept_eval = self.get('training.dinov3_concept_eval_sparsity', None)
387
+ if isinstance(concept_eval, str):
388
+ items = [item.strip() for item in concept_eval.split(',') if item.strip()]
389
+ concept_eval = [float(item) for item in items]
390
+ namespace.dinov3_concept_eval_sparsity = concept_eval
391
+ namespace.dinov3_concept_eval_log_path = self.get('training.dinov3_concept_eval_log_path', None)
392
+ # CLIP options (CLS + codebook top-k head)
393
+ namespace.clip_use_main_head = self.get('training.clip_use_main_head', True)
394
+ namespace.clip_codebook_path = self.get('training.clip_codebook_path', None)
395
+ namespace.clip_use_codebook_inject = self.get('training.clip_use_codebook_inject', True)
396
+ namespace.clip_codebook_dim = self.get('training.clip_codebook_dim', 1280)
397
+ namespace.clip_num_concepts = self.get('training.clip_num_concepts', 200)
398
+ namespace.clip_tau = self.get('training.clip_tau', 0.1)
399
+ namespace.clip_codebook_l2 = self.get('training.clip_codebook_l2', True)
400
+ namespace.clip_freeze_codebook = self.get('training.clip_freeze_codebook', True)
401
+ namespace.clip_override_codebook = self.get('training.clip_override_codebook', False)
402
+ namespace.clip_num_patches = self.get('training.clip_num_patches', None)
403
+ namespace.clip_cb_topk = self.get('training.clip_cb_topk', 20)
404
+ namespace.clip_cb_topr = self.get('training.clip_cb_topr', 8)
405
+ namespace.clip_cb_tau_w = self.get('training.clip_cb_tau_w', 0.1)
406
+ namespace.clip_cb_weight_mode = self.get('training.clip_cb_weight_mode', 'score')
407
+ namespace.clip_cb_mlp_hidden = self.get('training.clip_cb_mlp_hidden', None)
408
+ namespace.clip_cb_detach_tokens = self.get('training.clip_cb_detach_tokens', False)
409
+ namespace.clip_train_lora = self.get('training.clip_train_lora', True)
410
+ namespace.clip_train_fc = self.get('training.clip_train_fc', True)
411
+ namespace.clip_load_init_weights = self.get('training.clip_load_init_weights', True)
412
+ namespace.clip_cb_loss_weight = self.get('training.clip_cb_loss_weight', 1.0)
413
+ concept_loss = self.get('training.dinov3_concept_loss_weight', 1.0)
414
+ namespace.dinov3_concept_loss_weight = concept_loss
415
+ namespace.initial_eval = self.get('training.initial_eval', False)
416
+ namespace.clip_lora_rank = self.get('training.clip_lora_rank', 4)
417
+ namespace.clip_lora_alpha = self.get('training.clip_lora_alpha', 8)
418
+ namespace.clip_freeze_backbone = self.get('training.clip_freeze_backbone', True)
419
+ namespace.clip_model_path = self.get('models.pretrained.clip_model', None)
420
+ namespace.num_threads = self.get('system.num_threads', 8)
421
+ namespace.classes = ""
422
+ namespace.isTrain = bool(is_train)
423
+ namespace.pos_weight = self.get('training.pos_weight', None)
424
+ namespace.num_classes = self.get('training.num_classes', 1)
425
+ namespace.reverse = self.get('training.reverse', False)
426
+ namespace.save_backbone = self.get('training.save_backbone', False)
427
+
428
+ # Add missing parameters from base_options.py
429
+ namespace.mode = self.get('training.mode', 'binary')
430
+ namespace.class_bal = self.get('training.class_bal', False)
431
+ namespace.class_bal_strategy = self.get('training.class_bal_strategy', 'auto')
432
+ namespace.class_bal_strict = self.get('training.class_bal_strict', False)
433
+ namespace.serial_batches = self.get('training.serial_batches', False)
434
+ namespace.resize_or_crop = self.get('training.resize_or_crop', 'scale_and_crop')
435
+ namespace.no_flip = self.get('training.no_flip', False)
436
+ namespace.init_type = self.get('training.init_type', 'normal')
437
+ namespace.init_gain = self.get('training.init_gain', 0.02)
438
+ namespace.suffix = self.get('training.suffix', '')
439
+ namespace.epoch = self.get('training.epoch', 'latest')
440
+
441
+ # Data augmentation parameters
442
+ namespace.rz_interp = self.get('training.rz_interp', 'bilinear')
443
+ namespace.blur_prob = self.get('training.blur_prob', 0.0)
444
+ namespace.blur_sig = self.get('training.blur_sig', '0.5')
445
+ namespace.jpg_prob = self.get('training.jpg_prob', 0.0)
446
+ namespace.jpg_method = self.get('training.jpg_method', 'cv2')
447
+ namespace.jpg_qual = self.get('training.jpg_qual', '75')
448
+ # 兼容 legacy 预处理(对齐 NPR:resize -> crop -> ImageNet 归一化)
449
+ namespace.legacy_preprocess = self.get('training.legacy_preprocess', False)
450
+
451
+ # Testing parameters from test_options.py
452
+ namespace.model_path = self.get('testing.model_path', '')
453
+ namespace.no_resize = self.get('training.no_resize', False)
454
+ namespace.no_crop = self.get('testing.no_crop', False)
455
+ namespace.eval = self.get('testing.eval', False)
456
+ namespace.earlystop_epoch = self.get('training.earlystop_epoch', 15)
457
+ # Optional: dump codebook top-k patch coords during testing
458
+ namespace.codebook_coords_path = self.get('testing.codebook_coords_path', None)
459
+ namespace.codebook_coords_limit = self.get('testing.codebook_coords_limit', None)
460
+ robustness_cfg = self.get_testing_robustness()
461
+ namespace.robustness_preset = robustness_cfg['preset']
462
+ namespace.robustness_type = robustness_cfg['type']
463
+ namespace.robustness_chain = robustness_cfg['chain']
464
+ namespace.robustness_jpeg_quality = robustness_cfg['params']['jpeg_quality']
465
+ namespace.robustness_gaussian_blur_sigma = robustness_cfg['params']['gaussian_blur_sigma']
466
+ namespace.robustness_gaussian_noise_std = robustness_cfg['params']['gaussian_noise_std']
467
+ namespace.robustness_downsample_scale = robustness_cfg['params']['downsample_scale']
468
+ namespace.robustness_cj_brightness = robustness_cfg['params']['cj_brightness']
469
+ namespace.robustness_cj_contrast = robustness_cfg['params']['cj_contrast']
470
+ namespace.robustness_cj_saturation = robustness_cfg['params']['cj_saturation']
471
+ namespace.robustness_cj_hue = robustness_cfg['params']['cj_hue']
472
+
473
+ # Training parameters from train_options.py
474
+ namespace.optim = self.get('training.optim', 'adam')
475
+ namespace.new_optim = self.get('training.new_optim', False)
476
+ namespace.save_latest_freq = self.get('training.save_latest_freq', 2000)
477
+ namespace.save_epoch_freq = self.get('training.save_epoch_freq', 20)
478
+ namespace.continue_train = self.get('training.continue_train', False)
479
+ namespace.epoch_count = self.get('training.epoch_count', 1)
480
+ namespace.last_epoch = self.get('training.last_epoch', -1)
481
+ namespace.beta1 = self.get('training.beta1', 0.9)
482
+
483
+ def flatten_config(config, parent_key=''):
484
+ items = []
485
+ for k, v in config.items():
486
+ new_key = f"{parent_key}_{k}" if parent_key else k
487
+ if isinstance(v, dict):
488
+ items.extend(flatten_config(v, new_key).items())
489
+ else:
490
+ items.append((new_key, v))
491
+ return dict(items)
492
+
493
+ flat_config = flatten_config(self.config)
494
+
495
+ # Add all flattened config items
496
+ for k, v in flat_config.items():
497
+ setattr(namespace, k, v)
498
+
499
+ return namespace
500
+
501
+ def save_config(self, output_path: str):
502
+ """
503
+ Save current configuration to a YAML file.
504
+
505
+ Args:
506
+ output_path: Path to save the configuration file
507
+ """
508
+ with open(output_path, 'w', encoding='utf-8') as f:
509
+ yaml.dump(self.config, f, default_flow_style=False, allow_unicode=True)
510
+
511
+ def print_config(self):
512
+ """
513
+ Print the current configuration in a formatted way.
514
+ """
515
+ print("=" * 80)
516
+ print("Configuration:")
517
+ print("=" * 80)
518
+
519
+ def print_dict(d, indent=0):
520
+ for k, v in d.items():
521
+ if isinstance(v, dict):
522
+ print(" " * indent + f"{k}:")
523
+ print_dict(v, indent + 1)
524
+ else:
525
+ print(" " * indent + f"{k}: {v}")
526
+
527
+ print_dict(self.config)
528
+ print("=" * 80)
529
+
530
+
531
+ def create_argument_parser():
532
+ """
533
+ Create argument parser for command line interface.
534
+
535
+ Returns:
536
+ ArgumentParser object
537
+ """
538
+ parser = argparse.ArgumentParser(
539
+ description="AIGC Detection Training with Configuration File Support",
540
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter
541
+ )
542
+
543
+ # Configuration file
544
+ parser.add_argument(
545
+ '--config',
546
+ type=str,
547
+ default='config.yaml',
548
+ help='Path to configuration file'
549
+ )
550
+
551
+ # Override options
552
+ parser.add_argument(
553
+ '--train_dataroot',
554
+ type=str,
555
+ help='Training data directory (overrides config)'
556
+ )
557
+ parser.add_argument(
558
+ '--test_dataroot',
559
+ type=str,
560
+ help='Test data directory (overrides config)'
561
+ )
562
+ parser.add_argument(
563
+ '--checkpoints_dir',
564
+ type=str,
565
+ help='Checkpoints directory (overrides config)'
566
+ )
567
+ parser.add_argument(
568
+ '--lr',
569
+ type=float,
570
+ help='Learning rate (overrides config)'
571
+ )
572
+ parser.add_argument(
573
+ '--batch_size',
574
+ type=int,
575
+ help='Batch size (overrides config)'
576
+ )
577
+ parser.add_argument(
578
+ '--niter',
579
+ type=int,
580
+ help='Number of iterations (overrides config)'
581
+ )
582
+ parser.add_argument(
583
+ '--gpu_ids',
584
+ type=str,
585
+ help='GPU IDs (overrides config)'
586
+ )
587
+ parser.add_argument(
588
+ '--name',
589
+ type=str,
590
+ help='Experiment name (overrides config)'
591
+ )
592
+
593
+ return parser
594
+
595
+
596
+ def load_config_from_args(args: argparse.Namespace) -> ConfigLoader:
597
+ """
598
+ Load configuration from command line arguments.
599
+
600
+ Args:
601
+ args: Parsed command line arguments
602
+
603
+ Returns:
604
+ ConfigLoader instance
605
+ """
606
+ config_loader = ConfigLoader(args.config)
607
+ config_loader.update_from_args(args)
608
+ config_loader.create_directories()
609
+
610
+ return config_loader
611
+
612
+
613
+ if __name__ == "__main__":
614
+ # Test the configuration loader
615
+ parser = create_argument_parser()
616
+ args = parser.parse_args()
617
+
618
+ config_loader = load_config_from_args(args)
619
+ config_loader.print_config()
detectors/ForensicConcept/upstream/configs/clip_codebook.yaml ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stage 2: initialize from the stage-1 CLIP-LoRA detector and train the
2
+ # patch-token codebook branch. The released raw centers are L2-normalized at load time.
3
+ data:
4
+ train_dataroot: "./datasets"
5
+ train_split: "train"
6
+ test_dataroot: "./datasets/test"
7
+ val_split: "val"
8
+
9
+ models:
10
+ checkpoints_dir: "./checkpoints"
11
+ pretrained:
12
+ clip_model: "./weights/backbones/ViT-L-14.pt"
13
+
14
+ training:
15
+ trainmode: "lora"
16
+ modelname: "CLIP:ViT-L/14"
17
+ clip_use_main_head: true
18
+ clip_train_fc: true
19
+ clip_train_lora: false
20
+ clip_lora_rank: 4
21
+ clip_lora_alpha: 8
22
+ clip_freeze_backbone: true
23
+ clip_load_init_weights: true
24
+
25
+ clip_use_codebook_inject: true
26
+ clip_codebook_path: "./assets/codebooks/cleandift_codebook.npy"
27
+ clip_codebook_dim: 1280
28
+ clip_num_concepts: 200
29
+ clip_tau: 0.1
30
+ clip_codebook_l2: true
31
+ clip_freeze_codebook: true
32
+ clip_cb_loss_weight: 1.0
33
+ clip_num_patches: 256
34
+ clip_cb_topk: 20
35
+ clip_cb_topr: 8
36
+ clip_cb_tau_w: 0.05
37
+ clip_cb_weight_mode: "score"
38
+ clip_cb_mlp_hidden: 768
39
+ clip_cb_detach_tokens: true
40
+
41
+ num_classes: 1
42
+ legacy_preprocess: true
43
+ optim: "adam"
44
+ beta1: 0.9
45
+ weight_decay: 0.0
46
+ lr: 0.00002
47
+ lr_decay_factor: 0.9
48
+ lr_min: 0.000001
49
+ batch_size: 32
50
+ niter: 2
51
+ delr_freq: 5
52
+ loss_freq: 100
53
+
54
+ data_aug: true
55
+ loadSize: 224
56
+ cropSize: 224
57
+ class_bal: false
58
+ serial_batches: false
59
+
60
+ seed: 100
61
+ gpu_ids: "0"
62
+ name: "clip_vitl14_codebook_stage2"
63
+ initial_eval: false
64
+ continue_train: true
65
+ epoch: "./weights/detectors/clip_vitl14_lora_stage1.pth"
66
+ new_optim: true
67
+ save_last_checkpoint: true
68
+
69
+ testing:
70
+ batch_size: 64
71
+ data_aug: false
72
+ no_resize: false
73
+ no_crop: false
74
+ groups:
75
+ - name: "example_test"
76
+ path: "./datasets/test/example"
77
+ mode: "single"
78
+
79
+ logging:
80
+ tensorboard: true
81
+ log_file: "training.log"
82
+ print_options: true
83
+
84
+ system:
85
+ num_threads: 8
detectors/ForensicConcept/upstream/configs/clip_lora.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stage 1: train the CLIP ViT-L/14 classifier and visual qkv LoRA adapters.
2
+ data:
3
+ train_dataroot: "./datasets"
4
+ train_split: "train"
5
+ test_dataroot: "./datasets/test"
6
+ val_split: "val"
7
+
8
+ models:
9
+ checkpoints_dir: "./checkpoints"
10
+ pretrained:
11
+ clip_model: "./weights/backbones/ViT-L-14.pt"
12
+
13
+ training:
14
+ trainmode: "lora"
15
+ modelname: "CLIP:ViT-L/14"
16
+ clip_use_main_head: true
17
+ clip_train_fc: true
18
+ clip_train_lora: true
19
+ clip_lora_rank: 4
20
+ clip_lora_alpha: 8
21
+ clip_freeze_backbone: true
22
+ clip_load_init_weights: true
23
+ clip_use_codebook_inject: false
24
+
25
+ num_classes: 1
26
+ legacy_preprocess: true
27
+ optim: "adam"
28
+ beta1: 0.9
29
+ weight_decay: 0.0
30
+ lr: 0.00002
31
+ lr_decay_factor: 0.9
32
+ lr_min: 0.000001
33
+ batch_size: 32
34
+ niter: 98
35
+ delr_freq: 10
36
+ loss_freq: 100
37
+
38
+ data_aug: true
39
+ loadSize: 224
40
+ cropSize: 224
41
+ class_bal: false
42
+ serial_batches: false
43
+
44
+ seed: 100
45
+ gpu_ids: "0"
46
+ name: "clip_vitl14_lora_stage1"
47
+ initial_eval: true
48
+ continue_train: false
49
+ epoch: "latest"
50
+ save_last_checkpoint: true
51
+
52
+ testing:
53
+ batch_size: 64
54
+ data_aug: false
55
+ no_resize: false
56
+ no_crop: false
57
+ groups:
58
+ - name: "example_test"
59
+ path: "./datasets/test/example"
60
+ mode: "single"
61
+
62
+ logging:
63
+ tensorboard: true
64
+ log_file: "training.log"
65
+ print_options: true
66
+
67
+ system:
68
+ num_threads: 8
detectors/ForensicConcept/upstream/configs/dinov3_concept.yaml ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DINOv3 LoRA with the concept head used by the core method.
2
+ # Replace dataset, backbone weight, and concept matrix paths before running.
3
+ data:
4
+ train_dataroot: "./datasets"
5
+ train_split: "train"
6
+ test_dataroot: "./datasets/test"
7
+ val_split: "val"
8
+
9
+ models:
10
+ checkpoints_dir: "./checkpoints"
11
+
12
+ training:
13
+ trainmode: "dinov3"
14
+ dinov3_variant: "vitl16"
15
+ dinov3_backend: "official"
16
+ dinov3_repo_path: "./external/dinov3"
17
+ dinov3_weights: "./weights/backbones/dinov3-vitl16/model.safetensors"
18
+ dinov3_accel_backend: "none"
19
+
20
+ freeze_backbone: true
21
+ trainable_blocks: 0
22
+ head_hidden_dim: 512
23
+ head_dropout: 0.2
24
+ use_lora: true
25
+ lora_rank: 4
26
+ lora_alpha: 8
27
+ lora_dropout: 0.0
28
+ lora_bias: "none"
29
+ lora_target_modules: []
30
+ lora_target_last_n:
31
+
32
+ dinov3_use_concept_head: true
33
+ dinov3_concept_matrix_path: "./weights/concepts/dinov3_concept_matrix.npy"
34
+ dinov3_concept_mapping_trainable: true
35
+ dinov3_concept_mapping_bias: false
36
+ dinov3_concept_head_hidden_dim:
37
+ dinov3_concept_head_dropout: 0.0
38
+ dinov3_concept_sparsity_ratio: 0.0
39
+ dinov3_concept_loss_weight: 1.0
40
+ dinov3_concept_eval_sparsity: [0.1, 0.3, 0.5, 0.7, 0.9]
41
+
42
+ num_classes: 1
43
+ optim: "adam"
44
+ beta1: 0.9
45
+ weight_decay: 0.0
46
+ lr: 0.00002
47
+ lr_decay_factor: 0.9
48
+ lr_min: 0.000001
49
+ batch_size: 32
50
+ niter: 5
51
+ delr_freq: 5
52
+ loss_freq: 100
53
+
54
+ data_aug: true
55
+ no_resize: false
56
+ no_flip: false
57
+ loadSize: 224
58
+ cropSize: 224
59
+ class_bal: false
60
+ serial_batches: false
61
+
62
+ seed: 100
63
+ gpu_ids: "0"
64
+ name: "dinov3_vitl16_concept_stage2"
65
+ initial_eval: false
66
+ continue_train: true
67
+ epoch: "./weights/detectors/dinov3_vitl16_lora_stage1.pth"
68
+ new_optim: true
69
+ save_last_checkpoint: true
70
+
71
+ testing:
72
+ batch_size: 64
73
+ data_aug: false
74
+ no_resize: false
75
+ no_crop: false
76
+ groups:
77
+ - name: "example_test"
78
+ path: "./datasets/test/example"
79
+ mode: "single"
80
+
81
+ logging:
82
+ tensorboard: true
83
+ log_file: "training.log"
84
+ print_options: true
85
+
86
+ system:
87
+ num_threads: 8
88
+ ddp_timeout_minutes: 180
detectors/ForensicConcept/upstream/configs/dinov3_lora.yaml ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reproduction template. Replace dataset and weight paths before running.
2
+ data:
3
+ train_dataroot: "./datasets"
4
+ train_split: "train"
5
+ test_dataroot: "./datasets/test"
6
+ val_split: "val"
7
+
8
+ models:
9
+ checkpoints_dir: "./checkpoints"
10
+
11
+ training:
12
+ trainmode: "dinov3"
13
+ dinov3_variant: "vitl16"
14
+ dinov3_backend: "official"
15
+ dinov3_repo_path: "./external/dinov3"
16
+ dinov3_weights: "./weights/backbones/dinov3-vitl16/model.safetensors"
17
+ dinov3_accel_backend: "none"
18
+
19
+ freeze_backbone: true
20
+ trainable_blocks: 0
21
+ head_hidden_dim: 512
22
+ head_dropout: 0.2
23
+ use_lora: true
24
+ lora_rank: 4
25
+ lora_alpha: 8
26
+ lora_dropout: 0.0
27
+ lora_bias: "none"
28
+ lora_target_modules: []
29
+ lora_target_last_n:
30
+
31
+ num_classes: 1
32
+ optim: "adam"
33
+ beta1: 0.9
34
+ weight_decay: 0.0
35
+ lr: 0.0001
36
+ lr_decay_factor: 0.9
37
+ lr_min: 0.000001
38
+ batch_size: 32
39
+ niter: 10
40
+ delr_freq: 5
41
+ loss_freq: 100
42
+
43
+ data_aug: true
44
+ no_resize: false
45
+ no_flip: false
46
+ loadSize: 224
47
+ cropSize: 224
48
+ class_bal: false
49
+ serial_batches: false
50
+
51
+ seed: 100
52
+ gpu_ids: "0"
53
+ name: "dinov3_vitl16_lora_stage1"
54
+ initial_eval: false
55
+ continue_train: false
56
+ epoch: "latest"
57
+ save_last_checkpoint: true
58
+
59
+ testing:
60
+ batch_size: 64
61
+ data_aug: false
62
+ no_resize: false
63
+ no_crop: false
64
+ groups:
65
+ - name: "example_test"
66
+ path: "./datasets/test/example"
67
+ mode: "single"
68
+
69
+ logging:
70
+ tensorboard: true
71
+ log_file: "training.log"
72
+ print_options: true
73
+
74
+ system:
75
+ num_threads: 8
76
+ ddp_timeout_minutes: 180
detectors/ForensicConcept/upstream/data/__init__.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from torch.utils.data.sampler import WeightedRandomSampler
4
+ from torch.utils.data import Sampler
5
+ import math
6
+
7
+ from .datasets import dataset_folder, infer_single_label_from_root, is_dfdc_train_faces_root
8
+
9
+ '''
10
+ def get_dataset(opt):
11
+ dset_lst = []
12
+ for cls in opt.classes:
13
+ root = opt.dataroot + '/' + cls
14
+ dset = dataset_folder(opt, root)
15
+ dset_lst.append(dset)
16
+ return torch.utils.data.ConcatDataset(dset_lst)
17
+ '''
18
+
19
+ def _build_dataset_from_root(opt, root):
20
+ import os
21
+ if not root or not os.path.exists(root):
22
+ raise FileNotFoundError(f"Training dataroot not found: {root}")
23
+
24
+ if infer_single_label_from_root(root) is not None:
25
+ return dataset_folder(opt, root)
26
+ if is_dfdc_train_faces_root(root, opt):
27
+ return dataset_folder(opt, root)
28
+
29
+ if len(opt.classes) == 0:
30
+ classes = [
31
+ cls for cls in os.listdir(root)
32
+ if not cls.startswith('.') and os.path.isdir(os.path.join(root, cls))
33
+ ]
34
+ else:
35
+ classes = opt.classes
36
+
37
+ class_set = set(classes)
38
+ has_standard_binary = {'0_real', '1_fake'}.issubset(class_set)
39
+ has_reversed_binary = {'0_fake', '1_real'}.issubset(class_set)
40
+ has_raw_synthesis = {'raw', 'synthesis'}.issubset(class_set)
41
+ has_real_fake = {'real', 'fake'}.issubset(class_set)
42
+
43
+ if not (has_standard_binary or has_reversed_binary or has_raw_synthesis or has_real_fake):
44
+ dset_lst = []
45
+ for cls in classes:
46
+ sub_root = os.path.join(root, cls)
47
+ if not os.path.isdir(sub_root):
48
+ continue
49
+ dset = dataset_folder(opt, sub_root)
50
+ dset_lst.append(dset)
51
+ if not dset_lst:
52
+ # Fallback for flat-labeled folders or alternative binary aliases
53
+ # handled inside data/datasets.py binary_dataset.
54
+ return dataset_folder(opt, root)
55
+ return torch.utils.data.ConcatDataset(dset_lst)
56
+ return dataset_folder(opt, root)
57
+
58
+
59
+ def _coerce_bool(value, default=False):
60
+ if value is None:
61
+ return bool(default)
62
+ if isinstance(value, bool):
63
+ return value
64
+ if isinstance(value, (int, float)):
65
+ return bool(value)
66
+ if isinstance(value, str):
67
+ v = value.strip().lower()
68
+ if v in {"1", "true", "yes", "y", "on"}:
69
+ return True
70
+ if v in {"0", "false", "no", "n", "off"}:
71
+ return False
72
+ return bool(value)
73
+
74
+
75
+ def _get_first_opt(opt, names, default=None):
76
+ for name in names:
77
+ if hasattr(opt, name):
78
+ value = getattr(opt, name)
79
+ if value is not None:
80
+ return value
81
+ return default
82
+
83
+
84
+ class DynamicExtraSamplingDataset(torch.utils.data.Dataset):
85
+ """
86
+ Dataset wrapper for: main dataset + per-epoch sampled subset from external pools.
87
+
88
+ Typical use:
89
+ - main: training_data_final
90
+ - extra: FFPP/CelebDF/DFDC pools
91
+ - each epoch: sample len(main) items from extra (optionally 1:1 real/fake)
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ main_dataset,
97
+ extra_dataset,
98
+ *,
99
+ match_main_count=True,
100
+ balance_binary=True,
101
+ seed=0,
102
+ log_first_n_epochs=0,
103
+ ):
104
+ self.main_dataset = main_dataset
105
+ self.extra_dataset = extra_dataset
106
+ self.main_len = int(len(main_dataset))
107
+ self.extra_len = int(len(extra_dataset))
108
+ self.match_main_count = bool(match_main_count)
109
+ self.balance_binary = bool(balance_binary)
110
+ self.seed = int(seed)
111
+ self.log_first_n_epochs = max(0, int(log_first_n_epochs))
112
+ self.current_epoch = 0
113
+
114
+ self.sample_extra_count = self.main_len if self.match_main_count else self.extra_len
115
+ self._all_extra_indices = torch.arange(self.extra_len, dtype=torch.long)
116
+ self._sampled_extra_indices = torch.empty(0, dtype=torch.long)
117
+ self._sampled_extra_targets = []
118
+
119
+ try:
120
+ self._main_targets = [int(t) for t in _collect_targets(self.main_dataset)]
121
+ except Exception:
122
+ self._main_targets = None
123
+ try:
124
+ self._extra_targets = [int(t) for t in _collect_targets(self.extra_dataset)]
125
+ except Exception:
126
+ self._extra_targets = None
127
+
128
+ self._extra_has_binary_targets = False
129
+ self._extra_real_pool = torch.empty(0, dtype=torch.long)
130
+ self._extra_fake_pool = torch.empty(0, dtype=torch.long)
131
+ if self._extra_targets is not None and len(self._extra_targets) == self.extra_len:
132
+ real_idx = [i for i, t in enumerate(self._extra_targets) if int(t) == 0]
133
+ fake_idx = [i for i, t in enumerate(self._extra_targets) if int(t) == 1]
134
+ if real_idx and fake_idx:
135
+ self._extra_has_binary_targets = True
136
+ self._extra_real_pool = torch.as_tensor(real_idx, dtype=torch.long)
137
+ self._extra_fake_pool = torch.as_tensor(fake_idx, dtype=torch.long)
138
+
139
+ self.set_epoch(0)
140
+
141
+ @staticmethod
142
+ def _sample_pool(pool, n, generator):
143
+ if n <= 0:
144
+ return torch.empty(0, dtype=torch.long)
145
+ m = int(pool.numel())
146
+ if m <= 0:
147
+ return torch.empty(0, dtype=torch.long)
148
+ if m >= n:
149
+ perm = torch.randperm(m, generator=generator)[:n]
150
+ return pool[perm]
151
+ choice = torch.randint(low=0, high=m, size=(n,), generator=generator)
152
+ return pool[choice]
153
+
154
+ def _sample_extra_indices_for_epoch(self, epoch):
155
+ if self.extra_len <= 0 or self.sample_extra_count <= 0:
156
+ return torch.empty(0, dtype=torch.long)
157
+
158
+ g = torch.Generator()
159
+ g.manual_seed(self.seed + int(epoch))
160
+ n = int(self.sample_extra_count)
161
+
162
+ if self.balance_binary and self._extra_has_binary_targets:
163
+ n_real = n // 2
164
+ n_fake = n - n_real
165
+ real_pick = self._sample_pool(self._extra_real_pool, n_real, g)
166
+ fake_pick = self._sample_pool(self._extra_fake_pool, n_fake, g)
167
+ sampled = torch.cat([real_pick, fake_pick], dim=0)
168
+ if sampled.numel() > 1:
169
+ order = torch.randperm(sampled.numel(), generator=g)
170
+ sampled = sampled[order]
171
+ return sampled
172
+
173
+ if self.extra_len >= n:
174
+ perm = torch.randperm(self.extra_len, generator=g)[:n]
175
+ return self._all_extra_indices[perm]
176
+ choice = torch.randint(low=0, high=self.extra_len, size=(n,), generator=g)
177
+ return self._all_extra_indices[choice]
178
+
179
+ def set_epoch(self, epoch):
180
+ self.current_epoch = int(epoch)
181
+ self._sampled_extra_indices = self._sample_extra_indices_for_epoch(self.current_epoch)
182
+
183
+ if self._extra_targets is not None and len(self._extra_targets) == self.extra_len:
184
+ self._sampled_extra_targets = [
185
+ int(self._extra_targets[int(i)]) for i in self._sampled_extra_indices.tolist()
186
+ ]
187
+ else:
188
+ self._sampled_extra_targets = []
189
+
190
+ if self.log_first_n_epochs > 0 and self.current_epoch < self.log_first_n_epochs:
191
+ n_main = self.main_len
192
+ n_extra = int(self._sampled_extra_indices.numel())
193
+ if self._sampled_extra_targets:
194
+ extra_real = sum(1 for t in self._sampled_extra_targets if t == 0)
195
+ extra_fake = n_extra - extra_real
196
+ print(
197
+ f"[DataMix] epoch={self.current_epoch} main={n_main}, "
198
+ f"sampled_extra={n_extra} (real={extra_real}, fake={extra_fake})"
199
+ )
200
+ else:
201
+ print(
202
+ f"[DataMix] epoch={self.current_epoch} main={n_main}, "
203
+ f"sampled_extra={n_extra}"
204
+ )
205
+
206
+ @property
207
+ def targets(self):
208
+ if self._main_targets is None or self._extra_targets is None:
209
+ raise AttributeError("DynamicExtraSamplingDataset has no stable targets metadata")
210
+ return list(self._main_targets) + list(self._sampled_extra_targets)
211
+
212
+ def __len__(self):
213
+ return self.main_len + int(self._sampled_extra_indices.numel())
214
+
215
+ def __getitem__(self, index):
216
+ idx = int(index)
217
+ if idx < self.main_len:
218
+ return self.main_dataset[idx]
219
+ extra_idx = int(self._sampled_extra_indices[idx - self.main_len].item())
220
+ return self.extra_dataset[extra_idx]
221
+
222
+
223
+ def get_dataset(opt):
224
+ import os
225
+
226
+ extra_roots = getattr(opt, "extra_train_roots", None) or []
227
+ if isinstance(extra_roots, str):
228
+ extra_roots = [p.strip() for p in extra_roots.split(",") if p.strip()]
229
+
230
+ dynamic_sampling_enabled = _coerce_bool(
231
+ _get_first_opt(
232
+ opt,
233
+ [
234
+ "dynamic_extra_sampling_enable",
235
+ "data_dynamic_extra_sampling_enable",
236
+ ],
237
+ False,
238
+ ),
239
+ default=False,
240
+ )
241
+ dynamic_match_main_count = _coerce_bool(
242
+ _get_first_opt(
243
+ opt,
244
+ [
245
+ "dynamic_extra_sampling_match_main_count",
246
+ "data_dynamic_extra_sampling_match_main_count",
247
+ ],
248
+ True,
249
+ ),
250
+ default=True,
251
+ )
252
+ dynamic_balance_binary = _coerce_bool(
253
+ _get_first_opt(
254
+ opt,
255
+ [
256
+ "dynamic_extra_sampling_balance_binary",
257
+ "data_dynamic_extra_sampling_balance_binary",
258
+ ],
259
+ True,
260
+ ),
261
+ default=True,
262
+ )
263
+ dynamic_seed = int(
264
+ _get_first_opt(
265
+ opt,
266
+ [
267
+ "dynamic_extra_sampling_seed",
268
+ "data_dynamic_extra_sampling_seed",
269
+ "seed",
270
+ ],
271
+ 0,
272
+ )
273
+ )
274
+ dynamic_log_first_n_epochs = int(
275
+ _get_first_opt(
276
+ opt,
277
+ [
278
+ "dynamic_extra_sampling_log_first_n_epochs",
279
+ "data_dynamic_extra_sampling_log_first_n_epochs",
280
+ ],
281
+ 0,
282
+ )
283
+ )
284
+
285
+ if bool(getattr(opt, "isTrain", False)) and dynamic_sampling_enabled and extra_roots:
286
+ main_root = os.path.abspath(opt.dataroot)
287
+ main_dataset = _build_dataset_from_root(opt, main_root)
288
+
289
+ unique_extra_roots = []
290
+ seen_extra = set()
291
+ for r in extra_roots:
292
+ if not r:
293
+ continue
294
+ r_abs = os.path.abspath(r)
295
+ if r_abs == main_root:
296
+ continue
297
+ if r_abs in seen_extra:
298
+ continue
299
+ seen_extra.add(r_abs)
300
+ unique_extra_roots.append(r_abs)
301
+
302
+ extra_datasets = [_build_dataset_from_root(opt, root) for root in unique_extra_roots]
303
+ if not extra_datasets:
304
+ return main_dataset
305
+
306
+ extra_dataset = extra_datasets[0]
307
+ if len(extra_datasets) > 1:
308
+ extra_dataset = torch.utils.data.ConcatDataset(extra_datasets)
309
+
310
+ mixed_dataset = DynamicExtraSamplingDataset(
311
+ main_dataset,
312
+ extra_dataset,
313
+ match_main_count=dynamic_match_main_count,
314
+ balance_binary=dynamic_balance_binary,
315
+ seed=dynamic_seed,
316
+ log_first_n_epochs=dynamic_log_first_n_epochs,
317
+ )
318
+ return mixed_dataset
319
+
320
+ roots = [opt.dataroot]
321
+ roots.extend(extra_roots)
322
+
323
+ unique_roots = []
324
+ seen = set()
325
+ for r in roots:
326
+ if not r:
327
+ continue
328
+ r_abs = os.path.abspath(r)
329
+ if r_abs in seen:
330
+ continue
331
+ seen.add(r_abs)
332
+ unique_roots.append(r_abs)
333
+
334
+ datasets_all = []
335
+ for root in unique_roots:
336
+ dset = _build_dataset_from_root(opt, root)
337
+ datasets_all.append(dset)
338
+
339
+ if len(datasets_all) == 1:
340
+ return datasets_all[0]
341
+ return torch.utils.data.ConcatDataset(datasets_all)
342
+
343
+ def _collect_targets(dataset):
344
+ targets = getattr(dataset, 'targets', None)
345
+ if targets is not None:
346
+ return [int(t) for t in targets]
347
+ if hasattr(dataset, 'datasets'):
348
+ merged = []
349
+ for d in dataset.datasets:
350
+ merged.extend(_collect_targets(d))
351
+ return merged
352
+ raise AttributeError('Cannot build balanced sampler: dataset has no targets attribute')
353
+
354
+
355
+ class DistributedWeightedSampler(Sampler):
356
+ """DDP-friendly class-balanced sampler using weighted multinomial sampling."""
357
+ def __init__(self, sample_weights, num_samples, num_replicas, rank, seed=0):
358
+ self.weights = torch.as_tensor(sample_weights, dtype=torch.double)
359
+ self.num_samples = int(num_samples)
360
+ self.num_replicas = int(num_replicas)
361
+ self.rank = int(rank)
362
+ self.seed = int(seed)
363
+ self.epoch = 0
364
+ self.total_size = self.num_samples * self.num_replicas
365
+
366
+ def __iter__(self):
367
+ g = torch.Generator()
368
+ g.manual_seed(self.seed + self.epoch)
369
+ sampled = torch.multinomial(
370
+ self.weights,
371
+ self.total_size,
372
+ replacement=True,
373
+ generator=g,
374
+ )
375
+ rank_samples = sampled[self.rank:self.total_size:self.num_replicas]
376
+ return iter(rank_samples.tolist())
377
+
378
+ def __len__(self):
379
+ return self.num_samples
380
+
381
+ def set_epoch(self, epoch):
382
+ self.epoch = int(epoch)
383
+
384
+
385
+ class ClassUniformSampler(Sampler):
386
+ """Class-uniform sampler: each epoch enforces near-equal samples per class."""
387
+ def __init__(self, class_to_indices, num_samples, seed=0):
388
+ if not class_to_indices:
389
+ raise ValueError("class_to_indices must not be empty")
390
+ self.class_to_indices = {
391
+ int(k): torch.as_tensor(v, dtype=torch.long)
392
+ for k, v in class_to_indices.items()
393
+ if len(v) > 0
394
+ }
395
+ if not self.class_to_indices:
396
+ raise ValueError("class_to_indices has no non-empty classes")
397
+ self.classes = sorted(self.class_to_indices.keys())
398
+ self.num_samples = int(num_samples)
399
+ self.seed = int(seed)
400
+ self.epoch = 0
401
+
402
+ @staticmethod
403
+ def _draw(pool, n, generator):
404
+ if n <= 0:
405
+ return torch.empty(0, dtype=torch.long)
406
+ m = int(pool.numel())
407
+ if m <= 0:
408
+ raise ValueError("Cannot draw from an empty class pool")
409
+ if m >= n:
410
+ perm = torch.randperm(m, generator=generator)[:n]
411
+ return pool[perm]
412
+ idx = torch.randint(low=0, high=m, size=(n,), generator=generator)
413
+ return pool[idx]
414
+
415
+ def __iter__(self):
416
+ g = torch.Generator()
417
+ g.manual_seed(self.seed + self.epoch)
418
+ num_classes = len(self.classes)
419
+ base = self.num_samples // num_classes
420
+ rem = self.num_samples % num_classes
421
+
422
+ chunks = []
423
+ for i, cls in enumerate(self.classes):
424
+ need = base + (1 if i < rem else 0)
425
+ chunks.append(self._draw(self.class_to_indices[cls], need, g))
426
+ sampled = torch.cat(chunks, dim=0)
427
+ order = torch.randperm(sampled.numel(), generator=g)
428
+ sampled = sampled[order]
429
+ return iter(sampled.tolist())
430
+
431
+ def __len__(self):
432
+ return self.num_samples
433
+
434
+ def set_epoch(self, epoch):
435
+ self.epoch = int(epoch)
436
+
437
+
438
+ class DistributedClassUniformSampler(Sampler):
439
+ """DDP-friendly class-uniform sampler with rank-wise sharding."""
440
+ def __init__(self, class_to_indices, num_samples, num_replicas, rank, seed=0):
441
+ if not class_to_indices:
442
+ raise ValueError("class_to_indices must not be empty")
443
+ self.class_to_indices = {
444
+ int(k): torch.as_tensor(v, dtype=torch.long)
445
+ for k, v in class_to_indices.items()
446
+ if len(v) > 0
447
+ }
448
+ if not self.class_to_indices:
449
+ raise ValueError("class_to_indices has no non-empty classes")
450
+ self.classes = sorted(self.class_to_indices.keys())
451
+ self.num_samples = int(num_samples)
452
+ self.num_replicas = int(num_replicas)
453
+ self.rank = int(rank)
454
+ self.seed = int(seed)
455
+ self.epoch = 0
456
+ self.total_size = self.num_samples * self.num_replicas
457
+
458
+ @staticmethod
459
+ def _draw(pool, n, generator):
460
+ if n <= 0:
461
+ return torch.empty(0, dtype=torch.long)
462
+ m = int(pool.numel())
463
+ if m <= 0:
464
+ raise ValueError("Cannot draw from an empty class pool")
465
+ if m >= n:
466
+ perm = torch.randperm(m, generator=generator)[:n]
467
+ return pool[perm]
468
+ idx = torch.randint(low=0, high=m, size=(n,), generator=generator)
469
+ return pool[idx]
470
+
471
+ def __iter__(self):
472
+ g = torch.Generator()
473
+ g.manual_seed(self.seed + self.epoch)
474
+ num_classes = len(self.classes)
475
+ base = self.total_size // num_classes
476
+ rem = self.total_size % num_classes
477
+
478
+ chunks = []
479
+ for i, cls in enumerate(self.classes):
480
+ need = base + (1 if i < rem else 0)
481
+ chunks.append(self._draw(self.class_to_indices[cls], need, g))
482
+ sampled = torch.cat(chunks, dim=0)
483
+ order = torch.randperm(sampled.numel(), generator=g)
484
+ sampled = sampled[order]
485
+
486
+ rank_samples = sampled[self.rank:self.total_size:self.num_replicas]
487
+ return iter(rank_samples.tolist())
488
+
489
+ def __len__(self):
490
+ return self.num_samples
491
+
492
+ def set_epoch(self, epoch):
493
+ self.epoch = int(epoch)
494
+
495
+
496
+ def _collect_class_to_indices(targets):
497
+ class_to_indices = {}
498
+ for idx, t in enumerate(targets):
499
+ cls = int(t)
500
+ class_to_indices.setdefault(cls, []).append(idx)
501
+ return class_to_indices
502
+
503
+
504
+ def get_bal_sampler(dataset, *, distributed=False, num_replicas=1, rank=0, seed=0, strategy="auto"):
505
+ targets = _collect_targets(dataset)
506
+ if len(targets) == 0:
507
+ raise ValueError('Cannot build balanced sampler: empty targets')
508
+
509
+ strategy = str(strategy or "auto").strip().lower()
510
+ class_to_indices = _collect_class_to_indices(targets)
511
+
512
+ if strategy == "auto":
513
+ # For binary deepfake labels (0=real, 1=fake), enforce strict near-1:1
514
+ # class balance per epoch by default.
515
+ if len(class_to_indices) == 2 and set(class_to_indices.keys()) == {0, 1}:
516
+ strategy = "uniform"
517
+ else:
518
+ strategy = "weighted"
519
+
520
+ if strategy in {"uniform", "strict", "strict_binary", "exact"}:
521
+ if distributed:
522
+ num_samples = int(math.ceil(len(targets) / float(max(1, num_replicas))))
523
+ return DistributedClassUniformSampler(
524
+ class_to_indices=class_to_indices,
525
+ num_samples=num_samples,
526
+ num_replicas=max(1, num_replicas),
527
+ rank=rank,
528
+ seed=seed,
529
+ )
530
+ return ClassUniformSampler(
531
+ class_to_indices=class_to_indices,
532
+ num_samples=len(targets),
533
+ seed=seed,
534
+ )
535
+
536
+ ratio = np.bincount(targets)
537
+ w = 1. / torch.tensor(ratio, dtype=torch.float)
538
+ sample_weights = w[targets]
539
+ if distributed:
540
+ num_samples = int(math.ceil(len(sample_weights) / float(max(1, num_replicas))))
541
+ return DistributedWeightedSampler(
542
+ sample_weights=sample_weights,
543
+ num_samples=num_samples,
544
+ num_replicas=max(1, num_replicas),
545
+ rank=rank,
546
+ seed=seed,
547
+ )
548
+ return WeightedRandomSampler(
549
+ weights=sample_weights,
550
+ num_samples=len(sample_weights),
551
+ replacement=True,
552
+ )
553
+
554
+
555
+ def create_dataloader(opt):
556
+ shuffle = not opt.serial_batches if (opt.isTrain and not opt.class_bal) else False
557
+ dataset = get_dataset(opt)
558
+ distributed = bool(getattr(opt, 'distributed', False))
559
+ if opt.class_bal:
560
+ strategy = str(getattr(opt, 'class_bal_strategy', 'auto') or 'auto')
561
+ if bool(getattr(opt, 'class_bal_strict', False)) and strategy.lower() in {'weighted', 'auto'}:
562
+ strategy = 'uniform'
563
+ sampler = get_bal_sampler(
564
+ dataset,
565
+ distributed=distributed,
566
+ num_replicas=int(getattr(opt, 'world_size', 1)),
567
+ rank=int(getattr(opt, 'rank', 0)),
568
+ seed=int(getattr(opt, 'seed', 0)),
569
+ strategy=strategy,
570
+ )
571
+ shuffle = False
572
+ else:
573
+ sampler = None
574
+
575
+ data_loader = torch.utils.data.DataLoader(dataset,
576
+ batch_size=opt.batch_size,
577
+ shuffle=shuffle,
578
+ sampler=sampler,
579
+ num_workers=int(opt.num_threads))
580
+ return data_loader
detectors/ForensicConcept/upstream/data/datasets.py ADDED
@@ -0,0 +1,967 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import inspect
4
+ import re
5
+ import os
6
+
7
+ os.environ.setdefault("NO_ALBUMENTATIONS_UPDATE", "1")
8
+
9
+ import albumentations as A
10
+ from albumentations import Downscale, Compose, ImageCompression, GaussNoise, MotionBlur, GaussianBlur
11
+ from torchvision import transforms, datasets
12
+ import torchvision.transforms.functional as TF
13
+ from random import random, choice
14
+ from io import BytesIO
15
+ from PIL import Image
16
+ from PIL import ImageFile
17
+ from PIL import ImageFilter
18
+ from PIL import ImageOps
19
+ from PIL import UnidentifiedImageError
20
+ from scipy.ndimage import gaussian_filter
21
+ from torchvision.transforms import InterpolationMode
22
+ import torch
23
+
24
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
25
+
26
+
27
+ CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073]
28
+ CLIP_STD = [0.26862954, 0.26130258, 0.27577711]
29
+ IMAGENET_MEAN = [0.485, 0.456, 0.406]
30
+ IMAGENET_STD = [0.229, 0.224, 0.225]
31
+
32
+
33
+ def _supports_albu_arg(cls, arg_name):
34
+ try:
35
+ return arg_name in inspect.signature(cls.__init__).parameters
36
+ except Exception:
37
+ return False
38
+
39
+
40
+ def _build_downscale_aug():
41
+ """Build Downscale across the Albumentations 1.x and 2.x APIs."""
42
+ if _supports_albu_arg(Downscale, "scale_range"):
43
+ return Downscale(
44
+ scale_range=(0.25, 0.75),
45
+ interpolation_pair={
46
+ "downscale": cv2.INTER_LINEAR,
47
+ "upscale": cv2.INTER_LINEAR,
48
+ },
49
+ p=0.5,
50
+ )
51
+ return Downscale(
52
+ scale_min=0.25,
53
+ scale_max=0.75,
54
+ interpolation=cv2.INTER_LINEAR,
55
+ p=0.5,
56
+ )
57
+
58
+
59
+ def _build_testshift_like_aug(p_apply=1.0, max_groups=3):
60
+ # group 1) blur
61
+ blur_group = A.OneOf([
62
+ A.GaussianBlur(sigma_limit=(0.1, 5.0), p=1.0),
63
+ A.Defocus(radius=(1, 8), alias_blur=(0.1, 0.5), p=1.0),
64
+ ], p=1.0)
65
+
66
+ # group 2) color distortion
67
+ color_group = A.OneOf([
68
+ A.ChromaticAberration(
69
+ primary_distortion_limit=(0.01, 0.08),
70
+ secondary_distortion_limit=(0.01, 0.12),
71
+ p=1.0,
72
+ ),
73
+ A.ColorJitter(brightness=0.0, contrast=0.0, saturation=1.0, hue=0.0, p=1.0),
74
+ ], p=1.0)
75
+
76
+ # group 3) jpeg
77
+ if _supports_albu_arg(A.ImageCompression, "quality_range"):
78
+ jpeg_group = A.ImageCompression(compression_type="jpeg", quality_range=(4, 43), p=1.0)
79
+ else:
80
+ jpeg_group = A.ImageCompression(quality_lower=4, quality_upper=43, p=1.0)
81
+
82
+ # group 4) noise
83
+ if _supports_albu_arg(A.GaussNoise, "std_range"):
84
+ gauss_noise = A.GaussNoise(std_range=(0.032, 0.100), mean_range=(0.0, 0.0), per_channel=True, p=1.0)
85
+ else:
86
+ gauss_noise = A.GaussNoise(var_limit=(0.032 ** 2, 0.100 ** 2), mean=0.0, per_channel=True, p=1.0)
87
+ if hasattr(A, "SaltAndPepper"):
88
+ impulse_noise = A.SaltAndPepper(amount=(0.001, 0.03), salt_vs_pepper=(0.45, 0.55), p=1.0)
89
+ else:
90
+ impulse_noise = A.ISONoise(color_shift=(0.01, 0.05), intensity=(0.1, 0.5), p=1.0)
91
+ noise_group = A.OneOf([
92
+ gauss_noise,
93
+ impulse_noise,
94
+ ], p=1.0)
95
+
96
+ # group 5) brightness
97
+ brightness_group = A.RandomBrightnessContrast(
98
+ brightness_limit=(-0.8, 0.8),
99
+ contrast_limit=(0.0, 0.0),
100
+ brightness_by_max=True,
101
+ p=1.0,
102
+ )
103
+
104
+ # group 6) spatial distortion
105
+ spatial_group = A.OneOf([
106
+ A.GridDistortion(
107
+ num_steps=5,
108
+ distort_limit=(0.05, 0.5),
109
+ interpolation=cv2.INTER_LINEAR,
110
+ border_mode=cv2.BORDER_REFLECT_101,
111
+ p=1.0,
112
+ ),
113
+ A.Sequential([
114
+ A.ToGray(num_output_channels=3, p=1.0),
115
+ A.Posterize(num_bits=(3, 5), p=1.0),
116
+ ], p=1.0),
117
+ ], p=1.0)
118
+
119
+ # group 7) sharpness / contrast
120
+ sharp_contrast_group = A.RandomToneCurve(scale=0.2, p=1.0)
121
+
122
+ groups = [
123
+ blur_group,
124
+ color_group,
125
+ jpeg_group,
126
+ noise_group,
127
+ brightness_group,
128
+ spatial_group,
129
+ sharp_contrast_group,
130
+ ]
131
+
132
+ max_groups = max(1, min(int(max_groups), len(groups)))
133
+ choices = [A.SomeOf(groups, n=n, replace=False, p=1.0) for n in range(1, max_groups + 1)]
134
+
135
+ return A.Compose([
136
+ A.OneOf(choices, p=1.0),
137
+ ], p=float(p_apply))
138
+
139
+ def dataset_folder(opt, root):
140
+ if opt.mode == 'binary':
141
+ return binary_dataset(opt, root)
142
+ if opt.mode == 'filename':
143
+ return FileNameDataset(opt, root)
144
+ raise ValueError('opt.mode needs to be binary or filename.')
145
+
146
+
147
+ def _apply_single_robustness(img, robustness_type, params=None):
148
+ params = dict(params or {})
149
+ robustness_type = str(robustness_type or "").strip().lower()
150
+ if not robustness_type:
151
+ return img
152
+
153
+ if robustness_type == "jpeg":
154
+ quality = int(params.get("jpeg_quality", 75) or 75)
155
+ out = BytesIO()
156
+ img.save(out, format="JPEG", quality=quality)
157
+ out.seek(0)
158
+ with Image.open(out) as aug_img:
159
+ return aug_img.convert("RGB")
160
+
161
+ if robustness_type == "gaussian_blur":
162
+ sigma = float(params.get("gaussian_blur_sigma", 1.0) or 1.0)
163
+ return img.filter(ImageFilter.GaussianBlur(radius=sigma))
164
+
165
+ if robustness_type == "gaussian_noise":
166
+ std = float(params.get("gaussian_noise_std", 0.1) or 0.1)
167
+ img_np = np.asarray(img).astype(np.float32) / 255.0
168
+ noise = np.random.normal(loc=0.0, scale=std, size=img_np.shape).astype(np.float32)
169
+ img_np = np.clip(img_np + noise, 0.0, 1.0)
170
+ img_np = (img_np * 255.0).round().astype(np.uint8)
171
+ return Image.fromarray(img_np)
172
+
173
+ if robustness_type == "downsample":
174
+ scale = float(params.get("downsample_scale", 0.5) or 0.5)
175
+ width, height = img.size
176
+ down_w = max(1, int(round(width * scale)))
177
+ down_h = max(1, int(round(height * scale)))
178
+ down = img.resize((down_w, down_h), resample=Image.BILINEAR)
179
+ return down.resize((width, height), resample=Image.BILINEAR)
180
+
181
+ if robustness_type == "color_jitter":
182
+ brightness = float(params.get("cj_brightness", 0.0) or 0.0)
183
+ contrast = float(params.get("cj_contrast", 0.0) or 0.0)
184
+ saturation = float(params.get("cj_saturation", 0.0) or 0.0)
185
+ hue = float(params.get("cj_hue", 0.0) or 0.0)
186
+
187
+ out = img
188
+ if brightness != 0.0:
189
+ out = TF.adjust_brightness(out, 1.0 + brightness)
190
+ if contrast != 0.0:
191
+ out = TF.adjust_contrast(out, 1.0 + contrast)
192
+ if saturation != 0.0:
193
+ out = TF.adjust_saturation(out, 1.0 + saturation)
194
+ if hue != 0.0:
195
+ hue = max(-0.5, min(0.5, hue))
196
+ out = TF.adjust_hue(out, hue)
197
+ return out
198
+
199
+ raise ValueError(f"Unsupported robustness_type: {robustness_type}")
200
+
201
+
202
+ def _apply_explicit_robustness(img, opt):
203
+ robustness_chain = getattr(opt, "robustness_chain", None) or []
204
+ if robustness_chain:
205
+ out = img
206
+ for idx, entry in enumerate(robustness_chain):
207
+ if not isinstance(entry, dict):
208
+ raise ValueError(f"robustness_chain[{idx}] must be a dict, got {type(entry).__name__}")
209
+ out = _apply_single_robustness(
210
+ out,
211
+ entry.get("type", ""),
212
+ entry.get("params", {}),
213
+ )
214
+ return out
215
+
216
+ return _apply_single_robustness(
217
+ img,
218
+ getattr(opt, "robustness_type", ""),
219
+ {
220
+ "jpeg_quality": getattr(opt, "robustness_jpeg_quality", 75),
221
+ "gaussian_blur_sigma": getattr(opt, "robustness_gaussian_blur_sigma", 1.0),
222
+ "gaussian_noise_std": getattr(opt, "robustness_gaussian_noise_std", 0.1),
223
+ "downsample_scale": getattr(opt, "robustness_downsample_scale", 0.5),
224
+ "cj_brightness": getattr(opt, "robustness_cj_brightness", 0.0),
225
+ "cj_contrast": getattr(opt, "robustness_cj_contrast", 0.0),
226
+ "cj_saturation": getattr(opt, "robustness_cj_saturation", 0.0),
227
+ "cj_hue": getattr(opt, "robustness_cj_hue", 0.0),
228
+ },
229
+ )
230
+
231
+
232
+ import base64
233
+ from io import BytesIO
234
+ from PIL import Image
235
+ import numpy as np
236
+ import torchvision.transforms
237
+ from scipy.ndimage import gaussian_filter
238
+
239
+
240
+ class ImageProcessor:
241
+ def __init__(self, opt):
242
+ self.opt = opt
243
+
244
+ def data_augment(self, img):
245
+ noise_type = getattr(self.opt, "noise_type", None)
246
+ noise_ratio = getattr(self.opt, "noise_ratio", None)
247
+
248
+ if noise_type == 'jpg':
249
+ img_processed = self.pil_jpg_new(img, noise_ratio)
250
+ elif noise_type == 'resize':
251
+ width, height = img.size
252
+ img_processed = torchvision.transforms.Resize((int(height / noise_ratio), int(width / noise_ratio)))(img)
253
+ elif noise_type == 'blur':
254
+ img = np.array(img)
255
+ self.gaussian_blur(img, noise_ratio)
256
+ img_processed = Image.fromarray(img)
257
+ elif noise_type is None:
258
+ img_processed = img
259
+
260
+ return img_processed
261
+
262
+ def pil_jpg_new(self, img, compress_val):
263
+ out = BytesIO()
264
+ img.save(out, format='jpeg', quality=compress_val)
265
+ img = Image.open(out)
266
+ # load from memory before ByteIO closes
267
+ img = np.array(img)
268
+ img = Image.fromarray(img)
269
+ out.close()
270
+ return img
271
+
272
+ def gaussian_blur(self, img, sigma):
273
+ # Check if the image has a third dimension
274
+ if img.ndim == 3:
275
+ # Check the number of channels in the image
276
+ channels = img.shape[2]
277
+ # if channels == 0:
278
+ # # If there are no channels, return the image as is
279
+ # return img
280
+ if channels == 1:
281
+ # If there is one channel, apply the filter to the single channel
282
+ gaussian_filter(img[:, :, 0], output=img[:, :, 0], sigma=sigma)
283
+ elif channels == 2:
284
+ # If there are two channels, apply the filter to both channels
285
+ gaussian_filter(img[:, :, 0], output=img[:, :, 0], sigma=sigma)
286
+ gaussian_filter(img[:, :, 1], output=img[:, :, 1], sigma=sigma)
287
+ elif channels == 3:
288
+ # If there are three channels, apply the filter to all three channels
289
+ gaussian_filter(img[:, :, 0], output=img[:, :, 0], sigma=sigma)
290
+ gaussian_filter(img[:, :, 1], output=img[:, :, 1], sigma=sigma)
291
+ gaussian_filter(img[:, :, 2], output=img[:, :, 2], sigma=sigma)
292
+ else:
293
+ # If the image does not have a third dimension, apply the filter to the 2D image
294
+ gaussian_filter(img, output=img, sigma=sigma)
295
+
296
+ # return img
297
+
298
+
299
+ def encode_image(image_path, processor=None):
300
+ with open(image_path, "rb") as image_file:
301
+ img = Image.open(image_file)
302
+
303
+ # Apply data augmentation if processor is provided
304
+ if processor is not None:
305
+ # print(processor.opt)
306
+ img = processor.data_augment(img)
307
+
308
+ # Convert image to Base64
309
+ buffered = BytesIO()
310
+ img.save(buffered, format="PNG")
311
+ img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
312
+
313
+ return img, img_base64
314
+
315
+ class Options:
316
+ def __init__(self, noise_type=None, noise_ratio=None):
317
+ """
318
+ 初始化数据增强的配置参数。
319
+
320
+ :param noise_type: 噪声类型,可选值为 'jpg', 'resize', 'blur' 或 None
321
+ :param noise_ratio: 噪声强度或比例,具体含义取决于 noise_type
322
+ """
323
+ self.noise_type = noise_type
324
+ self.noise_ratio = noise_ratio
325
+ def __str__(self):
326
+ """返回对象的字符串表示,便于调试"""
327
+ return (f"Options(noise_type={self.noise_type}, noise_ratio={self.noise_ratio}")
328
+
329
+
330
+ # Robust ImageFolder: skip unreadable/corrupted files instead of crashing workers.
331
+ class SafeImageFolder(datasets.ImageFolder):
332
+ def __init__(self, *args, skip_broken=True, skip_log_limit=0, **kwargs):
333
+ super().__init__(*args, **kwargs)
334
+ self.skip_broken = bool(skip_broken)
335
+ self.skip_log_limit = max(0, int(skip_log_limit))
336
+ self._skip_log_count = 0
337
+
338
+ @staticmethod
339
+ def _is_image_decode_error(exc):
340
+ return isinstance(exc, (UnidentifiedImageError, OSError, ValueError))
341
+
342
+ def __getitem__(self, index):
343
+ if not self.skip_broken:
344
+ return super().__getitem__(index)
345
+
346
+ total = len(self.samples)
347
+ if total == 0:
348
+ raise IndexError("SafeImageFolder is empty")
349
+
350
+ idx = int(index) % total
351
+ for _ in range(total):
352
+ try:
353
+ return super().__getitem__(idx)
354
+ except Exception as exc:
355
+ if not self._is_image_decode_error(exc):
356
+ raise
357
+
358
+ bad_path = self.samples[idx][0]
359
+ if self._skip_log_count < self.skip_log_limit:
360
+ print(
361
+ f"[Data] Skipping unreadable image: {bad_path} "
362
+ f"({type(exc).__name__}: {exc})"
363
+ )
364
+ self._skip_log_count += 1
365
+ idx = (idx + 1) % total
366
+
367
+ raise RuntimeError(
368
+ "Unable to fetch a readable image from dataset. "
369
+ "All candidates appear unreadable."
370
+ )
371
+
372
+
373
+ class FlatLabeledImageDataset(torch.utils.data.Dataset):
374
+ """Fallback dataset for flat folders: labels parsed from filename suffix (_real/_fake)."""
375
+
376
+ def __init__(self, samples, transform=None, skip_broken=True, skip_log_limit=0):
377
+ self.samples = list(samples)
378
+ self.transform = transform
379
+ self.skip_broken = bool(skip_broken)
380
+ self.skip_log_limit = max(0, int(skip_log_limit))
381
+ self._skip_log_count = 0
382
+ self.targets = [int(t) for _, t in self.samples]
383
+ self.class_to_idx = {'0_real': 0, '1_fake': 1}
384
+ self.classes = ['0_real', '1_fake']
385
+ self.imgs = self.samples
386
+
387
+ @staticmethod
388
+ def _is_image_decode_error(exc):
389
+ return isinstance(exc, (UnidentifiedImageError, OSError, ValueError))
390
+
391
+ def __len__(self):
392
+ return len(self.samples)
393
+
394
+ def __getitem__(self, index):
395
+ total = len(self.samples)
396
+ if total == 0:
397
+ raise IndexError("FlatLabeledImageDataset is empty")
398
+
399
+ idx = int(index) % total
400
+ for _ in range(total):
401
+ path, target = self.samples[idx]
402
+ try:
403
+ with Image.open(path) as img:
404
+ img = img.convert("RGB")
405
+ if self.transform is not None:
406
+ img = self.transform(img)
407
+ return img, int(target)
408
+ except Exception as exc:
409
+ if (not self.skip_broken) or (not self._is_image_decode_error(exc)):
410
+ raise
411
+ if self._skip_log_count < self.skip_log_limit:
412
+ print(
413
+ f"[Data] Skipping unreadable image: {path} "
414
+ f"({type(exc).__name__}: {exc})"
415
+ )
416
+ self._skip_log_count += 1
417
+ idx = (idx + 1) % total
418
+
419
+ raise RuntimeError("Unable to fetch a readable image from flat dataset.")
420
+
421
+
422
+ # Example usage:
423
+ # opt = SomeOptionsClass() # Replace with your actual options class
424
+ # print(opt_class)
425
+
426
+
427
+ def _find_binary_roots(root):
428
+ """Yield directories whose immediate children contain 0_real and 1_fake."""
429
+ binary_roots = []
430
+ valid_pairs = (
431
+ {'0_real', '1_fake'},
432
+ {'0_fake', '1_real'},
433
+ {'raw', 'synthesis'}, # deepfake datasets
434
+ {'real', 'fake'},
435
+ )
436
+ for current_root, dirs, _ in os.walk(root):
437
+ present = set(dirs)
438
+ if any(pair.issubset(present) for pair in valid_pairs):
439
+ binary_roots.append(current_root)
440
+ # ensure deterministic ordering so label mapping is stable
441
+ binary_roots.sort()
442
+ return binary_roots
443
+
444
+
445
+ def infer_single_label_from_root(root):
446
+ """Infer fixed binary label from directory name for one-class dataset roots."""
447
+ # Canonical deepfake aliases used by Celeb-DF/FF++ style trees.
448
+ alias_to_label = {
449
+ # real
450
+ "0_real": 0,
451
+ "1_real": 0,
452
+ "real": 0,
453
+ "raw": 0,
454
+ "original_sequences": 0,
455
+ "celeb-real-mtcnn": 0,
456
+ "youtube-real-mtcnn": 0,
457
+ # fake
458
+ "1_fake": 1,
459
+ "0_fake": 1,
460
+ "fake": 1,
461
+ "synthesis": 1,
462
+ "manipulated_sequences": 1,
463
+ "celeb-synthesis-mtcnn": 1,
464
+ }
465
+ base = os.path.basename(os.path.abspath(root)).strip().lower()
466
+ return alias_to_label.get(base)
467
+
468
+
469
+ def _collect_recursive_image_samples(root, label):
470
+ exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"}
471
+ samples = []
472
+ for current_root, _, files in os.walk(root):
473
+ for fname in files:
474
+ if os.path.splitext(fname)[1].lower() in exts:
475
+ samples.append((os.path.join(current_root, fname), int(label)))
476
+ samples.sort(key=lambda x: x[0])
477
+ return samples
478
+
479
+
480
+ def _resolve_dfdc_labels_path(root, opt):
481
+ root_abs = os.path.abspath(root)
482
+ explicit_candidates = [
483
+ getattr(opt, "dfdc_labels_npy", None),
484
+ getattr(opt, "data_dfdc_labels_npy", None),
485
+ ]
486
+ candidates = [c for c in explicit_candidates if c]
487
+ candidates.extend(
488
+ [
489
+ os.path.join(os.path.dirname(root_abs), "labels.npy"),
490
+ os.path.join(os.path.dirname(os.path.dirname(root_abs)), "labels.npy"),
491
+ os.path.join(root_abs, "labels.npy"),
492
+ ]
493
+ )
494
+ seen = set()
495
+ for candidate in candidates:
496
+ p = os.path.abspath(os.path.expanduser(str(candidate)))
497
+ if p in seen:
498
+ continue
499
+ seen.add(p)
500
+ if os.path.isfile(p):
501
+ return p
502
+ return None
503
+
504
+
505
+ def is_dfdc_train_faces_root(root, opt=None):
506
+ root_abs = os.path.abspath(root)
507
+ if os.path.basename(root_abs).strip().lower() != "train_faces":
508
+ return False
509
+ opt_obj = opt if opt is not None else object()
510
+ return _resolve_dfdc_labels_path(root_abs, opt_obj) is not None
511
+
512
+
513
+ def _build_dfdc_train_faces_dataset(opt, root, transform):
514
+ root_abs = os.path.abspath(root)
515
+ if not is_dfdc_train_faces_root(root_abs, opt):
516
+ return None
517
+
518
+ labels_path = _resolve_dfdc_labels_path(root_abs, opt)
519
+ if labels_path is None:
520
+ return None
521
+
522
+ try:
523
+ labels_raw = np.load(labels_path, allow_pickle=True).item()
524
+ except Exception as exc:
525
+ raise RuntimeError(f"Failed to load DFDC labels file: {labels_path} ({exc})") from exc
526
+
527
+ if not isinstance(labels_raw, dict):
528
+ raise RuntimeError(f"DFDC labels file is not a dict: {labels_path}")
529
+
530
+ video_to_label = {}
531
+ for k, v in labels_raw.items():
532
+ key = str(k)
533
+ if key.endswith(".mp4"):
534
+ key = key[:-4]
535
+ try:
536
+ iv = int(v)
537
+ except (TypeError, ValueError):
538
+ continue
539
+ if iv in (0, 1):
540
+ video_to_label[key] = iv
541
+
542
+ if not video_to_label:
543
+ raise RuntimeError(f"No valid binary labels parsed from: {labels_path}")
544
+
545
+ exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"}
546
+ samples = []
547
+ total_video_dirs = 0
548
+ missing_label_video_dirs = 0
549
+ missing_label_examples = []
550
+
551
+ for part_name in sorted(os.listdir(root_abs)):
552
+ part_dir = os.path.join(root_abs, part_name)
553
+ if not os.path.isdir(part_dir):
554
+ continue
555
+ for video_name in sorted(os.listdir(part_dir)):
556
+ video_dir = os.path.join(part_dir, video_name)
557
+ if not os.path.isdir(video_dir):
558
+ continue
559
+ total_video_dirs += 1
560
+ label = video_to_label.get(video_name)
561
+ if label is None:
562
+ missing_label_video_dirs += 1
563
+ if len(missing_label_examples) < 5:
564
+ missing_label_examples.append(video_dir)
565
+ continue
566
+ for fname in sorted(os.listdir(video_dir)):
567
+ if os.path.splitext(fname)[1].lower() in exts:
568
+ samples.append((os.path.join(video_dir, fname), int(label)))
569
+
570
+ if not samples:
571
+ raise RuntimeError(
572
+ f"Detected DFDC train_faces root but no labeled image files were collected under {root_abs}"
573
+ )
574
+
575
+ if missing_label_video_dirs > 0:
576
+ print(
577
+ f"[DFDC] Warning: {missing_label_video_dirs}/{total_video_dirs} video folders in {root_abs} "
578
+ f"missing labels from {labels_path}. Examples: {missing_label_examples}"
579
+ )
580
+
581
+ real_count = sum(1 for _, t in samples if int(t) == 0)
582
+ fake_count = len(samples) - real_count
583
+ print(
584
+ f"[DFDC] Loaded train_faces with labels from {labels_path}: "
585
+ f"samples={len(samples)} real={real_count} fake={fake_count}"
586
+ )
587
+
588
+ skip_broken_images = bool(getattr(opt, "skip_broken_images", True))
589
+ skip_log_limit = int(getattr(opt, "skip_broken_images_log_limit", 0))
590
+ return FlatLabeledImageDataset(
591
+ samples=samples,
592
+ transform=transform,
593
+ skip_broken=skip_broken_images,
594
+ skip_log_limit=skip_log_limit,
595
+ )
596
+
597
+
598
+ def _build_binary_datasets(opt, root, transform):
599
+ """Create ImageFolder datasets for every binary directory discovered under root."""
600
+ binary_roots = _find_binary_roots(root)
601
+ if not binary_roots:
602
+ dfdc_dataset = _build_dfdc_train_faces_dataset(opt, root, transform)
603
+ if dfdc_dataset is not None:
604
+ return dfdc_dataset
605
+
606
+ # Fallback: flat folder with filename labels like xxx_real.png / xxx_fake.png
607
+ exts = {'.jpg', '.jpeg', '.png', '.bmp', '.webp', '.tif', '.tiff'}
608
+ suffix_re = re.compile(r'(?:^|[_-])(real|fake)$', flags=re.IGNORECASE)
609
+ flat_samples = []
610
+ root_path = os.path.abspath(root)
611
+ for p in sorted(os.listdir(root_path)):
612
+ abs_p = os.path.join(root_path, p)
613
+ if not os.path.isfile(abs_p):
614
+ continue
615
+ ext = os.path.splitext(p)[1].lower()
616
+ if ext not in exts:
617
+ continue
618
+ stem = os.path.splitext(p)[0]
619
+ m = suffix_re.search(stem)
620
+ if not m:
621
+ continue
622
+ label = 0 if m.group(1).lower() == 'real' else 1
623
+ flat_samples.append((abs_p, label))
624
+
625
+ skip_broken_images = bool(getattr(opt, "skip_broken_images", True))
626
+ skip_log_limit = int(getattr(opt, "skip_broken_images_log_limit", 0))
627
+ if flat_samples:
628
+ return FlatLabeledImageDataset(
629
+ samples=flat_samples,
630
+ transform=transform,
631
+ skip_broken=skip_broken_images,
632
+ skip_log_limit=skip_log_limit,
633
+ )
634
+
635
+ forced_label = infer_single_label_from_root(root)
636
+ if forced_label is not None:
637
+ recursive_samples = _collect_recursive_image_samples(root, forced_label)
638
+ if not recursive_samples:
639
+ raise RuntimeError(
640
+ f"Single-label root inferred for {root}, but no image files were found recursively."
641
+ )
642
+ return FlatLabeledImageDataset(
643
+ samples=recursive_samples,
644
+ transform=transform,
645
+ skip_broken=skip_broken_images,
646
+ skip_log_limit=skip_log_limit,
647
+ )
648
+
649
+ raise RuntimeError(
650
+ f"Could not locate binary folders (0_real/1_fake, raw/synthesis, real/fake), "
651
+ f"flat *_real/*_fake files, or a known single-label root alias under {root}"
652
+ )
653
+
654
+ datasets_list = []
655
+ skip_broken_images = bool(getattr(opt, "skip_broken_images", True))
656
+ skip_log_limit = int(getattr(opt, "skip_broken_images_log_limit", 0))
657
+ for binary_root in binary_roots:
658
+ dset = SafeImageFolder(
659
+ binary_root,
660
+ transform=transform,
661
+ skip_broken=skip_broken_images,
662
+ skip_log_limit=skip_log_limit,
663
+ )
664
+ idx_to_class = {idx: cls_name for cls_name, idx in dset.class_to_idx.items()}
665
+ class_names = set(idx_to_class.values())
666
+
667
+ if class_names == {'0_real', '1_fake'}:
668
+ desired_order = {'0_real': 0, '1_fake': 1}
669
+ elif class_names == {'0_fake', '1_real'}:
670
+ # reverse-labelled datasets: map back to canonical ordering
671
+ desired_order = {'1_real': 0, '0_fake': 1}
672
+ elif class_names == {'raw', 'synthesis'}:
673
+ desired_order = {'raw': 0, 'synthesis': 1}
674
+ elif class_names == {'real', 'fake'}:
675
+ desired_order = {'real': 0, 'fake': 1}
676
+ else:
677
+ raise RuntimeError(
678
+ f"Unsupported class names {class_names} under {binary_root}; "
679
+ "expected 0_real/1_fake, 0_fake/1_real, raw/synthesis, or real/fake"
680
+ )
681
+
682
+ remapped = []
683
+ for path, target in dset.samples:
684
+ cls_name = idx_to_class[target]
685
+ if cls_name not in desired_order:
686
+ raise RuntimeError(
687
+ f"Encountered unexpected class '{cls_name}' in {binary_root}; expected one of {list(desired_order.keys())}"
688
+ )
689
+ remapped.append((path, desired_order[cls_name]))
690
+
691
+ if remapped != dset.samples:
692
+ dset.samples = remapped
693
+ dset.imgs = remapped
694
+ dset.targets = [t for _, t in remapped]
695
+
696
+ # Normalise metadata to canonical labels for downstream consumers
697
+ dset.class_to_idx = {'0_real': 0, '1_fake': 1}
698
+ dset.classes = ['0_real', '1_fake']
699
+ datasets_list.append(dset)
700
+
701
+ if len(datasets_list) == 1:
702
+ return datasets_list[0]
703
+ return torch.utils.data.ConcatDataset(datasets_list)
704
+
705
+
706
+ def _pad_to_min_size(img, target_h, target_w):
707
+ """Pad image with zeros so that height/width are at least target sizes."""
708
+ width, height = img.size
709
+ pad_w = max(target_w - width, 0)
710
+ pad_h = max(target_h - height, 0)
711
+ if pad_w == 0 and pad_h == 0:
712
+ return img
713
+
714
+ left = pad_w // 2
715
+ right = pad_w - left
716
+ top = pad_h // 2
717
+ bottom = pad_h - top
718
+ return ImageOps.expand(img, border=(left, top, right, bottom), fill=0)
719
+
720
+
721
+ def binary_dataset(opt, root):
722
+ # Allow switching to a simplified (legacy) preprocessing pipeline to match the NPR script.
723
+ legacy_preprocess = getattr(opt, "legacy_preprocess", False)
724
+
725
+ if opt.isTrain:
726
+ crop_func = transforms.RandomCrop(opt.cropSize)
727
+ elif opt.no_crop:
728
+ crop_func = transforms.Lambda(lambda img: img)
729
+ else:
730
+ crop_func = transforms.CenterCrop(opt.cropSize)
731
+
732
+ if opt.isTrain and not opt.no_flip:
733
+ flip_func = transforms.RandomHorizontalFlip()
734
+ else:
735
+ flip_func = transforms.Lambda(lambda img: img)
736
+ if opt.no_resize:
737
+ rz_func = transforms.Lambda(lambda img: img)
738
+ else:
739
+ # rz_func = transforms.Lambda(lambda img: custom_resize(img, opt))
740
+ rz_func = transforms.Resize((opt.loadSize, opt.loadSize))
741
+ # rz_func = transforms.Resize(opt.loadSize)
742
+ if legacy_preprocess:
743
+ # Match the older flow: resize -> basic augment -> crop -> flip -> IMAGENET normalize.
744
+ normalize_transform = transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
745
+ # normalize_transform = transforms.Normalize(mean=CLIP_MEAN, std=CLIP_STD)
746
+ transform = transforms.Compose([
747
+ transforms.Lambda(lambda img: _apply_explicit_robustness(img, opt)),
748
+ rz_func,
749
+ transforms.Lambda(lambda img: data_augment(img, opt)),
750
+ crop_func,
751
+ flip_func,
752
+ transforms.ToTensor(),
753
+ normalize_transform,
754
+ ])
755
+ return _build_binary_datasets(opt, root, transform)
756
+
757
+ NOISE_TYPE = getattr(opt, "noise_type", None)
758
+ NOISE_RATIO = getattr(opt, "noise_ratio", None)
759
+
760
+ opt_class = Options(noise_type=NOISE_TYPE, noise_ratio=NOISE_RATIO)
761
+ processor = ImageProcessor(opt_class)
762
+
763
+ # 定义Albumentations增强(兼容不同版本的 ImageCompression 参数)
764
+ def _build_image_compression():
765
+ try:
766
+ return ImageCompression(quality_range=(60, 100), p=0.5)
767
+ except TypeError:
768
+ return ImageCompression(quality_lower=60, quality_upper=100, p=0.5)
769
+
770
+ aug = Compose([
771
+ _build_image_compression(),
772
+ GaussNoise(p=0.2),
773
+ MotionBlur(p=0.2),
774
+ GaussianBlur(blur_limit=3, p=0.5),
775
+ _build_downscale_aug(),
776
+ ])
777
+
778
+ # 自定义转换函数:将PIL图像转换为NumPy数组,应用Albumentations增强,再转回PIL
779
+ def albumentations_aug(img):
780
+ # 将PIL图像转换为NumPy数组 (H, W, C) RGB格式
781
+ img_np = np.array(img)
782
+ # 应用Albumentations增强
783
+ augmented = aug(image=img_np)
784
+ # 从字典中提取增强后的图像
785
+ img_aug = augmented['image']
786
+ # 将NumPy数组转回PIL图像
787
+ return Image.fromarray(img_aug)
788
+
789
+ DATA_AUG = getattr(opt, "data_aug", False)
790
+ USE_TESTSHIFT_LIKE_AUG_TRAIN = bool(getattr(opt, "use_testshift_like_aug", False)) and bool(opt.isTrain)
791
+ USE_TESTSHIFT_LIKE_AUG_EVAL = bool(getattr(opt, "use_testshift_like_aug_eval", False)) and (not bool(opt.isTrain))
792
+ USE_TESTSHIFT_LIKE_AUG = USE_TESTSHIFT_LIKE_AUG_TRAIN or USE_TESTSHIFT_LIKE_AUG_EVAL
793
+ TESTSHIFT_LIKE_APPLY_PROB = float(getattr(opt, "testshift_like_apply_prob", 1.0))
794
+ TESTSHIFT_LIKE_MAX_GROUPS = int(getattr(opt, "testshift_like_max_groups", 3))
795
+ USE_AUG_UTILS_EVAL = bool(getattr(opt, "use_aug_utils_eval", False)) and (not bool(opt.isTrain))
796
+ USE_AUG_UTILS_TRAIN = bool(getattr(opt, "use_aug_utils_train", False)) and (
797
+ bool(opt.isTrain) or USE_AUG_UTILS_EVAL
798
+ )
799
+ AUG_UTILS_PROB = float(getattr(opt, "aug_utils_prob", 1.0))
800
+ AUG_UTILS_MAX_DISTORTIONS = int(getattr(opt, "aug_utils_max_distortions", 3))
801
+ AUG_UTILS_NUM_LEVELS = int(getattr(opt, "aug_utils_num_levels", 5))
802
+ # 创建数据增强变换(deepfake专用 TestShift-like 与原有增强互斥,避免叠加偏移)
803
+ if USE_TESTSHIFT_LIKE_AUG:
804
+ testshift_aug = _build_testshift_like_aug(
805
+ p_apply=TESTSHIFT_LIKE_APPLY_PROB,
806
+ max_groups=TESTSHIFT_LIKE_MAX_GROUPS,
807
+ )
808
+
809
+ def _testshift_like_aug(img):
810
+ img_np = np.array(img)
811
+ out = testshift_aug(image=img_np)["image"]
812
+ return Image.fromarray(out)
813
+
814
+ data_aug = transforms.Lambda(_testshift_like_aug)
815
+ print(
816
+ f"[Aug] Using testshift-like aug (prob={TESTSHIFT_LIKE_APPLY_PROB}, "
817
+ f"max_groups={TESTSHIFT_LIKE_MAX_GROUPS})"
818
+ )
819
+ elif DATA_AUG:
820
+ data_aug = transforms.Lambda(albumentations_aug)
821
+ else:
822
+ data_aug = transforms.Lambda(lambda img: img)
823
+
824
+ if isinstance(opt.cropSize, (tuple, list)):
825
+ target_h = opt.cropSize[0]
826
+ target_w = opt.cropSize[1] if len(opt.cropSize) > 1 else opt.cropSize[0]
827
+ else:
828
+ target_h = target_w = opt.cropSize
829
+
830
+ apply_padding = opt.no_resize and (opt.isTrain or not opt.no_crop)
831
+ pad_func = transforms.Lambda(lambda img: _pad_to_min_size(img, target_h, target_w)) if apply_padding else transforms.Lambda(lambda img: img)
832
+
833
+ trainmode = str(getattr(opt, 'trainmode', '')).lower()
834
+ modelname = str(getattr(opt, 'modelname', ''))
835
+ if trainmode == 'lora' and modelname.startswith('CLIP:'):
836
+ normalize_transform = transforms.Normalize(mean=CLIP_MEAN, std=CLIP_STD)
837
+ else:
838
+ normalize_transform = transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
839
+
840
+ # Optional: apply augmentations from aug_utils_train on tensor in [0, 1].
841
+ aug_utils_transform = transforms.Lambda(lambda tens: tens)
842
+ if USE_AUG_UTILS_TRAIN:
843
+ try:
844
+ from aug_utils_train.utils_data import distort_images as aug_utils_distort_images
845
+
846
+ def _apply_aug_utils_train(tens):
847
+ if random() > AUG_UTILS_PROB:
848
+ return tens
849
+ distorted, _, _ = aug_utils_distort_images(
850
+ tens,
851
+ max_distortions=AUG_UTILS_MAX_DISTORTIONS,
852
+ num_levels=AUG_UTILS_NUM_LEVELS,
853
+ )
854
+ return distorted
855
+
856
+ aug_utils_transform = transforms.Lambda(_apply_aug_utils_train)
857
+ stage = "train" if bool(opt.isTrain) else "eval"
858
+ print(
859
+ f"[Aug] Using aug_utils_train@{stage} (prob={AUG_UTILS_PROB}, "
860
+ f"max_distortions={AUG_UTILS_MAX_DISTORTIONS}, num_levels={AUG_UTILS_NUM_LEVELS})"
861
+ )
862
+ except Exception as exc:
863
+ print(f"[Aug] Failed to enable aug_utils_train, fallback to default aug only: {exc}")
864
+
865
+ transform = transforms.Compose([
866
+ transforms.Lambda(lambda img: processor.data_augment(img)),
867
+ transforms.Lambda(lambda img: _apply_explicit_robustness(img, opt)),
868
+ # 使用自定义函数替换原processor.data_augment
869
+ data_aug,
870
+ rz_func, # 后续PyTorch变换 (如调整大小)
871
+ pad_func, # 当禁用resize且图像不足裁剪尺寸时补零
872
+ crop_func, # 裁剪
873
+ flip_func, # 翻转
874
+ transforms.ToTensor(),
875
+ aug_utils_transform,
876
+ normalize_transform,
877
+ ])
878
+
879
+ return _build_binary_datasets(opt, root, transform)
880
+
881
+
882
+ class FileNameDataset(datasets.ImageFolder):
883
+ def name(self):
884
+ return 'FileNameDataset'
885
+
886
+ def __init__(self, opt, root):
887
+ self.opt = opt
888
+ super().__init__(root)
889
+
890
+ def __getitem__(self, index):
891
+ # Loading sample
892
+ path, target = self.samples[index]
893
+ return path
894
+
895
+
896
+ def data_augment(img, opt):
897
+ img = np.array(img)
898
+
899
+ if random() < opt.blur_prob:
900
+ sig = sample_continuous(opt.blur_sig)
901
+ gaussian_blur(img, sig)
902
+
903
+ if random() < opt.jpg_prob:
904
+ method = sample_discrete(opt.jpg_method)
905
+ qual = sample_discrete(opt.jpg_qual)
906
+ img = jpeg_from_key(img, qual, method)
907
+
908
+ return Image.fromarray(img)
909
+
910
+
911
+ def sample_continuous(s):
912
+ if len(s) == 1:
913
+ return s[0]
914
+ if len(s) == 2:
915
+ rg = s[1] - s[0]
916
+ return random() * rg + s[0]
917
+ raise ValueError("Length of iterable s should be 1 or 2.")
918
+
919
+
920
+ def sample_discrete(s):
921
+ if len(s) == 1:
922
+ return s[0]
923
+ return choice(s)
924
+
925
+
926
+ def gaussian_blur(img, sigma):
927
+ gaussian_filter(img[:,:,0], output=img[:,:,0], sigma=sigma)
928
+ gaussian_filter(img[:,:,1], output=img[:,:,1], sigma=sigma)
929
+ gaussian_filter(img[:,:,2], output=img[:,:,2], sigma=sigma)
930
+
931
+
932
+ def cv2_jpg(img, compress_val):
933
+ img_cv2 = img[:,:,::-1]
934
+ encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), compress_val]
935
+ result, encimg = cv2.imencode('.jpg', img_cv2, encode_param)
936
+ decimg = cv2.imdecode(encimg, 1)
937
+ return decimg[:,:,::-1]
938
+
939
+
940
+ def pil_jpg(img, compress_val):
941
+ out = BytesIO()
942
+ img = Image.fromarray(img)
943
+ img.save(out, format='jpeg', quality=compress_val)
944
+ img = Image.open(out)
945
+ # load from memory before ByteIO closes
946
+ img = np.array(img)
947
+ out.close()
948
+ return img
949
+
950
+
951
+ jpeg_dict = {'cv2': cv2_jpg, 'pil': pil_jpg}
952
+ def jpeg_from_key(img, compress_val, key):
953
+ method = jpeg_dict[key]
954
+ return method(img, compress_val)
955
+
956
+
957
+ # rz_dict = {'bilinear': Image.BILINEAR,
958
+ # 'bicubic': Image.BICUBIC,
959
+ # 'lanczos': Image.LANCZOS,
960
+ # 'nearest': Image.NEAREST}
961
+ rz_dict = {'bilinear': InterpolationMode.BILINEAR,
962
+ 'bicubic': InterpolationMode.BICUBIC,
963
+ 'lanczos': InterpolationMode.LANCZOS,
964
+ 'nearest': InterpolationMode.NEAREST}
965
+ def custom_resize(img, opt):
966
+ interp = sample_discrete(opt.rz_interp)
967
+ return TF.resize(img, (opt.loadSize,opt.loadSize), interpolation=rz_dict[interp])
detectors/ForensicConcept/upstream/models/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .clip_models import CLIPModel
2
+
3
+
4
+ VALID_NAMES = [
5
+ "CLIP:ViT-L/14",
6
+ ]
7
+
8
+
9
+
10
+
11
+
12
+ def get_model(name, opt=None):
13
+ if name not in VALID_NAMES:
14
+ # Allow custom CLIP identifiers when explicit checkpoint path is provided.
15
+ custom_clip_ok = (
16
+ name.startswith("CLIP:")
17
+ and opt is not None
18
+ and bool(getattr(opt, "clip_model_path", None))
19
+ )
20
+ assert custom_clip_ok, f"Unsupported model name: {name}"
21
+ if name.startswith("CLIP:"):
22
+ return CLIPModel(name[5:], 1, opt)
23
+ raise ValueError(f"Unsupported model name: {name}")
detectors/ForensicConcept/upstream/models/clip/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .clip import *
2
+ from .model import set_lora_config
detectors/ForensicConcept/upstream/models/clip/bpe_simple_vocab_16e6.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
3
+ size 1356917
detectors/ForensicConcept/upstream/models/clip/clip.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import urllib
4
+ import warnings
5
+ from typing import Any, Union, List
6
+ from packaging import version
7
+
8
+ import torch
9
+ from PIL import Image
10
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
11
+ from tqdm import tqdm
12
+
13
+ from .model import build_model, build_pe_model
14
+ from .simple_tokenizer import SimpleTokenizer as _Tokenizer
15
+
16
+ try:
17
+ from torchvision.transforms import InterpolationMode
18
+ BICUBIC = InterpolationMode.BICUBIC
19
+ except ImportError:
20
+ BICUBIC = Image.BICUBIC
21
+
22
+
23
+ if version.parse(torch.__version__) < version.parse("1.7.1"):
24
+ warnings.warn("PyTorch version 1.7.1 or higher is recommended")
25
+
26
+
27
+ __all__ = ["available_models", "load", "tokenize"]
28
+ _tokenizer = _Tokenizer()
29
+
30
+ _MODELS = {
31
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
32
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
33
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
34
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
35
+ "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
36
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
37
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
38
+ "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
39
+ "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
40
+ }
41
+
42
+
43
+ def _download(url: str, root: str):
44
+ os.makedirs(root, exist_ok=True)
45
+ filename = os.path.basename(url)
46
+
47
+ expected_sha256 = url.split("/")[-2]
48
+ download_target = os.path.join(root, filename)
49
+
50
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
51
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
52
+
53
+ if os.path.isfile(download_target):
54
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
55
+ return download_target
56
+ else:
57
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
58
+
59
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
60
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
61
+ while True:
62
+ buffer = source.read(8192)
63
+ if not buffer:
64
+ break
65
+
66
+ output.write(buffer)
67
+ loop.update(len(buffer))
68
+
69
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
70
+ raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
71
+
72
+ return download_target
73
+
74
+
75
+ def _convert_image_to_rgb(image):
76
+ return image.convert("RGB")
77
+
78
+
79
+ def _transform(n_px):
80
+ return Compose([
81
+ Resize(n_px, interpolation=BICUBIC),
82
+ CenterCrop(n_px),
83
+ _convert_image_to_rgb,
84
+ ToTensor(),
85
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
86
+ ])
87
+
88
+
89
+ def available_models() -> List[str]:
90
+ """Returns the names of available CLIP models"""
91
+ return list(_MODELS.keys())
92
+
93
+
94
+ def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
95
+ """Load a CLIP model
96
+
97
+ Parameters
98
+ ----------
99
+ name : str
100
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
101
+
102
+ device : Union[str, torch.device]
103
+ The device to put the loaded model
104
+
105
+ jit : bool
106
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
107
+
108
+ download_root: str
109
+ path to download the model files; by default, it uses "./.cache/clip"
110
+
111
+ Returns
112
+ -------
113
+ model : torch.nn.Module
114
+ The CLIP model
115
+
116
+ preprocess : Callable[[PIL.Image], torch.Tensor]
117
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
118
+ """
119
+ if name in _MODELS:
120
+ model_path = _download(_MODELS[name], download_root or os.path.abspath("./.cache/clip"))
121
+ elif os.path.isfile(name):
122
+ model_path = name
123
+ else:
124
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
125
+
126
+ with open(model_path, 'rb') as opened_file:
127
+ try:
128
+ # loading JIT archive
129
+ model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
130
+ state_dict = None
131
+ except RuntimeError:
132
+ # loading saved state dict
133
+ if jit:
134
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
135
+ jit = False
136
+ opened_file.seek(0)
137
+ state_dict = torch.load(opened_file, map_location="cpu")
138
+
139
+ if not jit:
140
+ loaded_state = state_dict or model.state_dict()
141
+ # PE-Lang / PE-Core checkpoints are vision-only and do not include CLIP text keys.
142
+ is_pe_state = (
143
+ isinstance(loaded_state, dict)
144
+ and "conv1.weight" in loaded_state
145
+ and "positional_embedding" in loaded_state
146
+ and any(k.startswith("transformer.resblocks.") for k in loaded_state.keys())
147
+ and not any(k.startswith("visual.") for k in loaded_state.keys())
148
+ )
149
+ model = (build_pe_model(loaded_state) if is_pe_state else build_model(loaded_state)).to(device)
150
+ if str(device) == "cpu":
151
+ model.float()
152
+ input_res = getattr(getattr(model, "visual", model), "input_resolution", 224)
153
+ return model, _transform(input_res)
154
+
155
+ # patch the device names
156
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
157
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
158
+
159
+ def patch_device(module):
160
+ try:
161
+ graphs = [module.graph] if hasattr(module, "graph") else []
162
+ except RuntimeError:
163
+ graphs = []
164
+
165
+ if hasattr(module, "forward1"):
166
+ graphs.append(module.forward1.graph)
167
+
168
+ for graph in graphs:
169
+ for node in graph.findAllNodes("prim::Constant"):
170
+ if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
171
+ node.copyAttributes(device_node)
172
+
173
+ model.apply(patch_device)
174
+ patch_device(model.encode_image)
175
+ patch_device(model.encode_text)
176
+
177
+ # patch dtype to float32 on CPU
178
+ if str(device) == "cpu":
179
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
180
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
181
+ float_node = float_input.node()
182
+
183
+ def patch_float(module):
184
+ try:
185
+ graphs = [module.graph] if hasattr(module, "graph") else []
186
+ except RuntimeError:
187
+ graphs = []
188
+
189
+ if hasattr(module, "forward1"):
190
+ graphs.append(module.forward1.graph)
191
+
192
+ for graph in graphs:
193
+ for node in graph.findAllNodes("aten::to"):
194
+ inputs = list(node.inputs())
195
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
196
+ if inputs[i].node()["value"] == 5:
197
+ inputs[i].node().copyAttributes(float_node)
198
+
199
+ model.apply(patch_float)
200
+ patch_float(model.encode_image)
201
+ patch_float(model.encode_text)
202
+
203
+ model.float()
204
+
205
+ return model, _transform(model.input_resolution.item())
206
+
207
+
208
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]:
209
+ """
210
+ Returns the tokenized representation of given input string(s)
211
+
212
+ Parameters
213
+ ----------
214
+ texts : Union[str, List[str]]
215
+ An input string or a list of input strings to tokenize
216
+
217
+ context_length : int
218
+ The context length to use; all CLIP models use 77 as the context length
219
+
220
+ truncate: bool
221
+ Whether to truncate the text in case its encoding is longer than the context length
222
+
223
+ Returns
224
+ -------
225
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
226
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
227
+ """
228
+ if isinstance(texts, str):
229
+ texts = [texts]
230
+
231
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
232
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
233
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
234
+ if version.parse(torch.__version__) < version.parse("1.8.0"):
235
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
236
+ else:
237
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
238
+
239
+ for i, tokens in enumerate(all_tokens):
240
+ if len(tokens) > context_length:
241
+ if truncate:
242
+ tokens = tokens[:context_length]
243
+ tokens[-1] = eot_token
244
+ else:
245
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
246
+ result[i, :len(tokens)] = torch.tensor(tokens)
247
+
248
+ return result
detectors/ForensicConcept/upstream/models/clip/loratorch/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ name = "lora"
2
+
3
+ from .layers import *
4
+ from .utils import *
detectors/ForensicConcept/upstream/models/clip/loratorch/layers.py ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------------------------
2
+ # This code is reconstructed based on loralib (https://github.com/microsoft/LoRA) by Baijiong Lin.
3
+ # ------------------------------------------------------------------------------------------
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ import math
9
+ from typing import Optional, List
10
+
11
+ def set_param(curr_mod, name, param=None, mode='update'):
12
+ r"""Refer to https://github.com/Baijiong-Lin/MOML/blob/main/MTL/utils.py"""
13
+ if '.' in name:
14
+ n = name.split('.')
15
+ module_name = n[0]
16
+ rest = '.'.join(n[1:])
17
+ for name, mod in curr_mod.named_children():
18
+ if module_name == name:
19
+ return set_param(mod, rest, param, mode=mode)
20
+ else:
21
+ if mode == 'update':
22
+ delattr(curr_mod, name)
23
+ setattr(curr_mod, name, param)
24
+ elif mode == 'get':
25
+ if hasattr(curr_mod, name):
26
+ p = getattr(curr_mod, name)
27
+ return p
28
+
29
+ class LoRALayer():
30
+ def __init__(
31
+ self,
32
+ r: int,
33
+ lora_alpha: int,
34
+ fan_in_fan_out: bool = False,
35
+ ):
36
+ self.r = r
37
+ self.lora_alpha = lora_alpha
38
+ if self.r > 0:
39
+ self.scaling = self.lora_alpha / self.r
40
+ # Mark the weight as unmerged
41
+ self.merged = False
42
+ # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
43
+ self.fan_in_fan_out = fan_in_fan_out
44
+ # define params that require LoRA {'param_name': 'lora_name'}
45
+ self.params_with_lora = {}
46
+
47
+ def register_lora_param(self):
48
+ r"""Register LoRA matrix"""
49
+ for param_name, lora_name in self.params_with_lora.items():
50
+ assert len(eval(f'self.{param_name}').size()) == 2
51
+ self.register_parameter(f'{lora_name}_lora_A',
52
+ nn.Parameter(eval(f'self.{param_name}').new_zeros((self.r, eval(f'self.{param_name}').size()[1])))
53
+ )
54
+ self.register_parameter(f'{lora_name}_lora_B',
55
+ nn.Parameter(eval(f'self.{param_name}').new_zeros((eval(f'self.{param_name}').size()[0], self.r)))
56
+ )
57
+ eval(f'self.{param_name}').requires_grad = False
58
+
59
+ def init_lora_param(self):
60
+ for param_name, lora_name in self.params_with_lora.items():
61
+ if hasattr(self, f'{lora_name}_lora_A'):
62
+ # initialize A the same way as the default for nn.Linear and B to zero
63
+ nn.init.kaiming_uniform_(eval(f'self.{lora_name}_lora_A'), a=math.sqrt(5))
64
+ nn.init.zeros_(eval(f'self.{lora_name}_lora_B'))
65
+
66
+ def transpose(self, w: torch.Tensor):
67
+ return w.transpose(0, 1) if self.fan_in_fan_out else w
68
+
69
+ def merge_BA(self, param_name: str):
70
+ lora_name = self.params_with_lora[param_name]
71
+ return self.transpose((eval(f'self.{lora_name}_lora_B') @ eval(f'self.{lora_name}_lora_A')).view(eval(f'self.{param_name}').shape))
72
+
73
+ def merge_lora_param(self):
74
+ r"""p_new = p + scaling * B @ A and keep differentiable to A and B"""
75
+ for param_name, lora_name in self.params_with_lora.items():
76
+ p = set_param(self, param_name, mode='get')
77
+ # detach() is very important here
78
+ p_new = p.detach() + self.merge_BA(param_name) * self.scaling
79
+ set_param(self, param_name, param=p_new, mode='update')
80
+
81
+ def add_lora_data(self):
82
+ r"""NOT differentiable"""
83
+ for param_name, lora_name in self.params_with_lora.items():
84
+ eval(f'self.{param_name}').data += self.merge_BA(param_name) * self.scaling
85
+
86
+ def sub_lora_data(self):
87
+ r"""NOT differentiable"""
88
+ for param_name, lora_name in self.params_with_lora.items():
89
+ eval(f'self.{param_name}').data -= self.merge_BA(param_name) * self.scaling
90
+
91
+ def lora_train(self, mode: bool = True):
92
+ if mode:
93
+ if self.merged and self.r > 0:
94
+ # Make sure that the weights are not merged
95
+ self.sub_lora_data()
96
+ self.merged = False
97
+ else:
98
+ if not self.merged and self.r > 0:
99
+ # Merge the weights and mark it
100
+ self.add_lora_data()
101
+ self.merged = True
102
+
103
+ class LoRAMOELayer():
104
+ def __init__(
105
+ self,
106
+ r: int,
107
+ lora_alpha: int,
108
+ fan_in_fan_out: bool = False,
109
+ ):
110
+ self.r = r
111
+ self.lora_alpha = lora_alpha
112
+ if self.r > 0:
113
+ self.scaling = self.lora_alpha / self.r
114
+ # Mark the weight as unmerged
115
+ self.merged = False
116
+ # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
117
+ self.fan_in_fan_out = fan_in_fan_out
118
+ # define params that require LoRA {'param_name': 'lora_name'}
119
+ self.params_with_lora = {}
120
+
121
+ def register_lora_param(self):
122
+ r"""Register LoRA matrix"""
123
+ for param_name, lora_name in self.params_with_lora.items():
124
+ assert len(eval(f'self.{param_name}').size()) == 2
125
+ self.register_parameter(f'{lora_name}_lora_A',
126
+ nn.Parameter(eval(f'self.{param_name}').new_zeros((self.r, eval(f'self.{param_name}').size()[1])))
127
+ )
128
+ self.register_parameter(f'{lora_name}_lora_B',
129
+ nn.Parameter(eval(f'self.{param_name}').new_zeros((eval(f'self.{param_name}').size()[0], self.r)))
130
+ )
131
+ eval(f'self.{param_name}').requires_grad = False
132
+
133
+ def init_lora_param(self):
134
+ for param_name, lora_name in self.params_with_lora.items():
135
+ if hasattr(self, f'{lora_name}_lora_A'):
136
+ # initialize A the same way as the default for nn.Linear and B to zero
137
+ nn.init.kaiming_uniform_(eval(f'self.{lora_name}_lora_A'), a=math.sqrt(5))
138
+ nn.init.zeros_(eval(f'self.{lora_name}_lora_B'))
139
+
140
+ def transpose(self, w: torch.Tensor):
141
+ return w.transpose(0, 1) if self.fan_in_fan_out else w
142
+
143
+ def merge_BA(self, param_name: str):
144
+ lora_name = self.params_with_lora[param_name]
145
+ return self.transpose((eval(f'self.{lora_name}_lora_B') @ eval(f'self.{lora_name}_lora_A')).view(eval(f'self.{param_name}').shape))
146
+
147
+ def merge_lora_param(self):
148
+ r"""p_new = p + scaling * B @ A and keep differentiable to A and B"""
149
+ for param_name, lora_name in self.params_with_lora.items():
150
+ p = set_param(self, param_name, mode='get')
151
+ # detach() is very important here
152
+ p_new = p.detach() + self.merge_BA(param_name) * self.scaling
153
+ set_param(self, param_name, param=p_new, mode='update')
154
+
155
+ def add_lora_data(self):
156
+ r"""NOT differentiable"""
157
+ for param_name, lora_name in self.params_with_lora.items():
158
+ eval(f'self.{param_name}').data += self.merge_BA(param_name) * self.scaling
159
+
160
+ def sub_lora_data(self):
161
+ r"""NOT differentiable"""
162
+ for param_name, lora_name in self.params_with_lora.items():
163
+ eval(f'self.{param_name}').data -= self.merge_BA(param_name) * self.scaling
164
+
165
+ def lora_train(self, mode: bool = True):
166
+ if mode:
167
+ if self.merged and self.r > 0:
168
+ # Make sure that the weights are not merged
169
+ self.sub_lora_data()
170
+ self.merged = False
171
+ else:
172
+ if not self.merged and self.r > 0:
173
+ # Merge the weights and mark it
174
+ self.add_lora_data()
175
+ self.merged = True
176
+
177
+ class Embedding(nn.Embedding, LoRALayer):
178
+ # LoRA implemented in a Embedding layer
179
+ def __init__(
180
+ self,
181
+ num_embeddings: int,
182
+ embedding_dim: int,
183
+ r: int = 0,
184
+ lora_alpha: int = 1,
185
+ **kwargs
186
+ ):
187
+ nn.Embedding.__init__(self, num_embeddings, embedding_dim, **kwargs)
188
+ LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha)
189
+
190
+ self.params_with_lora = {'weight': 'w'}
191
+ if r > 0:
192
+ self.register_lora_param()
193
+ nn.Embedding.reset_parameters(self)
194
+ self.init_lora_param()
195
+
196
+ def init_lora_param(self):
197
+ if hasattr(self, 'w_lora_A'):
198
+ # initialize A the same way as the default for nn.Linear and B to zero
199
+ nn.init.zeros_(self.w_lora_A)
200
+ nn.init.normal_(self.w_lora_B)
201
+
202
+ def train(self, mode: bool = True):
203
+ nn.Embedding.train(self, mode)
204
+ self.lora_train(mode)
205
+
206
+ def forward(self, x: torch.Tensor, **kwargs):
207
+ if self.r > 0 and not self.merged:
208
+ self.merge_lora_param()
209
+ result = nn.Embedding.forward(self, x, **kwargs)
210
+ self.sub_lora_data()
211
+ return result
212
+ else:
213
+ return nn.Embedding.forward(self, x, **kwargs)
214
+
215
+ class Linear(nn.Linear, LoRALayer):
216
+ # LoRA implemented in a Linear layer
217
+ def __init__(
218
+ self,
219
+ in_features: int,
220
+ out_features: int,
221
+ r: int = 0,
222
+ lora_alpha: int = 1,
223
+ fan_in_fan_out: bool = False,
224
+ **kwargs
225
+ ):
226
+ nn.Linear.__init__(self, in_features, out_features, **kwargs)
227
+ LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha, fan_in_fan_out=fan_in_fan_out)
228
+
229
+ # Actual trainable parameters
230
+ self.params_with_lora = {'weight': 'w'}
231
+ if r > 0:
232
+ self.register_lora_param()
233
+ nn.Linear.reset_parameters(self)
234
+ self.init_lora_param()
235
+ self.weight.data = self.transpose(self.weight.data)
236
+
237
+ def train(self, mode: bool = True):
238
+ nn.Linear.train(self, mode)
239
+ self.lora_train(mode)
240
+
241
+ def forward(self, x: torch.Tensor, **kwargs):
242
+
243
+ if self.r > 0 and not self.merged:
244
+ self.merge_lora_param()
245
+ result = nn.Linear.forward(self, x, **kwargs)
246
+ self.sub_lora_data()
247
+ return result
248
+ else:
249
+ return nn.Linear.forward(self, x, **kwargs)
250
+
251
+ class Conv1d(nn.Conv1d, LoRALayer):
252
+ # LoRA implemented in a Conv1d layer
253
+ def __init__(
254
+ self,
255
+ in_channels: int,
256
+ out_channels: int,
257
+ kernel_size: int,
258
+ r: int = 0,
259
+ lora_alpha: int = 1,
260
+ **kwargs
261
+ ):
262
+ nn.Conv1d.__init__(self, in_channels, out_channels, kernel_size, **kwargs)
263
+ LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha)
264
+
265
+ assert type(kernel_size) is int
266
+ # Actual trainable parameters
267
+ self.params_with_lora = {'weight': 'w'}
268
+ if r > 0:
269
+ self.w_lora_A = nn.Parameter(
270
+ self.weight.new_zeros((r*kernel_size, in_channels*kernel_size))
271
+ )
272
+ self.w_lora_B = nn.Parameter(
273
+ self.weight.new_zeros((out_channels//self.groups*kernel_size, r*kernel_size))
274
+ )
275
+ # Freezing the pre-trained weight matrix
276
+ self.weight.requires_grad = False
277
+ nn.Conv1d.reset_parameters(self)
278
+ self.init_lora_param()
279
+
280
+ def train(self, mode: bool = True):
281
+ nn.Conv1d.train(self, mode)
282
+ self.lora_train(mode)
283
+
284
+ def forward(self, x: torch.Tensor, **kwargs):
285
+
286
+ if self.r > 0 and not self.merged:
287
+ self.merge_lora_param()
288
+ result = nn.Conv1d.forward(self, x, **kwargs)
289
+ self.sub_lora_data()
290
+ return result
291
+ else:
292
+ return nn.Conv1d.forward(self, x, **kwargs)
293
+
294
+ class Conv2d(nn.Conv2d, LoRALayer):
295
+ # LoRA implemented in a Conv2d layer
296
+ def __init__(
297
+ self,
298
+ in_channels: int,
299
+ out_channels: int,
300
+ kernel_size: int,
301
+ r: int = 0,
302
+ lora_alpha: int = 1,
303
+ **kwargs
304
+ ):
305
+ nn.Conv2d.__init__(self, in_channels, out_channels, kernel_size, **kwargs)
306
+ LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha)
307
+
308
+ assert type(kernel_size) is int
309
+ # Actual trainable parameters
310
+ self.params_with_lora = {'weight': 'w'}
311
+ if r > 0:
312
+ self.w_lora_A = nn.Parameter(
313
+ self.weight.new_zeros((r*kernel_size, in_channels*kernel_size))
314
+ )
315
+ self.w_lora_B = nn.Parameter(
316
+ self.weight.new_zeros((out_channels//self.groups*kernel_size, r*kernel_size))
317
+ )
318
+ # Freezing the pre-trained weight matrix
319
+ self.weight.requires_grad = False
320
+ nn.Conv2d.reset_parameters(self)
321
+ self.init_lora_param()
322
+
323
+ def train(self, mode: bool = True):
324
+ nn.Conv2d.train(self, mode)
325
+ self.lora_train(mode)
326
+
327
+ def forward(self, x: torch.Tensor, **kwargs):
328
+
329
+ if self.r > 0 and not self.merged:
330
+ self.merge_lora_param()
331
+ result = nn.Conv2d.forward(self, x, **kwargs)
332
+ self.sub_lora_data()
333
+ return result
334
+ else:
335
+ return nn.Conv2d.forward(self, x, **kwargs)
336
+
337
+ class Conv3d(nn.Conv3d, LoRALayer):
338
+ # LoRA implemented in a Conv3d layer
339
+ def __init__(
340
+ self,
341
+ in_channels: int,
342
+ out_channels: int,
343
+ kernel_size: int,
344
+ r: int = 0,
345
+ lora_alpha: int = 1,
346
+ **kwargs
347
+ ):
348
+ nn.Conv3d.__init__(self, in_channels, out_channels, kernel_size, **kwargs)
349
+ LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha)
350
+
351
+ assert type(kernel_size) is int
352
+ # Actual trainable parameters
353
+ self.params_with_lora = {'weight': 'w'}
354
+ if r > 0:
355
+ self.w_lora_A = nn.Parameter(
356
+ self.weight.new_zeros((r*kernel_size, in_channels*kernel_size))
357
+ )
358
+ self.w_lora_B = nn.Parameter(
359
+ self.weight.new_zeros((out_channels//self.groups*kernel_size, r*kernel_size))
360
+ )
361
+ # Freezing the pre-trained weight matrix
362
+ self.weight.requires_grad = False
363
+ nn.Conv3d.reset_parameters(self)
364
+ self.init_lora_param()
365
+
366
+ def train(self, mode: bool = True):
367
+ nn.Conv3d.train(self, mode)
368
+ self.lora_train(mode)
369
+
370
+ def forward(self, x: torch.Tensor, **kwargs):
371
+
372
+ if self.r > 0 and not self.merged:
373
+ self.merge_lora_param()
374
+ result = nn.Conv3d.forward(self, x, **kwargs)
375
+ self.sub_lora_data()
376
+ return result
377
+ else:
378
+ return nn.Conv3d.forward(self, x, **kwargs)
379
+
380
+ class LoRALayer():
381
+ def __init__(
382
+ self,
383
+ r: int,
384
+ lora_alpha: int,
385
+ fan_in_fan_out: bool = False,
386
+ ):
387
+ self.r = r
388
+ self.lora_alpha = lora_alpha
389
+ if self.r > 0:
390
+ self.scaling = self.lora_alpha / self.r
391
+ # Mark the weight as unmerged
392
+ self.merged = False
393
+ # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
394
+ self.fan_in_fan_out = fan_in_fan_out
395
+ # define params that require LoRA {'param_name': 'lora_name'}
396
+ self.params_with_lora = {}
397
+
398
+ def register_lora_param(self):
399
+ r"""Register LoRA matrix"""
400
+ for param_name, lora_name in self.params_with_lora.items():
401
+ assert len(eval(f'self.{param_name}').size()) == 2
402
+ self.register_parameter(f'{lora_name}_lora_A',
403
+ nn.Parameter(eval(f'self.{param_name}').new_zeros((self.r, eval(f'self.{param_name}').size()[1])))
404
+ )
405
+ self.register_parameter(f'{lora_name}_lora_B',
406
+ nn.Parameter(eval(f'self.{param_name}').new_zeros((eval(f'self.{param_name}').size()[0], self.r)))
407
+ )
408
+ eval(f'self.{param_name}').requires_grad = False
409
+
410
+ def init_lora_param(self):
411
+ for param_name, lora_name in self.params_with_lora.items():
412
+ if hasattr(self, f'{lora_name}_lora_A'):
413
+ # initialize A the same way as the default for nn.Linear and B to zero
414
+ nn.init.kaiming_uniform_(eval(f'self.{lora_name}_lora_A'), a=math.sqrt(5))
415
+ nn.init.zeros_(eval(f'self.{lora_name}_lora_B'))
416
+
417
+ def transpose(self, w: torch.Tensor):
418
+ return w.transpose(0, 1) if self.fan_in_fan_out else w
419
+
420
+ def merge_BA(self, param_name: str):
421
+ lora_name = self.params_with_lora[param_name]
422
+ return self.transpose((eval(f'self.{lora_name}_lora_B') @ eval(f'self.{lora_name}_lora_A')).view(eval(f'self.{param_name}').shape))
423
+
424
+ def merge_lora_param(self):
425
+ r"""p_new = p + scaling * B @ A and keep differentiable to A and B"""
426
+ for param_name, lora_name in self.params_with_lora.items():
427
+ p = set_param(self, param_name, mode='get')
428
+ # detach() is very important here
429
+ p_new = p.detach() + self.merge_BA(param_name) * self.scaling
430
+ set_param(self, param_name, param=p_new, mode='update')
431
+
432
+ def add_lora_data(self):
433
+ r"""NOT differentiable"""
434
+ for param_name, lora_name in self.params_with_lora.items():
435
+ eval(f'self.{param_name}').data += self.merge_BA(param_name) * self.scaling
436
+
437
+ def sub_lora_data(self):
438
+ r"""NOT differentiable"""
439
+ for param_name, lora_name in self.params_with_lora.items():
440
+ eval(f'self.{param_name}').data -= self.merge_BA(param_name) * self.scaling
441
+
442
+ def lora_train(self, mode: bool = True):
443
+ if mode:
444
+ if self.merged and self.r > 0:
445
+ # Make sure that the weights are not merged
446
+ self.sub_lora_data()
447
+ self.merged = False
448
+ else:
449
+ if not self.merged and self.r > 0:
450
+ # Merge the weights and mark it
451
+ self.add_lora_data()
452
+ self.merged = True
453
+
454
+ class MultiheadAttention(nn.MultiheadAttention, LoRALayer):
455
+ # LoRA implemented in a MultiheadAttention layer
456
+ def __init__(
457
+ self,
458
+ embed_dim: int,
459
+ num_heads: int,
460
+ enable_lora: list = ['q', 'k', 'v', 'o'],
461
+ r: int = 0,
462
+ lora_alpha: int = 1,
463
+ **kwargs
464
+ ):
465
+ nn.MultiheadAttention.__init__(self, embed_dim, num_heads, **kwargs)
466
+ LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha)
467
+
468
+ # Actual trainable parameters
469
+ if self.r > 0:
470
+ if 'o' in enable_lora:
471
+ self.params_with_lora.update({'out_proj.weight': 'o'})
472
+
473
+ if not self._qkv_same_embed_dim:
474
+ for n in ['q', 'k', 'v']:
475
+ if n in enable_lora:
476
+ self.params_with_lora.update({f'{n}_proj_weight': n})
477
+ self.register_lora_param()
478
+ nn.MultiheadAttention._reset_parameters(self)
479
+ self.init_lora_param()
480
+ else:
481
+ lora_name, enable_lora_bool = '', []
482
+ for n in ['q', 'k', 'v']:
483
+ if n in enable_lora:
484
+ lora_name += n
485
+ enable_lora_bool.append(True)
486
+ else:
487
+ enable_lora_bool.append(False)
488
+ self.params_with_lora.update({'in_proj_weight': lora_name})
489
+ self.register_lora_param()
490
+ nn.MultiheadAttention._reset_parameters(self)
491
+ self.init_lora_param_qkv(enable_lora_bool)
492
+
493
+ def init_lora_param_qkv(self, enable_lora_bool):
494
+ lora_name = self.params_with_lora['in_proj_weight']
495
+ nn.init.zeros_(eval(f'self.{lora_name}_lora_B'))
496
+ dim = int(self.in_proj_weight.size()[1] / 3)
497
+ for idx, enable in zip(range(3), enable_lora_bool):
498
+ if enable:
499
+ nn.init.kaiming_uniform_(eval(f'self.{lora_name}_lora_A')[:,idx*dim:(idx+1)*dim], a=math.sqrt(5))
500
+ else:
501
+ nn.init.zeros_(eval(f'self.{lora_name}_lora_A')[:,idx*dim:(idx+1)*dim])
502
+
503
+ def train(self, mode: bool = True):
504
+ nn.MultiheadAttention.train(self, mode)
505
+ self.lora_train(mode)
506
+
507
+ def forward(self,
508
+ query: torch.Tensor,
509
+ key: torch.Tensor,
510
+ value: torch.Tensor,
511
+ **kwargs):
512
+ if self.r > 0 and not self.merged:
513
+ self.merge_lora_param()
514
+ result = nn.MultiheadAttention.forward(self, query, key, value, **kwargs)
515
+ self.sub_lora_data()
516
+ return result
517
+ else:
518
+ return nn.MultiheadAttention.forward(self, query, key, value, **kwargs)
519
+
520
+ class MergedLinear(nn.Linear, LoRALayer):
521
+ # LoRA implemented in a dense layer
522
+ def __init__(
523
+ self,
524
+ in_features: int,
525
+ out_features: int,
526
+ r: int = 0,
527
+ lora_alpha: int = 1,
528
+ enable_lora: List[bool] = [False],
529
+ fan_in_fan_out: bool = False,
530
+ **kwargs
531
+ ):
532
+ nn.Linear.__init__(self, in_features, out_features, **kwargs)
533
+ LoRALayer.__init__(self, r=r, lora_alpha=lora_alpha)
534
+
535
+ assert out_features % len(enable_lora) == 0, \
536
+ 'The length of enable_lora must divide out_features'
537
+ self.enable_lora = enable_lora
538
+ # Actual trainable parameters
539
+ self.params_with_lora = {'weight': 'w'}
540
+ if r > 0 and any(enable_lora):
541
+ self.w_lora_A = nn.Parameter(
542
+ self.weight.new_zeros((r * sum(enable_lora), in_features)))
543
+ self.w_lora_B = nn.Parameter(
544
+ self.weight.new_zeros((out_features // len(enable_lora) * sum(enable_lora), r))
545
+ ) # weights for Conv1D with groups=sum(enable_lora)
546
+ # Freezing the pre-trained weight matrix
547
+ self.weight.requires_grad = False
548
+ # Compute the indices
549
+ self.lora_ind = self.weight.new_zeros(
550
+ (out_features, ), dtype=torch.bool
551
+ ).view(len(enable_lora), -1)
552
+ self.lora_ind[enable_lora, :] = True
553
+ self.lora_ind = self.lora_ind.view(-1)
554
+ nn.Linear.reset_parameters(self)
555
+ self.init_lora_param()
556
+ self.weight.data = self.transpose(self.weight.data)
557
+
558
+ def zero_pad(self, x):
559
+ result = x.new_zeros((len(self.lora_ind), *x.shape[1:]))
560
+ result[self.lora_ind] = x
561
+ return result
562
+
563
+ def merge_BA(self, param_name: str):
564
+ lora_name = self.params_with_lora[param_name]
565
+ delta_w = F.conv1d(
566
+ eval(f'self.{lora_name}_lora_A').unsqueeze(0),
567
+ eval(f'self.{lora_name}_lora_B').unsqueeze(-1),
568
+ groups=sum(self.enable_lora)
569
+ ).squeeze(0)
570
+ return self.transpose(self.zero_pad(delta_w))
571
+
572
+ def train(self, mode: bool = True):
573
+ nn.Linear.train(self, mode)
574
+ self.lora_train(mode)
575
+
576
+ def forward(self, x: torch.Tensor, **kwargs):
577
+
578
+ if self.r > 0 and not self.merged:
579
+ self.merge_lora_param()
580
+ result = nn.Linear.forward(self, x, **kwargs)
581
+ self.sub_lora_data()
582
+ return result
583
+ else:
584
+ return nn.Linear.forward(self, x, **kwargs)
detectors/ForensicConcept/upstream/models/clip/loratorch/utils.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------------------------
2
+ # This code is reconstructed based on loralib (https://github.com/microsoft/LoRA) by Baijiong Lin.
3
+ # ------------------------------------------------------------------------------------------
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from typing import Dict
8
+
9
+ from .layers import LoRALayer
10
+
11
+ def print_trainable_parameters(model):
12
+ r"""Prints the number of trainable parameters in the model."""
13
+ trainable_params = 0
14
+ all_param = 0
15
+ for _, param in model.named_parameters():
16
+ all_param += param.numel()
17
+ if param.requires_grad:
18
+ trainable_params += param.numel()
19
+ print(
20
+ f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param:.2f}"
21
+ )
22
+
23
+ def mark_only_lora_as_trainable(model: nn.Module, bias: str = 'none') -> None:
24
+ for n, p in model.named_parameters():
25
+ if 'lora_' not in n:
26
+ p.requires_grad = False
27
+ if bias == 'none':
28
+ return
29
+ elif bias == 'all':
30
+ for n, p in model.named_parameters():
31
+ if 'bias' in n:
32
+ p.requires_grad = True
33
+ elif bias == 'lora_only':
34
+ for m in model.modules():
35
+ if isinstance(m, LoRALayer) and \
36
+ hasattr(m, 'bias') and \
37
+ m.bias is not None:
38
+ m.bias.requires_grad = True
39
+ else:
40
+ raise NotImplementedError
41
+ print_trainable_parameters(model)
42
+
43
+
44
+ def lora_state_dict(model: nn.Module, bias: str = 'none') -> Dict[str, torch.Tensor]:
45
+ my_state_dict = model.state_dict()
46
+ if bias == 'none':
47
+ return {k: my_state_dict[k] for k in my_state_dict if 'lora_' in k}
48
+ elif bias == 'all':
49
+ return {k: my_state_dict[k] for k in my_state_dict if 'lora_' in k or 'bias' in k}
50
+ elif bias == 'lora_only':
51
+ to_return = {}
52
+ for k in my_state_dict:
53
+ if 'lora_' in k:
54
+ to_return[k] = my_state_dict[k]
55
+ bias_name = k.split('lora_')[0]+'bias'
56
+ if bias_name in my_state_dict:
57
+ to_return[bias_name] = my_state_dict[bias_name]
58
+ return to_return
59
+ else:
60
+ raise NotImplementedError
detectors/ForensicConcept/upstream/models/clip/model.py ADDED
@@ -0,0 +1,775 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Optional, Tuple, Union
3
+ import os
4
+
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from torch import nn
9
+
10
+ from . import loratorch
11
+ import math
12
+
13
+
14
+ DEFAULT_LORA_RANK = 4
15
+ DEFAULT_LORA_ALPHA = 8
16
+
17
+
18
+ def set_lora_config(rank: Optional[int] = None, alpha: Optional[int] = None):
19
+ global DEFAULT_LORA_RANK, DEFAULT_LORA_ALPHA
20
+ if rank is not None:
21
+ DEFAULT_LORA_RANK = max(0, rank)
22
+ if alpha is not None:
23
+ DEFAULT_LORA_ALPHA = max(1, alpha)
24
+
25
+ class Bottleneck(nn.Module):
26
+ expansion = 4
27
+
28
+ def __init__(self, inplanes, planes, stride=1):
29
+ super().__init__()
30
+
31
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
32
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
33
+ self.bn1 = nn.BatchNorm2d(planes)
34
+ self.relu1 = nn.ReLU(inplace=True)
35
+
36
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
37
+ self.bn2 = nn.BatchNorm2d(planes)
38
+ self.relu2 = nn.ReLU(inplace=True)
39
+
40
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
41
+
42
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
43
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
44
+ self.relu3 = nn.ReLU(inplace=True)
45
+
46
+ self.downsample = None
47
+ self.stride = stride
48
+
49
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
50
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
51
+ self.downsample = nn.Sequential(OrderedDict([
52
+ ("-1", nn.AvgPool2d(stride)),
53
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
54
+ ("1", nn.BatchNorm2d(planes * self.expansion))
55
+ ]))
56
+
57
+ def forward(self, x: torch.Tensor):
58
+ identity = x
59
+
60
+ out = self.relu1(self.bn1(self.conv1(x)))
61
+ out = self.relu2(self.bn2(self.conv2(out)))
62
+ out = self.avgpool(out)
63
+ out = self.bn3(self.conv3(out))
64
+
65
+ if self.downsample is not None:
66
+ identity = self.downsample(x)
67
+
68
+ out += identity
69
+ out = self.relu3(out)
70
+ return out
71
+
72
+
73
+ class AttentionPool2d(nn.Module):
74
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
75
+ super().__init__()
76
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
77
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
78
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
79
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
80
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
81
+ self.num_heads = num_heads
82
+
83
+ def forward(self, x):
84
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
85
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
86
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
87
+ x, _ = F.multi_head_attention_forward(
88
+ query=x[:1], key=x, value=x,
89
+ embed_dim_to_check=x.shape[-1],
90
+ num_heads=self.num_heads,
91
+ q_proj_weight=self.q_proj.weight,
92
+ k_proj_weight=self.k_proj.weight,
93
+ v_proj_weight=self.v_proj.weight,
94
+ in_proj_weight=None,
95
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
96
+ bias_k=None,
97
+ bias_v=None,
98
+ add_zero_attn=False,
99
+ dropout_p=0,
100
+ out_proj_weight=self.c_proj.weight,
101
+ out_proj_bias=self.c_proj.bias,
102
+ use_separate_proj_weight=True,
103
+ training=self.training,
104
+ need_weights=False
105
+ )
106
+ return x.squeeze(0)
107
+
108
+
109
+ class ModifiedResNet(nn.Module):
110
+ """
111
+ A ResNet class that is similar to torchvision's but contains the following changes:
112
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
113
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
114
+ - The final pooling layer is a QKV attention instead of an average pool
115
+ """
116
+
117
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
118
+ super().__init__()
119
+ self.output_dim = output_dim
120
+ self.input_resolution = input_resolution
121
+
122
+ # the 3-layer stem
123
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
124
+ self.bn1 = nn.BatchNorm2d(width // 2)
125
+ self.relu1 = nn.ReLU(inplace=True)
126
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
127
+ self.bn2 = nn.BatchNorm2d(width // 2)
128
+ self.relu2 = nn.ReLU(inplace=True)
129
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
130
+ self.bn3 = nn.BatchNorm2d(width)
131
+ self.relu3 = nn.ReLU(inplace=True)
132
+ self.avgpool = nn.AvgPool2d(2)
133
+
134
+ # residual layers
135
+ self._inplanes = width # this is a *mutable* variable used during construction
136
+ self.layer1 = self._make_layer(width, layers[0])
137
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
138
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
139
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
140
+
141
+ embed_dim = width * 32 # the ResNet feature dimension
142
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
143
+
144
+ def _make_layer(self, planes, blocks, stride=1):
145
+ layers = [Bottleneck(self._inplanes, planes, stride)]
146
+
147
+ self._inplanes = planes * Bottleneck.expansion
148
+ for _ in range(1, blocks):
149
+ layers.append(Bottleneck(self._inplanes, planes))
150
+
151
+ return nn.Sequential(*layers)
152
+
153
+ def forward(self, x):
154
+ def stem(x):
155
+ x = self.relu1(self.bn1(self.conv1(x)))
156
+ x = self.relu2(self.bn2(self.conv2(x)))
157
+ x = self.relu3(self.bn3(self.conv3(x)))
158
+ x = self.avgpool(x)
159
+ return x
160
+
161
+ x = x.type(self.conv1.weight.dtype)
162
+ x = stem(x)
163
+ x = self.layer1(x)
164
+ x = self.layer2(x)
165
+ x = self.layer3(x)
166
+ x = self.layer4(x)
167
+ x = self.attnpool(x)
168
+
169
+ return x
170
+
171
+
172
+ class LayerNorm(nn.LayerNorm):
173
+ """Subclass torch's LayerNorm to handle fp16."""
174
+
175
+ def forward(self, x: torch.Tensor):
176
+ orig_type = x.dtype
177
+ ret = super().forward(x.type(torch.float32))
178
+ return ret.type(orig_type)
179
+
180
+
181
+ class QuickGELU(nn.Module):
182
+ def forward(self, x: torch.Tensor):
183
+ return x * torch.sigmoid(1.702 * x)
184
+
185
+
186
+ class LayerScale(nn.Module):
187
+ def __init__(self, dim: int, init_value: float = 1.0):
188
+ super().__init__()
189
+ self.gamma = nn.Parameter(torch.ones(dim) * init_value)
190
+
191
+ def forward(self, x: torch.Tensor):
192
+ return x * self.gamma
193
+
194
+
195
+ class Convpass(nn.Module):
196
+ def __init__(self, dim=8, xavier_init=False):
197
+ super().__init__()
198
+
199
+ self.adapter_conv = nn.Conv2d(dim, dim, 3, 1, 1)
200
+ if xavier_init:
201
+ nn.init.xavier_uniform_(self.adapter_conv.weight)
202
+ else:
203
+ nn.init.zeros_(self.adapter_conv.weight)
204
+ self.adapter_conv.weight.data[:, :, 1, 1] += torch.eye(8, dtype=torch.float)
205
+ nn.init.zeros_(self.adapter_conv.bias)
206
+
207
+ self.adapter_down = nn.Linear(1024, dim) # equivalent to 1 * 1 Conv
208
+ # self.adapter_down = nn.Linear(768, dim) # equivalent to 1 * 1 Conv
209
+ # self.adapter_up = nn.Linear(dim, 768) # equivalent to 1 * 1 Conv
210
+ self.adapter_up = nn.Linear(dim, 1024) # equivalent to 1 * 1 Conv
211
+ nn.init.xavier_uniform_(self.adapter_down.weight)
212
+ nn.init.zeros_(self.adapter_down.bias)
213
+ nn.init.zeros_(self.adapter_up.weight)
214
+ nn.init.zeros_(self.adapter_up.bias)
215
+
216
+ self.act = QuickGELU()
217
+ self.dropout = nn.Dropout(0.1)
218
+ self.dim = dim
219
+
220
+ def forward(self, x):
221
+ N, B, C = x.shape
222
+
223
+ x_down = self.adapter_down(x) # equivalent to 1 * 1 Conv
224
+ x_down = self.act(x_down)
225
+
226
+ x_patch = x_down[1:, :].reshape(B, 16, 16, self.dim).permute(0, 3, 1, 2)
227
+ x_patch = self.adapter_conv(x_patch)
228
+ x_patch = x_patch.permute(0, 2, 3, 1).reshape(B, 16 * 16, self.dim)
229
+
230
+ x_cls = x_down[:1, :].reshape(B, 1, 1, self.dim).permute(0, 3, 1, 2)
231
+ x_cls = self.adapter_conv(x_cls)
232
+ x_cls = x_cls.permute(0, 2, 3, 1).reshape(B, 1, self.dim)
233
+
234
+ x_down = torch.cat([x_cls, x_patch], dim=1)
235
+
236
+ x_down = self.act(x_down)
237
+ x_down = self.dropout(x_down)
238
+ x_up = self.adapter_up(x_down) # equivalent to 1 * 1 Conv
239
+
240
+ x_up = x_up.permute(1, 0, 2)
241
+
242
+ return x_up
243
+
244
+ class ResidualAttentionBlock(nn.Module):
245
+ def __init__(
246
+ self,
247
+ d_model: int,
248
+ n_head: int,
249
+ attn_mask: torch.Tensor = None,
250
+ mlp_hidden_dim: Optional[int] = None,
251
+ ):
252
+ super().__init__()
253
+
254
+ if DEFAULT_LORA_RANK > 0:
255
+ self.attn = loratorch.MultiheadAttention(
256
+ d_model,
257
+ n_head,
258
+ r=DEFAULT_LORA_RANK,
259
+ lora_alpha=DEFAULT_LORA_ALPHA,
260
+ enable_lora=['q', 'k', 'v'], # 仅对 qkv 加 LoRA,关闭 out_proj LoRA
261
+ )
262
+ else:
263
+ self.attn = nn.MultiheadAttention(d_model, n_head)
264
+ self.ln_1 = LayerNorm(d_model)
265
+ hidden_dim = int(mlp_hidden_dim) if mlp_hidden_dim is not None else d_model * 4
266
+ self.mlp = nn.Sequential(OrderedDict([
267
+ ("c_fc", nn.Linear(d_model, hidden_dim)),
268
+ ("gelu", QuickGELU()),
269
+ ("c_proj", nn.Linear(hidden_dim, d_model))
270
+ ]))
271
+ self.ls_1 = LayerScale(d_model, init_value=1.0)
272
+ self.ls_2 = LayerScale(d_model, init_value=1.0)
273
+ self.ln_2 = LayerNorm(d_model)
274
+ self.attn_mask = attn_mask
275
+ # self.adapter_mlp = Convpass()
276
+ self.s = 1.
277
+ self.store_attn = False
278
+ self.track_attn_grad = False
279
+ self.attn_storage = []
280
+
281
+ def attention(self, x: torch.Tensor):
282
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
283
+ if self.store_attn:
284
+ out, attn_weights = self.attn(
285
+ x, x, x, need_weights=True, attn_mask=self.attn_mask, average_attn_weights=False
286
+ )
287
+ if self.track_attn_grad:
288
+ attn_weights.retain_grad()
289
+ self.attn_storage.append(attn_weights)
290
+ return out
291
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
292
+
293
+ def forward(self, x: torch.Tensor):
294
+ x = x + self.ls_1(self.attention(self.ln_1(x)))
295
+ x = x + self.ls_2(self.mlp(self.ln_2(x)))
296
+ # x = x + self.mlp(self.ln_2(x)) + (self.adapter_mlp(self.ln_2(x))) * self.s
297
+ return x
298
+
299
+
300
+ class Transformer(nn.Module):
301
+ def __init__(
302
+ self,
303
+ width: int,
304
+ layers: int,
305
+ heads: int,
306
+ attn_mask: torch.Tensor = None,
307
+ mlp_hidden_dim: Optional[int] = None,
308
+ ):
309
+ super().__init__()
310
+ self.width = width
311
+ self.layers = layers
312
+ self.resblocks = nn.Sequential(
313
+ *[
314
+ ResidualAttentionBlock(
315
+ width,
316
+ heads,
317
+ attn_mask,
318
+ mlp_hidden_dim=mlp_hidden_dim,
319
+ )
320
+ for _ in range(layers)
321
+ ]
322
+ )
323
+ # Load pre-saved initialization from NPR if available.
324
+ # NOTE: removed custom resblocks init load to avoid shape mismatch; base CLIP weights are used as-is.
325
+
326
+ def enable_attention_tracking(self, track_grad: bool = False):
327
+ for block in self.resblocks:
328
+ block.store_attn = True
329
+ block.track_attn_grad = bool(track_grad)
330
+ block.attn_storage = []
331
+
332
+ def clear_attention_storage(self):
333
+ for block in self.resblocks:
334
+ block.attn_storage = []
335
+
336
+ def forward(self, x: torch.Tensor):
337
+ out = {}
338
+ for idx, layer in enumerate(self.resblocks.children()):
339
+ x = layer(x)
340
+ out['layer'+str(idx)] = x[0] # shape:LND. choose cls token feature
341
+ return out, x
342
+
343
+ # return self.resblocks(x) # This is the original code
344
+
345
+
346
+ class VisionTransformer(nn.Module):
347
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
348
+ super().__init__()
349
+ self.input_resolution = input_resolution
350
+ self.output_dim = output_dim
351
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
352
+ self.grid_size = input_resolution // patch_size
353
+
354
+ scale = width ** -0.5
355
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
356
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
357
+ self.ln_pre = LayerNorm(width)
358
+
359
+ self.transformer = Transformer(width, layers, heads)
360
+
361
+ self.ln_post = LayerNorm(width)
362
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
363
+
364
+
365
+
366
+ def _encode_tokens(self, x: torch.Tensor):
367
+ x = self.conv1(x) # shape = [*, width, grid_h, grid_w]
368
+ grid_h, grid_w = x.shape[-2], x.shape[-1]
369
+
370
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
371
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
372
+
373
+ class_embed = self.class_embedding.to(x.dtype)
374
+ class_embed = class_embed + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device)
375
+ x = torch.cat([class_embed, x], dim=1) # shape = [*, grid ** 2 + 1, width]
376
+
377
+ if grid_h != self.grid_size or grid_w != self.grid_size:
378
+ patch_pos = self.positional_embedding[1:]
379
+ patch_pos = patch_pos.reshape(1, self.grid_size, self.grid_size, -1).permute(0, 3, 1, 2)
380
+ patch_pos = F.interpolate(patch_pos, size=(grid_h, grid_w), mode='bicubic', align_corners=False)
381
+ patch_pos = patch_pos.permute(0, 2, 3, 1).reshape(grid_h * grid_w, -1)
382
+ pos_embed = torch.cat([self.positional_embedding[:1], patch_pos], dim=0)
383
+ else:
384
+ pos_embed = self.positional_embedding
385
+
386
+ x = x + pos_embed.to(x.dtype)
387
+ x = self.ln_pre(x)
388
+
389
+ x = x.permute(1, 0, 2) # NLD -> LND
390
+ out, x = self.transformer(x)
391
+ x = x.permute(1, 0, 2) # LND -> NLD
392
+ x = self.ln_post(x)
393
+ out['before_projection'] = x
394
+ if self.proj is not None:
395
+ x = x @ self.proj
396
+ out['after_projection'] = x
397
+
398
+ cls = x[:, 0, :]
399
+ return cls, x
400
+
401
+ def forward(self, x: torch.Tensor):
402
+ cls, _ = self._encode_tokens(x)
403
+ return cls
404
+
405
+ def forward_with_tokens(self, x: torch.Tensor):
406
+ return self._encode_tokens(x)
407
+
408
+ # Return both intermediate features and final clip feature
409
+ # return out
410
+
411
+ # This only returns CLIP features
412
+ return x
413
+
414
+ def enable_attention_tracking(self, track_grad: bool = False):
415
+ self.transformer.enable_attention_tracking(track_grad=track_grad)
416
+
417
+ def clear_attention_storage(self):
418
+ self.transformer.clear_attention_storage()
419
+
420
+
421
+ class PerceptionVisionTransformer(nn.Module):
422
+ """
423
+ Vision-only transformer used by Perception Encoder checkpoints.
424
+ Unlike OpenAI CLIP ViT, this backbone has no class token/projection heads.
425
+ """
426
+
427
+ def __init__(
428
+ self,
429
+ input_resolution: int,
430
+ patch_size: int,
431
+ width: int,
432
+ layers: int,
433
+ heads: int,
434
+ num_pos_tokens: int,
435
+ mlp_hidden_dim: Optional[int] = None,
436
+ ):
437
+ super().__init__()
438
+ self.input_resolution = int(input_resolution)
439
+ self.patch_size = int(patch_size)
440
+ self.output_dim = int(width)
441
+ self.grid_size = self.input_resolution // self.patch_size
442
+ self.num_pos_tokens = int(num_pos_tokens)
443
+
444
+ self.conv1 = nn.Conv2d(
445
+ in_channels=3,
446
+ out_channels=width,
447
+ kernel_size=self.patch_size,
448
+ stride=self.patch_size,
449
+ bias=False,
450
+ )
451
+ scale = width ** -0.5
452
+ self.positional_embedding = nn.Parameter(scale * torch.randn(self.num_pos_tokens, width))
453
+ self.ln_pre = LayerNorm(width)
454
+ self.transformer = Transformer(width, layers, heads, mlp_hidden_dim=mlp_hidden_dim)
455
+
456
+ def _resize_positional_embedding(self, grid_h: int, grid_w: int, dtype: torch.dtype) -> torch.Tensor:
457
+ if self.positional_embedding.shape[0] == grid_h * grid_w:
458
+ return self.positional_embedding.to(dtype)
459
+
460
+ base_grid = round(self.positional_embedding.shape[0] ** 0.5)
461
+ if base_grid * base_grid != self.positional_embedding.shape[0]:
462
+ raise ValueError(
463
+ f"Invalid positional embedding length {self.positional_embedding.shape[0]} "
464
+ f"for PE backbone (expected perfect square)."
465
+ )
466
+
467
+ patch_pos = self.positional_embedding.reshape(base_grid, base_grid, -1).permute(2, 0, 1).unsqueeze(0)
468
+ patch_pos = F.interpolate(patch_pos, size=(grid_h, grid_w), mode="bicubic", align_corners=False)
469
+ patch_pos = patch_pos.squeeze(0).permute(1, 2, 0).reshape(grid_h * grid_w, -1)
470
+ return patch_pos.to(dtype)
471
+
472
+ def _encode_tokens(self, x: torch.Tensor):
473
+ x = self.conv1(x) # [B,C,H',W']
474
+ grid_h, grid_w = x.shape[-2], x.shape[-1]
475
+ x = x.reshape(x.shape[0], x.shape[1], -1).permute(0, 2, 1) # [B,N,C]
476
+
477
+ pos_embed = self._resize_positional_embedding(grid_h, grid_w, x.dtype)
478
+ x = x + pos_embed
479
+ x = self.ln_pre(x)
480
+
481
+ x = x.permute(1, 0, 2) # NLD -> LND
482
+ _, x = self.transformer(x)
483
+ x = x.permute(1, 0, 2) # LND -> NLD
484
+
485
+ pooled = x.mean(dim=1)
486
+ # Keep CLIP-compatible output shape expected by downstream wrapper:
487
+ # prepend pooled token so callers can strip [:, 1:, :] as patch tokens.
488
+ tokens_with_pooled = torch.cat([pooled.unsqueeze(1), x], dim=1)
489
+ return pooled, tokens_with_pooled
490
+
491
+ def forward(self, x: torch.Tensor):
492
+ pooled, _ = self._encode_tokens(x)
493
+ return pooled
494
+
495
+ def forward_with_tokens(self, x: torch.Tensor):
496
+ return self._encode_tokens(x)
497
+
498
+ def enable_attention_tracking(self, track_grad: bool = False):
499
+ self.transformer.enable_attention_tracking(track_grad=track_grad)
500
+
501
+ def clear_attention_storage(self):
502
+ self.transformer.clear_attention_storage()
503
+
504
+
505
+ class PerceptionCLIPWrapper(nn.Module):
506
+ """
507
+ Minimal CLIP-like wrapper around PE visual backbone.
508
+ Exposes encode_image / encode_image_with_tokens used by CLIPModel.
509
+ """
510
+
511
+ def __init__(self, visual: PerceptionVisionTransformer):
512
+ super().__init__()
513
+ self.visual = visual
514
+
515
+ @property
516
+ def dtype(self):
517
+ return self.visual.conv1.weight.dtype
518
+
519
+ def encode_image(self, image: torch.Tensor):
520
+ return self.visual(image.type(self.dtype))
521
+
522
+ def encode_image_with_tokens(self, image: torch.Tensor):
523
+ return self.visual.forward_with_tokens(image.type(self.dtype))
524
+
525
+
526
+ class CLIP(nn.Module):
527
+ def __init__(self,
528
+ embed_dim: int,
529
+ # vision
530
+ image_resolution: int,
531
+ vision_layers: Union[Tuple[int, int, int, int], int],
532
+ vision_width: int,
533
+ vision_patch_size: int,
534
+ # text
535
+ context_length: int,
536
+ vocab_size: int,
537
+ transformer_width: int,
538
+ transformer_heads: int,
539
+ transformer_layers: int
540
+ ):
541
+ super().__init__()
542
+ self.context_length = context_length
543
+
544
+ if isinstance(vision_layers, (tuple, list)):
545
+ vision_heads = vision_width * 32 // 64
546
+ self.visual = ModifiedResNet(
547
+ layers=vision_layers,
548
+ output_dim=embed_dim,
549
+ heads=vision_heads,
550
+ input_resolution=image_resolution,
551
+ width=vision_width
552
+ )
553
+ else:
554
+ vision_heads = vision_width // 64
555
+ self.visual = VisionTransformer(
556
+ input_resolution=image_resolution,
557
+ patch_size=vision_patch_size,
558
+ width=vision_width,
559
+ layers=vision_layers,
560
+ heads=vision_heads,
561
+ output_dim=embed_dim
562
+ )
563
+
564
+ # 文本侧不用 LoRA,临时将 LoRA 配置置零后再恢复,避免修改接口或影响视觉侧
565
+ _old_rank, _old_alpha = DEFAULT_LORA_RANK, DEFAULT_LORA_ALPHA
566
+ try:
567
+ set_lora_config(rank=0, alpha=_old_alpha)
568
+ self.transformer = Transformer(
569
+ width=transformer_width,
570
+ layers=transformer_layers,
571
+ heads=transformer_heads,
572
+ attn_mask=self.build_attention_mask()
573
+ )
574
+ finally:
575
+ set_lora_config(rank=_old_rank, alpha=_old_alpha)
576
+
577
+ self.vocab_size = vocab_size
578
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
579
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
580
+ self.ln_final = LayerNorm(transformer_width)
581
+
582
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
583
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
584
+
585
+ self.initialize_parameters()
586
+
587
+ def initialize_parameters(self):
588
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
589
+ nn.init.normal_(self.positional_embedding, std=0.01)
590
+
591
+ if isinstance(self.visual, ModifiedResNet):
592
+ if self.visual.attnpool is not None:
593
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
594
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
595
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
596
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
597
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
598
+
599
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
600
+ for name, param in resnet_block.named_parameters():
601
+ if name.endswith("bn3.weight"):
602
+ nn.init.zeros_(param)
603
+
604
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
605
+ attn_std = self.transformer.width ** -0.5
606
+ fc_std = (2 * self.transformer.width) ** -0.5
607
+ for block in self.transformer.resblocks:
608
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
609
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
610
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
611
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
612
+
613
+ if self.text_projection is not None:
614
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
615
+
616
+ def build_attention_mask(self):
617
+ # lazily create causal attention mask, with full attention between the vision tokens
618
+ # pytorch uses additive attention mask; fill with -inf
619
+ mask = torch.empty(self.context_length, self.context_length)
620
+ mask.fill_(float("-inf"))
621
+ mask.triu_(1) # zero out the lower diagonal
622
+ return mask
623
+
624
+ @property
625
+ def dtype(self):
626
+ return self.visual.conv1.weight.dtype
627
+
628
+ def encode_image(self, image):
629
+ return self.visual(image.type(self.dtype))
630
+
631
+ def encode_image_with_tokens(self, image):
632
+ if not hasattr(self.visual, "forward_with_tokens"):
633
+ raise RuntimeError("Visual backbone does not support token outputs.")
634
+ return self.visual.forward_with_tokens(image.type(self.dtype))
635
+
636
+ def encode_text(self, text):
637
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
638
+
639
+ x = x + self.positional_embedding.type(self.dtype)
640
+ x = x.permute(1, 0, 2) # NLD -> LND
641
+ x = self.transformer(x)
642
+ x = x.permute(1, 0, 2) # LND -> NLD
643
+ x = self.ln_final(x).type(self.dtype)
644
+
645
+ # x.shape = [batch_size, n_ctx, transformer.width]
646
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
647
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
648
+
649
+ return x
650
+
651
+ def forward(self, image, text):
652
+ image_features = self.encode_image(image)
653
+ text_features = self.encode_text(text)
654
+
655
+ # normalized features
656
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
657
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
658
+
659
+ # cosine similarity as logits
660
+ logit_scale = self.logit_scale.exp()
661
+ logits_per_image = logit_scale * image_features @ text_features.t()
662
+ logits_per_text = logits_per_image.t()
663
+
664
+ # shape = [global_batch_size, global_batch_size]
665
+ return logits_per_image, logits_per_text
666
+
667
+
668
+ def convert_weights(model: nn.Module):
669
+ """Convert applicable model parameters to fp16"""
670
+
671
+ def _convert_weights_to_fp16(l):
672
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
673
+ l.weight.data = l.weight.data.half()
674
+ if l.bias is not None:
675
+ l.bias.data = l.bias.data.half()
676
+
677
+ if isinstance(l, nn.MultiheadAttention):
678
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
679
+ tensor = getattr(l, attr)
680
+ if tensor is not None:
681
+ tensor.data = tensor.data.half()
682
+
683
+ for name in ["text_projection", "proj"]:
684
+ if hasattr(l, name):
685
+ attr = getattr(l, name)
686
+ if attr is not None:
687
+ attr.data = attr.data.half()
688
+
689
+ model.apply(_convert_weights_to_fp16)
690
+
691
+
692
+ def build_pe_model(state_dict: dict):
693
+ required_keys = ["conv1.weight", "ln_pre.weight", "ln_pre.bias", "positional_embedding"]
694
+ for key in required_keys:
695
+ if key not in state_dict:
696
+ raise KeyError(f"Missing key `{key}` in PE checkpoint")
697
+
698
+ vision_width = state_dict["conv1.weight"].shape[0]
699
+ vision_patch_size = state_dict["conv1.weight"].shape[-1]
700
+ num_pos_tokens = state_dict["positional_embedding"].shape[0]
701
+ grid_size = round(num_pos_tokens ** 0.5)
702
+ if grid_size * grid_size != num_pos_tokens:
703
+ raise ValueError(
704
+ f"PE positional_embedding length {num_pos_tokens} is not a perfect square."
705
+ )
706
+ image_resolution = vision_patch_size * grid_size
707
+ vision_layers = len(
708
+ [
709
+ k
710
+ for k in state_dict.keys()
711
+ if k.startswith("transformer.resblocks.") and k.endswith(".attn.in_proj_weight")
712
+ ]
713
+ )
714
+ mlp_hidden_dim = int(state_dict["transformer.resblocks.0.mlp.c_fc.weight"].shape[0])
715
+ vision_heads = max(1, vision_width // 64)
716
+
717
+ visual = PerceptionVisionTransformer(
718
+ input_resolution=image_resolution,
719
+ patch_size=vision_patch_size,
720
+ width=vision_width,
721
+ layers=vision_layers,
722
+ heads=vision_heads,
723
+ num_pos_tokens=num_pos_tokens,
724
+ mlp_hidden_dim=mlp_hidden_dim,
725
+ )
726
+
727
+ missing, unexpected = visual.load_state_dict(state_dict, strict=False)
728
+ missing_non_lora = [k for k in missing if "lora_" not in k]
729
+ if unexpected:
730
+ print(f"[PE] Unexpected checkpoint keys (showing up to 8): {unexpected[:8]}")
731
+ if missing_non_lora:
732
+ print(f"[PE] Missing checkpoint keys (showing up to 8): {missing_non_lora[:8]}")
733
+
734
+ return PerceptionCLIPWrapper(visual).eval()
735
+
736
+
737
+ def build_model(state_dict: dict):
738
+ vit = "visual.proj" in state_dict
739
+
740
+ if vit:
741
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
742
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
743
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
744
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
745
+ image_resolution = vision_patch_size * grid_size
746
+ else:
747
+ 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]]
748
+ vision_layers = tuple(counts)
749
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
750
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
751
+ vision_patch_size = None
752
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
753
+ image_resolution = output_width * 32
754
+
755
+ embed_dim = state_dict["text_projection"].shape[1]
756
+ context_length = state_dict["positional_embedding"].shape[0]
757
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
758
+ transformer_width = state_dict["ln_final.weight"].shape[0]
759
+ transformer_heads = transformer_width // 64
760
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
761
+
762
+ model = CLIP(
763
+ embed_dim,
764
+ image_resolution, vision_layers, vision_width, vision_patch_size,
765
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
766
+ )
767
+
768
+ for key in ["input_resolution", "context_length", "vocab_size"]:
769
+ if key in state_dict:
770
+ del state_dict[key]
771
+
772
+ convert_weights(model)
773
+ model.load_state_dict(state_dict, strict=False)
774
+
775
+ return model.eval()
detectors/ForensicConcept/upstream/models/clip/simple_tokenizer.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import html
3
+ import os
4
+ from functools import lru_cache
5
+
6
+ import ftfy
7
+ import regex as re
8
+
9
+
10
+ @lru_cache()
11
+ def default_bpe():
12
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
13
+
14
+
15
+ @lru_cache()
16
+ def bytes_to_unicode():
17
+ """
18
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
19
+ The reversible bpe codes work on unicode strings.
20
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
21
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
22
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
23
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
24
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
25
+ """
26
+ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
27
+ cs = bs[:]
28
+ n = 0
29
+ for b in range(2**8):
30
+ if b not in bs:
31
+ bs.append(b)
32
+ cs.append(2**8+n)
33
+ n += 1
34
+ cs = [chr(n) for n in cs]
35
+ return dict(zip(bs, cs))
36
+
37
+
38
+ def get_pairs(word):
39
+ """Return set of symbol pairs in a word.
40
+ Word is represented as tuple of symbols (symbols being variable-length strings).
41
+ """
42
+ pairs = set()
43
+ prev_char = word[0]
44
+ for char in word[1:]:
45
+ pairs.add((prev_char, char))
46
+ prev_char = char
47
+ return pairs
48
+
49
+
50
+ def basic_clean(text):
51
+ text = ftfy.fix_text(text)
52
+ text = html.unescape(html.unescape(text))
53
+ return text.strip()
54
+
55
+
56
+ def whitespace_clean(text):
57
+ text = re.sub(r'\s+', ' ', text)
58
+ text = text.strip()
59
+ return text
60
+
61
+
62
+ class SimpleTokenizer(object):
63
+ def __init__(self, bpe_path: str = default_bpe()):
64
+ self.byte_encoder = bytes_to_unicode()
65
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
66
+ merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
67
+ merges = merges[1:49152-256-2+1]
68
+ merges = [tuple(merge.split()) for merge in merges]
69
+ vocab = list(bytes_to_unicode().values())
70
+ vocab = vocab + [v+'</w>' for v in vocab]
71
+ for merge in merges:
72
+ vocab.append(''.join(merge))
73
+ vocab.extend(['<|startoftext|>', '<|endoftext|>'])
74
+ self.encoder = dict(zip(vocab, range(len(vocab))))
75
+ self.decoder = {v: k for k, v in self.encoder.items()}
76
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
77
+ self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
78
+ 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)
79
+
80
+ def bpe(self, token):
81
+ if token in self.cache:
82
+ return self.cache[token]
83
+ word = tuple(token[:-1]) + ( token[-1] + '</w>',)
84
+ pairs = get_pairs(word)
85
+
86
+ if not pairs:
87
+ return token+'</w>'
88
+
89
+ while True:
90
+ bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
91
+ if bigram not in self.bpe_ranks:
92
+ break
93
+ first, second = bigram
94
+ new_word = []
95
+ i = 0
96
+ while i < len(word):
97
+ try:
98
+ j = word.index(first, i)
99
+ new_word.extend(word[i:j])
100
+ i = j
101
+ except:
102
+ new_word.extend(word[i:])
103
+ break
104
+
105
+ if word[i] == first and i < len(word)-1 and word[i+1] == second:
106
+ new_word.append(first+second)
107
+ i += 2
108
+ else:
109
+ new_word.append(word[i])
110
+ i += 1
111
+ new_word = tuple(new_word)
112
+ word = new_word
113
+ if len(word) == 1:
114
+ break
115
+ else:
116
+ pairs = get_pairs(word)
117
+ word = ' '.join(word)
118
+ self.cache[token] = word
119
+ return word
120
+
121
+ def encode(self, text):
122
+ bpe_tokens = []
123
+ text = whitespace_clean(basic_clean(text)).lower()
124
+ for token in re.findall(self.pat, text):
125
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
126
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
127
+ return bpe_tokens
128
+
129
+ def decode(self, tokens):
130
+ text = ''.join([self.decoder[token] for token in tokens])
131
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
132
+ return text
detectors/ForensicConcept/upstream/models/clip_models.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from .clip import clip, set_lora_config
9
+
10
+
11
+ CHANNELS = {
12
+ "RN50": 1024,
13
+ "ViT-L/14": 768,
14
+ "ViT-L/14@336px": 768,
15
+ "PE-Lang-L14-448": 1024,
16
+ "PE-Lang-G14-448": 1536,
17
+ "PE-Core-G14-448": 1536,
18
+ }
19
+
20
+
21
+ def _load_codebook(path: str) -> torch.Tensor:
22
+ """Load codebook from .npy or .pt/.pth"""
23
+ if path is None:
24
+ raise ValueError("codebook_path is None")
25
+ if path.endswith(".npy"):
26
+ arr = np.load(path)
27
+ cb = torch.from_numpy(arr).float()
28
+ else:
29
+ obj = torch.load(path, map_location="cpu")
30
+ if isinstance(obj, dict):
31
+ for k in ["codebook", "centroids", "C"]:
32
+ if k in obj:
33
+ obj = obj[k]
34
+ break
35
+ cb = obj.float() if torch.is_tensor(obj) else torch.tensor(obj, dtype=torch.float32)
36
+ if cb.ndim != 2:
37
+ raise ValueError(f"codebook must be 2D, got {tuple(cb.shape)} from {path}")
38
+ return cb
39
+
40
+
41
+ class CodebookTopKHead(nn.Module):
42
+ """
43
+ Top-k patch pooling guided by codebook similarity.
44
+ tokens: [B,N,dim_x]
45
+ codebook: [K,dim_c] (assumed L2 normalized if clip_codebook_l2=True at load)
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ dim_x: int,
51
+ dim_c: int,
52
+ num_concepts: int,
53
+ tau: float = 0.1,
54
+ tau_w: float = 0.1,
55
+ topk_m: int = 20,
56
+ top_r: int = 8,
57
+ weight_mode: str = "score",
58
+ l2_codebook: bool = True,
59
+ freeze_codebook: bool = True,
60
+ mlp_hidden: int = None,
61
+ ):
62
+ super().__init__()
63
+ self.dim_x = dim_x
64
+ self.dim_c = dim_c
65
+ self.num_concepts = num_concepts
66
+ self.tau = tau
67
+ self.tau_w = tau_w
68
+ self.topk_m = topk_m
69
+ self.top_r = top_r
70
+ self.weight_mode = (weight_mode or "score").lower()
71
+ self.l2_codebook = l2_codebook
72
+ self.freeze_codebook = freeze_codebook
73
+
74
+ self.w_q = nn.Linear(dim_x, dim_c, bias=False)
75
+ self.register_buffer("codebook", torch.empty(num_concepts, dim_c), persistent=True)
76
+
77
+ hidden = mlp_hidden if mlp_hidden is not None else dim_x
78
+ self.mlp = nn.Sequential(
79
+ nn.LayerNorm(dim_x),
80
+ nn.Linear(dim_x, hidden),
81
+ nn.GELU(),
82
+ nn.Linear(hidden, 1),
83
+ )
84
+
85
+ @torch.no_grad()
86
+ def set_codebook(self, codebook: torch.Tensor):
87
+ if codebook.shape != self.codebook.shape:
88
+ raise ValueError(
89
+ f"codebook shape mismatch: got {tuple(codebook.shape)} expected {tuple(self.codebook.shape)}"
90
+ )
91
+ cb = codebook.float()
92
+ if self.l2_codebook:
93
+ cb = F.normalize(cb, dim=-1)
94
+ self.codebook.copy_(cb)
95
+
96
+ def forward(self, tokens: torch.Tensor, return_feature: bool = False):
97
+ """
98
+ returns:
99
+ logits_cb: [B,1]
100
+ score: [B,N]
101
+ idx: [B,m]
102
+ """
103
+ bsz, num_patches, dim_x = tokens.shape
104
+ if dim_x != self.dim_x:
105
+ raise ValueError(f"tokens dim mismatch: {dim_x} vs {self.dim_x}")
106
+
107
+ q_raw = self.w_q(tokens)
108
+ q = F.normalize(q_raw, dim=-1)
109
+ k = self.codebook.detach() if self.freeze_codebook else self.codebook
110
+
111
+ s = torch.matmul(q, k.t()) / max(self.tau, 1e-8)
112
+ r = int(self.top_r) if self.top_r else 1
113
+ r = min(r, s.shape[-1])
114
+ top_vals, top_ids = s.topk(k=r, dim=-1)
115
+ score = top_vals.mean(dim=-1)
116
+
117
+ m = int(self.topk_m) if self.topk_m else num_patches
118
+ m = min(m, num_patches)
119
+ score_sel, idx = torch.topk(score, k=m, dim=1)
120
+ top_ids_sel = top_ids.gather(1, idx.unsqueeze(-1).expand(-1, -1, top_ids.shape[-1]))
121
+ concept_id = s.argmax(dim=-1)
122
+ topk_concept = concept_id.gather(1, idx)
123
+
124
+ x_sel = tokens.gather(1, idx.unsqueeze(-1).expand(-1, -1, dim_x))
125
+ if self.weight_mode == "score":
126
+ patch_weight = score_sel
127
+ elif self.weight_mode == "concept":
128
+ s_sel = s.gather(1, idx.unsqueeze(-1).expand(-1, -1, s.shape[-1]))
129
+ concept_prob = F.softmax(s_sel, dim=-1)
130
+ patch_weight = concept_prob.max(dim=-1).values
131
+ else:
132
+ raise ValueError(f"Unsupported weight_mode: {self.weight_mode}")
133
+
134
+ w = F.softmax(patch_weight / max(self.tau_w, 1e-8), dim=1)
135
+ g = (w.unsqueeze(-1) * x_sel).sum(dim=1)
136
+
137
+ logits_cb = self.mlp(g)
138
+ if return_feature:
139
+ return logits_cb, score, idx, top_ids_sel, g
140
+ return logits_cb, score, idx, top_ids_sel
141
+
142
+
143
+ class CLIPModel(nn.Module):
144
+ """CLIP wrapper: CLS head + codebook top-k head."""
145
+
146
+ def __init__(self, name, num_classes=1, opt=None):
147
+ super().__init__()
148
+
149
+ clip_rank = getattr(opt, "clip_lora_rank", 4) if opt is not None else 4
150
+ clip_alpha = getattr(opt, "clip_lora_alpha", 8) if opt is not None else 8
151
+ set_lora_config(rank=clip_rank, alpha=clip_alpha)
152
+
153
+ load_init = True if opt is None else bool(getattr(opt, "clip_load_init_weights", True))
154
+ os.environ["CLIP_USE_INIT"] = "1" if load_init else "0"
155
+
156
+ weight_path = getattr(opt, "clip_model_path", None)
157
+ load_target = weight_path if weight_path else name
158
+ self.model, self.preprocess = clip.load(load_target, device="cpu")
159
+
160
+ # If explicit checkpoint path is provided, trust loaded model metadata first.
161
+ in_features = None
162
+ if weight_path:
163
+ in_features = getattr(self.model.visual, "output_dim", None)
164
+ if in_features is None:
165
+ in_features = CHANNELS.get(name)
166
+ if in_features is None:
167
+ in_features = getattr(self.model.visual, "output_dim", None)
168
+ if in_features is None:
169
+ with torch.no_grad():
170
+ res = getattr(self.model.visual, "input_resolution", 224)
171
+ dummy = torch.zeros(1, 3, res, res)
172
+ in_features = self.model.encode_image(dummy).shape[-1]
173
+
174
+ self.dim_x = int(in_features)
175
+ self.opt = opt
176
+ self.use_main_head = bool(getattr(opt, "clip_use_main_head", True))
177
+ if not self.use_main_head:
178
+ raise ValueError("clip_use_main_head must be True for this CLIP head.")
179
+
180
+ num_patches = getattr(opt, "clip_num_patches", None) if opt is not None else None
181
+ if not num_patches:
182
+ patch_size = getattr(self.model.visual, "patch_size", None)
183
+ crop_size = getattr(opt, "cropSize", None) if opt is not None else None
184
+ if patch_size and crop_size:
185
+ grid = int(crop_size) // int(patch_size)
186
+ num_patches = grid * grid
187
+ if not num_patches:
188
+ raise ValueError("clip_num_patches is required (or provide cropSize to infer it).")
189
+ self.num_patches = int(num_patches)
190
+
191
+ self.codebook_path = getattr(opt, "clip_codebook_path", None) if opt is not None else None
192
+ self.use_codebook_inject = bool(getattr(opt, "clip_use_codebook_inject", True)) if opt is not None else True
193
+ self.cb_detach_tokens = bool(getattr(opt, "clip_cb_detach_tokens", False)) if opt is not None else False
194
+
195
+ self.dim_c = int(getattr(opt, "clip_codebook_dim", 1280)) if opt is not None else 1280
196
+ self.num_concepts = int(getattr(opt, "clip_num_concepts", 200)) if opt is not None else 200
197
+
198
+ tau = float(getattr(opt, "clip_tau", 0.1)) if opt is not None else 0.1
199
+
200
+ l2_codebook = bool(getattr(opt, "clip_codebook_l2", True)) if opt is not None else True
201
+ freeze_codebook = bool(getattr(opt, "clip_freeze_codebook", True)) if opt is not None else True
202
+
203
+ self.codebook_head = None
204
+ if self.use_codebook_inject:
205
+ if not self.codebook_path:
206
+ raise ValueError("clip_use_codebook_inject=True but clip_codebook_path is None")
207
+
208
+ topk_m = int(getattr(opt, "clip_cb_topk", 20)) if opt is not None else 20
209
+ top_r = int(getattr(opt, "clip_cb_topr", 8)) if opt is not None else 8
210
+ tau_w = float(getattr(opt, "clip_cb_tau_w", 0.1)) if opt is not None else 0.1
211
+ weight_mode = getattr(opt, "clip_cb_weight_mode", "score") if opt is not None else "score"
212
+ mlp_hidden = getattr(opt, "clip_cb_mlp_hidden", None) if opt is not None else None
213
+
214
+ self.codebook_head = CodebookTopKHead(
215
+ dim_x=self.dim_x,
216
+ dim_c=self.dim_c,
217
+ num_concepts=self.num_concepts,
218
+ tau=tau,
219
+ tau_w=tau_w,
220
+ topk_m=topk_m,
221
+ top_r=top_r,
222
+ weight_mode=weight_mode,
223
+ l2_codebook=l2_codebook,
224
+ freeze_codebook=freeze_codebook,
225
+ mlp_hidden=mlp_hidden,
226
+ )
227
+
228
+ cb = _load_codebook(self.codebook_path)
229
+ if cb.shape[0] != self.num_concepts or cb.shape[1] != self.dim_c:
230
+ raise ValueError(
231
+ f"Loaded codebook shape {tuple(cb.shape)} != ({self.num_concepts},{self.dim_c})"
232
+ )
233
+ self.codebook_head.set_codebook(cb)
234
+
235
+ self.fc = nn.Linear(self.dim_x, num_classes)
236
+
237
+ def forward(self, x, return_feature=False, return_debug=False):
238
+ """
239
+ returns:
240
+ logits: [B,num_classes]
241
+ tokens: original patch tokens (CLS removed)
242
+ logits_cb: [B,1] (if enabled)
243
+ """
244
+ cls, tokens = self.model.encode_image_with_tokens(x)
245
+ tokens = tokens[:, 1:, :]
246
+ if tokens.shape[1] != self.num_patches:
247
+ raise ValueError(
248
+ f"num_patches mismatch: tokens has {tokens.shape[1]} patches, expected {self.num_patches}"
249
+ )
250
+
251
+ logits_cls = self.fc(cls)
252
+ if self.use_codebook_inject:
253
+ if self.codebook_head is None:
254
+ raise RuntimeError("Codebook head is not initialized.")
255
+ cb_tokens = tokens.detach() if self.cb_detach_tokens else tokens
256
+ logits_cb, score, idx, topk_concept = self.codebook_head(cb_tokens)
257
+ else:
258
+ logits_cb, score, idx, topk_concept = None, None, None, None
259
+
260
+ if return_feature:
261
+ return cls
262
+
263
+ logits = logits_cls
264
+
265
+ out = {
266
+ "logits": logits,
267
+ "cb_only": logits_cb,
268
+ "tokens": tokens,
269
+ }
270
+ if return_debug and score is not None:
271
+ out.update({
272
+ "codebook_score": score,
273
+ "codebook_topk_idx": idx,
274
+ "codebook_topk_concept": topk_concept,
275
+ })
276
+ return out
detectors/ForensicConcept/upstream/networks/__init__.py ADDED
File without changes
detectors/ForensicConcept/upstream/networks/base_model.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from pix2pix
2
+ import os
3
+ import torch
4
+ import torch.nn as nn
5
+ from models.clip import loratorch
6
+
7
+
8
+ def _parse_primary_gpu_id(gpu_ids):
9
+ if gpu_ids is None:
10
+ return -1
11
+ if isinstance(gpu_ids, (list, tuple)):
12
+ if not gpu_ids:
13
+ return -1
14
+ try:
15
+ return int(gpu_ids[0])
16
+ except (TypeError, ValueError):
17
+ return -1
18
+ if isinstance(gpu_ids, str):
19
+ parts = [part.strip() for part in gpu_ids.split(',') if part.strip()]
20
+ if not parts:
21
+ return -1
22
+ try:
23
+ return int(parts[0])
24
+ except ValueError:
25
+ return -1
26
+ try:
27
+ return int(gpu_ids)
28
+ except (TypeError, ValueError):
29
+ return -1
30
+
31
+
32
+ class BaseModel(nn.Module):
33
+ def __init__(self, opt):
34
+ super(BaseModel, self).__init__()
35
+ self.opt = opt
36
+ self.total_steps = 0
37
+ self.isTrain = opt.isTrain
38
+ self.lr = opt.lr
39
+ self.save_dir = os.path.join(opt.checkpoints_dir, opt.name)
40
+ self.resume_name = getattr(opt, "resume_name", None)
41
+ self.load_dir = os.path.join(opt.checkpoints_dir, self.resume_name or opt.name)
42
+ os.makedirs(self.save_dir, exist_ok=True)
43
+ self.rank = int(getattr(opt, "rank", 0) or 0)
44
+ self.is_main_process = self.rank == 0
45
+ local_rank = int(getattr(opt, "local_rank", -1) or -1)
46
+ if torch.cuda.is_available():
47
+ if local_rank >= 0:
48
+ self.device = torch.device(f"cuda:{local_rank}")
49
+ else:
50
+ gpu_id = _parse_primary_gpu_id(getattr(opt, "gpu_ids", None))
51
+ self.device = torch.device(f"cuda:{gpu_id}") if gpu_id >= 0 else torch.device("cpu")
52
+ else:
53
+ self.device = torch.device('cpu')
54
+
55
+ def _unwrap_model(self):
56
+ return self.model.module if hasattr(self.model, "module") else self.model
57
+
58
+ def save_networks(self, epoch):
59
+ if not self.is_main_process:
60
+ return
61
+ save_filename = 'model_epoch_%s.pth' % epoch
62
+ save_path = os.path.join(self.save_dir, save_filename)
63
+ model_ref = self._unwrap_model()
64
+
65
+ if getattr(self.opt, "trainmode", None) == "lora":
66
+ state_dict = {
67
+ 'backbone': getattr(model_ref, "model", None).state_dict() if getattr(self.opt, "save_backbone", False) else None,
68
+ 'lora': loratorch.lora_state_dict(model_ref),
69
+ 'optimizer': self.optimizer.state_dict(),
70
+ 'total_steps': self.total_steps,
71
+ }
72
+ if hasattr(model_ref, "fc"):
73
+ state_dict['fc'] = model_ref.fc.state_dict()
74
+ if getattr(model_ref, "codebook_head", None) is not None:
75
+ state_dict['codebook_head'] = model_ref.codebook_head.state_dict()
76
+ torch.save(state_dict, save_path)
77
+ print(f'Saving model {save_path}')
78
+ elif getattr(self.opt, "trainmode", None) == "dinov3" and getattr(model_ref, "using_lora", False):
79
+ state_dict = {
80
+ 'head': model_ref.head.state_dict(),
81
+ 'backbone_lora': model_ref.get_lora_state_dict(),
82
+ 'optimizer': self.optimizer.state_dict(),
83
+ 'total_steps': self.total_steps,
84
+ }
85
+ if getattr(model_ref, "concept_head", None) is not None:
86
+ state_dict['concept_head'] = model_ref.concept_head.state_dict()
87
+ if getattr(model_ref, "concept_mapping", None) is not None:
88
+ state_dict['concept_mapping'] = model_ref.concept_mapping.state_dict()
89
+ torch.save(state_dict, save_path)
90
+ print(f'Saving DINOv3 LoRA model {save_path}')
91
+ elif getattr(self.opt, "trainmode", None) == "dinov3" and getattr(model_ref, "freeze_backbone", False) and getattr(model_ref, "trainable_blocks", 0) == 0:
92
+ # Save only the trainable classifier parameters to keep checkpoints small.
93
+ model_state = model_ref.state_dict()
94
+ trainable_names = [name for name, param in model_ref.named_parameters() if param.requires_grad]
95
+ trainable_state = {name: model_state[name].detach().cpu().clone() for name in trainable_names}
96
+ checkpoint = {
97
+ 'trainable_state': trainable_state,
98
+ 'trainable_parameter_names': trainable_names,
99
+ 'optimizer': self.optimizer.state_dict() if hasattr(self, 'optimizer') else None,
100
+ 'total_steps': self.total_steps,
101
+ }
102
+ torch.save(checkpoint, save_path)
103
+ print(f'Saving DINOv3 trainable parameters {save_path}')
104
+ else:
105
+ torch.save(model_ref.state_dict(), save_path)
106
+ print(f'Saving model {save_path}')
107
+
108
+ # load models from the disk
109
+ def load_networks(self, epoch):
110
+ """Load model/optimizer state.
111
+
112
+ Accepts either an epoch tag (e.g., '0.80_0.83') or a full path to a
113
+ checkpoint file. This makes explicit checkpoint paths work even when the
114
+ directory name differs from `self.load_dir`.
115
+ """
116
+ if isinstance(epoch, (str, os.PathLike)) and os.path.isfile(str(epoch)):
117
+ load_path = str(epoch)
118
+ else:
119
+ load_filename = 'model_epoch_%s.pth' % epoch
120
+ load_path = os.path.join(self.load_dir, load_filename)
121
+
122
+ print('loading the model from %s' % load_path)
123
+ state_dict = torch.load(load_path, map_location=self.device)
124
+ model_ref = self._unwrap_model()
125
+ if hasattr(state_dict, '_metadata'):
126
+ del state_dict._metadata
127
+
128
+ if isinstance(state_dict, dict) and 'model' in state_dict:
129
+ model_ref.load_state_dict(state_dict['model'])
130
+ self.total_steps = state_dict.get('total_steps', 0)
131
+ if self.isTrain and not self.opt.new_optim and 'optimizer' in state_dict:
132
+ self.optimizer.load_state_dict(state_dict['optimizer'])
133
+ elif isinstance(state_dict, dict) and 'trainable_state' in state_dict:
134
+ current_state = model_ref.state_dict()
135
+ for name, tensor in state_dict['trainable_state'].items():
136
+ if name in current_state:
137
+ current_state[name] = tensor
138
+ else:
139
+ print(f"[Checkpoint] Warning: skipped unknown parameter '{name}'")
140
+ model_ref.load_state_dict(current_state)
141
+ self.total_steps = state_dict.get('total_steps', 0)
142
+ if self.isTrain and not self.opt.new_optim and state_dict.get('optimizer'):
143
+ self.optimizer.load_state_dict(state_dict['optimizer'])
144
+ elif getattr(self.opt, "trainmode", None) == "lora" and isinstance(state_dict, dict):
145
+ if 'fc' in state_dict and hasattr(model_ref, "fc"):
146
+ model_ref.fc.load_state_dict(state_dict['fc'])
147
+ if 'codebook_head' in state_dict and getattr(model_ref, "codebook_head", None) is not None:
148
+ if getattr(self.opt, "clip_override_codebook", False):
149
+ # Load head weights but keep the codebook buffer from config.
150
+ ckpt_state = state_dict['codebook_head']
151
+ current = model_ref.codebook_head.state_dict()
152
+ for k, v in ckpt_state.items():
153
+ if k != 'codebook':
154
+ current[k] = v
155
+ model_ref.codebook_head.load_state_dict(current, strict=False)
156
+ else:
157
+ model_ref.codebook_head.load_state_dict(state_dict['codebook_head'])
158
+ # LoRA state dict may be saved from the wrapper (keys start with 'model.')
159
+ # or directly from the CLIP backbone (no prefix). Route to the matching object.
160
+ lora_state = state_dict.get('lora', {})
161
+ if any(k.startswith("model.") for k in lora_state):
162
+ model_ref.load_state_dict(lora_state, strict=False)
163
+ else:
164
+ model_ref.model.load_state_dict(lora_state, strict=False)
165
+ backbone_state = state_dict.get('backbone')
166
+ if backbone_state:
167
+ # LoRA backbone state may omit frozen params; allow non-strict load.
168
+ model_ref.model.load_state_dict(backbone_state, strict=False)
169
+
170
+ # 确保 LoRA 层的 merged 标记被重置,避免某些检查点加载后 merged=True
171
+ # 导致推理/训练阶段跳过 LoRA 权重的合并。
172
+ def _reset_lora_merge_flag(module):
173
+ if getattr(module, "r", 0) > 0 and hasattr(module, "merged"):
174
+ module.merged = False
175
+ model_ref.apply(_reset_lora_merge_flag)
176
+
177
+ if not self.isTrain:
178
+ def _merge_once(module):
179
+ if getattr(module, "r", 0) > 0 and hasattr(module, "lora_train"):
180
+ try:
181
+ module.merged = False # force a fresh merge
182
+ module.lora_train(False)
183
+ except Exception:
184
+ pass
185
+ model_ref.apply(_merge_once)
186
+
187
+ self.total_steps = state_dict.get('total_steps', 0)
188
+ if self.isTrain and not self.opt.new_optim and 'optimizer' in state_dict:
189
+ self.optimizer.load_state_dict(state_dict['optimizer'])
190
+ elif getattr(self.opt, "trainmode", None) == "dinov3" and getattr(model_ref, "using_lora", False):
191
+ # Preferred LoRA checkpoint format (head + backbone_lora).
192
+ if isinstance(state_dict, dict) and 'head' in state_dict and 'backbone_lora' in state_dict:
193
+ model_ref.head.load_state_dict(state_dict['head'])
194
+ model_ref.load_lora_state_dict(state_dict['backbone_lora'])
195
+ if 'concept_head' in state_dict and getattr(model_ref, "concept_head", None) is not None:
196
+ model_ref.concept_head.load_state_dict(state_dict['concept_head'])
197
+ if 'concept_mapping' in state_dict and getattr(model_ref, "concept_mapping", None) is not None:
198
+ model_ref.concept_mapping.load_state_dict(state_dict['concept_mapping'])
199
+ self.total_steps = state_dict.get('total_steps', 0)
200
+ if self.isTrain and not self.opt.new_optim and 'optimizer' in state_dict:
201
+ self.optimizer.load_state_dict(state_dict['optimizer'])
202
+ else:
203
+ # Compatibility path: initialize LoRA run from a full-finetune/plain checkpoint.
204
+ loaded_any = False
205
+ if isinstance(state_dict, dict):
206
+ head_state = {
207
+ k[len("head."):]: v
208
+ for k, v in state_dict.items()
209
+ if isinstance(k, str) and k.startswith("head.")
210
+ }
211
+ if head_state:
212
+ missing, unexpected = model_ref.head.load_state_dict(head_state, strict=False)
213
+ print(
214
+ f"[Checkpoint] Loaded head from full checkpoint (missing={len(missing)}, "
215
+ f"unexpected={len(unexpected)})."
216
+ )
217
+ loaded_any = True
218
+
219
+ backbone_state = {
220
+ k[len("backbone."):]: v
221
+ for k, v in state_dict.items()
222
+ if isinstance(k, str) and k.startswith("backbone.")
223
+ }
224
+ if backbone_state:
225
+ target_backbone = model_ref.backbone
226
+ base_model = getattr(target_backbone, "base_model", None)
227
+ if base_model is not None and hasattr(base_model, "model"):
228
+ target_backbone = base_model.model
229
+ missing, unexpected = target_backbone.load_state_dict(backbone_state, strict=False)
230
+ print(
231
+ f"[Checkpoint] Loaded backbone base weights into LoRA model "
232
+ f"(missing={len(missing)}, unexpected={len(unexpected)})."
233
+ )
234
+ loaded_any = True
235
+
236
+ if 'concept_head' in state_dict and getattr(model_ref, "concept_head", None) is not None:
237
+ model_ref.concept_head.load_state_dict(state_dict['concept_head'], strict=False)
238
+ if 'concept_mapping' in state_dict and getattr(model_ref, "concept_mapping", None) is not None:
239
+ model_ref.concept_mapping.load_state_dict(state_dict['concept_mapping'], strict=False)
240
+
241
+ if not loaded_any:
242
+ # Last resort for any custom checkpoint format.
243
+ missing, unexpected = model_ref.load_state_dict(state_dict, strict=False)
244
+ print(
245
+ f"[Checkpoint] Fallback non-strict load for LoRA model "
246
+ f"(missing={len(missing)}, unexpected={len(unexpected)})."
247
+ )
248
+ self.total_steps = state_dict.get('total_steps', 0) if isinstance(state_dict, dict) else self.total_steps
249
+ if self.isTrain and not self.opt.new_optim and isinstance(state_dict, dict) and 'optimizer' in state_dict:
250
+ self.optimizer.load_state_dict(state_dict['optimizer'])
251
+ else:
252
+ model_ref.load_state_dict(state_dict)
253
+ self.total_steps = state_dict.get('total_steps', 0) if isinstance(state_dict, dict) else self.total_steps
254
+
255
+ if self.isTrain and not self.opt.new_optim and hasattr(self, 'optimizer'):
256
+ # move optimizer state to GPU
257
+ for state in self.optimizer.state.values():
258
+ for k, v in state.items():
259
+ if torch.is_tensor(v):
260
+ state[k] = v.to(self.device)
261
+
262
+ for g in self.optimizer.param_groups:
263
+ g['lr'] = self.opt.lr
264
+
265
+ def eval(self):
266
+ self.model.eval()
267
+
268
+ def train(self):
269
+ self.model.train()
270
+
271
+ def test(self):
272
+ with torch.no_grad():
273
+ self.forward()
detectors/ForensicConcept/upstream/networks/dinov3_detector.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import sys
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Dict, Iterable, List, Optional, Union
7
+
8
+ import re
9
+ from urllib.parse import urlparse
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ from safetensors.torch import load_file, safe_open
15
+
16
+ try:
17
+ from tqdm import tqdm # type: ignore
18
+ _TQDM_AVAILABLE = True
19
+ except ImportError: # pragma: no cover - fallback when tqdm missing
20
+ _TQDM_AVAILABLE = False
21
+
22
+ def tqdm(iterable=None, **kwargs): # type: ignore
23
+ return iterable if iterable is not None else range(kwargs.get("total", 0))
24
+
25
+ _DINOV3_REPOSITORY_URL = "https://github.com/facebookresearch/dinov3"
26
+
27
+
28
+ @dataclass
29
+ class Dinov3Config:
30
+ variant: str = "vitl16"
31
+ backend: str = "official" # official | legacy-compatible external source
32
+ repo_path: Optional[str] = None
33
+ weights_path: Optional[str] = None
34
+ freeze_backbone: bool = True
35
+ trainable_blocks: int = 0
36
+ max_blocks: Optional[int] = None
37
+ head_hidden_dim: Optional[int] = None
38
+ head_dropout: float = 0.1
39
+ use_lora: bool = False
40
+ lora_rank: int = 4
41
+ lora_alpha: int = 8
42
+ lora_dropout: float = 0.0
43
+ lora_bias: str = "none"
44
+ lora_target_modules: Optional[List[str]] = None
45
+ lora_target_last_n: Optional[int] = None
46
+ use_concept_head: bool = False
47
+ concept_matrix_path: Optional[str] = None
48
+ concept_mapping_trainable: bool = False
49
+ concept_mapping_bias: bool = False
50
+ concept_head_hidden_dim: Optional[int] = None
51
+ concept_head_dropout: Optional[float] = None
52
+ concept_sparsity_ratio: float = 0.0
53
+ concept_loss_weight: float = 1.0
54
+ concept_eval_sparsity: Optional[List[float]] = None
55
+ train_lora: bool = True
56
+ disable_rope_train_jitter: bool = False
57
+ gradient_checkpointing: bool = False
58
+
59
+
60
+ def _normalize_backend(backend: str) -> str:
61
+ value = str(backend or "").strip().lower()
62
+ if value in {"official", "legacy"}:
63
+ return value
64
+ raise ValueError(f"Unsupported DINOv3 backend: {backend}. Expected one of: official, legacy.")
65
+
66
+
67
+ def _candidate_dinov3_roots(config: Dinov3Config) -> List[Path]:
68
+ _normalize_backend(config.backend)
69
+ if not config.repo_path:
70
+ return []
71
+ return [Path(config.repo_path).expanduser().resolve()]
72
+
73
+
74
+ def _ensure_dinov3_importable(config: Dinov3Config) -> Optional[Path]:
75
+ for root in _candidate_dinov3_roots(config):
76
+ if not (root / "dinov3").is_dir():
77
+ continue
78
+ root_str = str(root)
79
+ if root_str in sys.path:
80
+ sys.path.remove(root_str)
81
+ sys.path.insert(0, root_str)
82
+ return root
83
+
84
+ try:
85
+ import dinov3 as dinov3_pkg # type: ignore
86
+
87
+ return Path(dinov3_pkg.__file__).resolve().parents[1]
88
+ except Exception as exc: # noqa: BLE001
89
+ configured = _candidate_dinov3_roots(config)
90
+ checked = "\n".join(f" - {p}" for p in configured) if configured else " - no repository path configured"
91
+ raise ImportError(
92
+ "Could not import the official DINOv3 package.\n"
93
+ f"Clone {_DINOV3_REPOSITORY_URL} and set training.dinov3_repo_path, "
94
+ "or install DINOv3 in the active Python environment.\n"
95
+ f"Checked:\n{checked}"
96
+ ) from exc
97
+
98
+
99
+ def _resolve_weights_path(path: Optional[str]) -> Optional[str]:
100
+ if not path:
101
+ return None
102
+ if os.path.isfile(path):
103
+ return path
104
+ if os.path.isdir(path):
105
+ direct_file = os.path.join(path, "model.safetensors")
106
+ if os.path.isfile(direct_file):
107
+ return direct_file
108
+ index_file = os.path.join(path, "model.safetensors.index.json")
109
+ if os.path.isfile(index_file):
110
+ return index_file
111
+ raise FileNotFoundError(f"Could not resolve DINOv3 weights from: {path}")
112
+
113
+
114
+ def _is_pth_like(path: str) -> bool:
115
+ lower = str(path).lower()
116
+ return lower.endswith(".pth") or lower.endswith(".pt")
117
+
118
+
119
+ def _is_url(path: str) -> bool:
120
+ try:
121
+ parsed = urlparse(str(path))
122
+ except Exception:
123
+ return False
124
+ return parsed.scheme in {"http", "https", "file"}
125
+
126
+
127
+ def _load_safetensors(path: str) -> Dict[str, torch.Tensor]:
128
+ if path.endswith(".index.json"):
129
+ with open(path, "r", encoding="utf-8") as f:
130
+ index = json.load(f)
131
+ directory = os.path.dirname(path)
132
+ state_dict: Dict[str, torch.Tensor] = {}
133
+ total_tensors = len(index["weight_map"])
134
+ unique_shards = sorted(set(index["weight_map"].values()))
135
+ progress = tqdm(total=total_tensors, desc="Loading DINOv3 weights", unit="tensor") if _TQDM_AVAILABLE else None
136
+ for shard_file in unique_shards:
137
+ shard_path = os.path.join(directory, shard_file)
138
+ with safe_open(shard_path, framework="pt") as f:
139
+ for key in f.keys():
140
+ state_dict[key] = f.get_tensor(key)
141
+ if progress is not None:
142
+ progress.update(1)
143
+ if progress is not None:
144
+ progress.close()
145
+ return state_dict
146
+ with safe_open(path, framework="pt") as f:
147
+ keys = list(f.keys())
148
+ if _TQDM_AVAILABLE:
149
+ progress = tqdm(keys, desc="Loading DINOv3 weights", unit="tensor")
150
+ state_dict = {key: f.get_tensor(key) for key in progress}
151
+ progress.close()
152
+ return state_dict
153
+ return {key: f.get_tensor(key) for key in keys}
154
+
155
+
156
+ def _dinov3_constructors(config: Dinov3Config):
157
+ source_root = _ensure_dinov3_importable(config)
158
+ from dinov3.hub import backbones
159
+
160
+ backend = _normalize_backend(config.backend)
161
+ if source_root is not None:
162
+ print(f"[DINOv3] backend={backend}, source={source_root}")
163
+
164
+ return {
165
+ "vits16": backbones.dinov3_vits16,
166
+ "vits16plus": backbones.dinov3_vits16plus,
167
+ "vitb16": backbones.dinov3_vitb16,
168
+ "vitl16": backbones.dinov3_vitl16,
169
+ "vith16plus": backbones.dinov3_vith16plus,
170
+ "vit7b16": backbones.dinov3_vit7b16,
171
+ "convnext_tiny": backbones.dinov3_convnext_tiny,
172
+ "convnext_small": backbones.dinov3_convnext_small,
173
+ "convnext_base": backbones.dinov3_convnext_base,
174
+ "convnext_large": backbones.dinov3_convnext_large,
175
+ }
176
+
177
+
178
+ def _sparse_shrink(
179
+ x: torch.Tensor, ratio: float, return_mask: bool = False
180
+ ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
181
+ if ratio <= 0.0:
182
+ if return_mask:
183
+ mask = torch.ones_like(x, dtype=torch.bool)
184
+ return x, mask
185
+ return x
186
+
187
+ width = x.shape[-1]
188
+ if width == 0:
189
+ if return_mask:
190
+ mask = torch.zeros_like(x, dtype=torch.bool)
191
+ return x, mask
192
+ return x
193
+
194
+ keep = int(width * (1 - ratio))
195
+ keep = max(1, min(width, keep))
196
+ if keep >= width:
197
+ if return_mask:
198
+ mask = torch.ones_like(x, dtype=torch.bool)
199
+ return x, mask
200
+ return x
201
+
202
+ # kthvalue returns the k-th smallest element, so convert to the keep-th largest
203
+ threshold_index = width - keep + 1
204
+ threshold, _ = x.abs().kthvalue(threshold_index, dim=-1, keepdim=True)
205
+ mask = x.abs() >= threshold
206
+ shrunk = x * mask
207
+ if return_mask:
208
+ return shrunk, mask
209
+ return shrunk
210
+
211
+
212
+ def _map_hf_to_dinov3(backbone: nn.Module, hf_state: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
213
+ mapped: Dict[str, torch.Tensor] = {}
214
+ if "embeddings.cls_token" in hf_state:
215
+ cls_token = hf_state["embeddings.cls_token"]
216
+ mapped["cls_token"] = cls_token if cls_token.ndim == 3 else cls_token.unsqueeze(1)
217
+ if "embeddings.mask_token" in hf_state:
218
+ mask_token = hf_state["embeddings.mask_token"]
219
+ if mask_token.ndim == 3:
220
+ mask_token = mask_token.squeeze(1)
221
+ mapped["mask_token"] = mask_token
222
+ if "embeddings.register_tokens" in hf_state and hasattr(backbone, "n_storage_tokens") and backbone.n_storage_tokens:
223
+ mapped["storage_tokens"] = hf_state["embeddings.register_tokens"]
224
+ if "embeddings.patch_embeddings.weight" in hf_state:
225
+ mapped["patch_embed.proj.weight"] = hf_state["embeddings.patch_embeddings.weight"]
226
+ if "embeddings.patch_embeddings.bias" in hf_state:
227
+ mapped["patch_embed.proj.bias"] = hf_state["embeddings.patch_embeddings.bias"]
228
+
229
+ n_blocks = getattr(backbone, "n_blocks", 0)
230
+ ref_tensor = next(iter(hf_state.values()))
231
+ blocks = getattr(backbone, "blocks", None)
232
+ progress = None
233
+ iterator: Iterable[int]
234
+ if _TQDM_AVAILABLE and n_blocks > 0:
235
+ progress = tqdm(range(n_blocks), desc="Mapping DINOv3 blocks", unit="block")
236
+ iterator = progress
237
+ else:
238
+ iterator = range(n_blocks)
239
+
240
+ for i in iterator:
241
+ prefix = f"layer.{i}."
242
+ block_prefix = f"blocks.{i}."
243
+ block = blocks[i] if blocks is not None else None
244
+ mapped[f"{block_prefix}norm1.weight"] = hf_state[f"{prefix}norm1.weight"]
245
+ mapped[f"{block_prefix}norm1.bias"] = hf_state[f"{prefix}norm1.bias"]
246
+ mapped[f"{block_prefix}norm2.weight"] = hf_state[f"{prefix}norm2.weight"]
247
+ mapped[f"{block_prefix}norm2.bias"] = hf_state[f"{prefix}norm2.bias"]
248
+
249
+ q_w = hf_state[f"{prefix}attention.q_proj.weight"]
250
+ k_w = hf_state[f"{prefix}attention.k_proj.weight"]
251
+ v_w = hf_state[f"{prefix}attention.v_proj.weight"]
252
+ mapped[f"{block_prefix}attn.qkv.weight"] = torch.cat([q_w, k_w, v_w], dim=0)
253
+
254
+ attn_qkv = getattr(block, "attn", None)
255
+ qkv_bias = getattr(attn_qkv, "qkv", None)
256
+ has_qkv_bias = bool(qkv_bias is not None and getattr(qkv_bias, "bias", None) is not None)
257
+ if has_qkv_bias:
258
+ dim = q_w.shape[0]
259
+ zeros = torch.zeros(dim, dtype=ref_tensor.dtype, device=ref_tensor.device)
260
+ q_b = hf_state.get(f"{prefix}attention.q_proj.bias", zeros)
261
+ k_b = hf_state.get(f"{prefix}attention.k_proj.bias", zeros)
262
+ v_b = hf_state.get(f"{prefix}attention.v_proj.bias", zeros)
263
+ mapped[f"{block_prefix}attn.qkv.bias"] = torch.cat([q_b, k_b, v_b], dim=0)
264
+
265
+ mapped[f"{block_prefix}attn.proj.weight"] = hf_state[f"{prefix}attention.o_proj.weight"]
266
+ mapped[f"{block_prefix}attn.proj.bias"] = hf_state[f"{prefix}attention.o_proj.bias"]
267
+
268
+ if hasattr(block, "mlp") and hasattr(block.mlp, "fc1"):
269
+ mapped[f"{block_prefix}mlp.fc1.weight"] = hf_state[f"{prefix}mlp.up_proj.weight"]
270
+ mapped[f"{block_prefix}mlp.fc1.bias"] = hf_state[f"{prefix}mlp.up_proj.bias"]
271
+ mapped[f"{block_prefix}mlp.fc2.weight"] = hf_state[f"{prefix}mlp.down_proj.weight"]
272
+ mapped[f"{block_prefix}mlp.fc2.bias"] = hf_state[f"{prefix}mlp.down_proj.bias"]
273
+ elif hasattr(block, "mlp") and all(hasattr(block.mlp, attr) for attr in ("w1", "w2", "w3")):
274
+ mapped[f"{block_prefix}mlp.w1.weight"] = hf_state[f"{prefix}mlp.gate_proj.weight"]
275
+ mapped[f"{block_prefix}mlp.w1.bias"] = hf_state[f"{prefix}mlp.gate_proj.bias"]
276
+ mapped[f"{block_prefix}mlp.w2.weight"] = hf_state[f"{prefix}mlp.up_proj.weight"]
277
+ mapped[f"{block_prefix}mlp.w2.bias"] = hf_state[f"{prefix}mlp.up_proj.bias"]
278
+ mapped[f"{block_prefix}mlp.w3.weight"] = hf_state[f"{prefix}mlp.down_proj.weight"]
279
+ mapped[f"{block_prefix}mlp.w3.bias"] = hf_state[f"{prefix}mlp.down_proj.bias"]
280
+ else:
281
+ raise RuntimeError(
282
+ f"Unsupported MLP structure for block {i}: {type(getattr(block, 'mlp', None))}"
283
+ )
284
+
285
+ if f"{prefix}layer_scale1.lambda1" in hf_state:
286
+ mapped[f"{block_prefix}ls1.gamma"] = hf_state[f"{prefix}layer_scale1.lambda1"]
287
+ if f"{prefix}layer_scale2.lambda1" in hf_state:
288
+ mapped[f"{block_prefix}ls2.gamma"] = hf_state[f"{prefix}layer_scale2.lambda1"]
289
+
290
+ if progress is not None:
291
+ progress.close()
292
+
293
+ if "norm.weight" in hf_state:
294
+ mapped["norm.weight"] = hf_state["norm.weight"]
295
+ if "norm.bias" in hf_state:
296
+ mapped["norm.bias"] = hf_state["norm.bias"]
297
+
298
+ return mapped
299
+
300
+
301
+ def _load_backbone(config: Dinov3Config) -> nn.Module:
302
+ constructors = _dinov3_constructors(config)
303
+ if config.variant not in constructors:
304
+ raise ValueError(f"Unsupported DINOv3 variant: {config.variant}")
305
+ constructor = constructors[config.variant]
306
+
307
+ raw_weights = config.weights_path
308
+ resolved_weights: Optional[str] = None
309
+ if raw_weights:
310
+ try:
311
+ resolved_weights = _resolve_weights_path(raw_weights)
312
+ except FileNotFoundError:
313
+ # Allow direct URL/file-like .pth path for official DINOv3 checkpoints.
314
+ if _is_url(raw_weights) and _is_pth_like(raw_weights):
315
+ resolved_weights = raw_weights
316
+ else:
317
+ raise
318
+
319
+ if resolved_weights and _is_pth_like(resolved_weights):
320
+ return constructor(pretrained=True, weights=resolved_weights)
321
+
322
+ backbone = constructor(pretrained=False)
323
+ if resolved_weights:
324
+ if not (
325
+ resolved_weights.endswith(".safetensors")
326
+ or resolved_weights.endswith(".index.json")
327
+ ):
328
+ raise RuntimeError(
329
+ f"Unsupported DINOv3 weight format: {resolved_weights}. "
330
+ "Expected .safetensors/.index.json or .pth/.pt."
331
+ )
332
+ hf_state = _load_safetensors(resolved_weights)
333
+ mapped_state = _map_hf_to_dinov3(backbone, hf_state)
334
+ missing, unexpected = backbone.load_state_dict(mapped_state, strict=False)
335
+ unexpected = [k for k in unexpected if not k.endswith("bias_mask")]
336
+ if unexpected:
337
+ raise RuntimeError(f"Unexpected keys when loading DINOv3 weights: {unexpected}")
338
+ if missing:
339
+ diff = [
340
+ m
341
+ for m in missing
342
+ if not (
343
+ m.startswith("rope_embed.")
344
+ or m.endswith("bias_mask")
345
+ or m.startswith("local_cls_norm.")
346
+ )
347
+ ]
348
+ if diff:
349
+ raise RuntimeError(f"Missing keys when loading DINOv3 weights: {diff}")
350
+ return backbone
351
+
352
+
353
+ class Dinov3Detector(nn.Module):
354
+ def __init__(self, config: Dinov3Config, num_classes: int = 1):
355
+ super().__init__()
356
+ self.config = config
357
+ self.backbone = _load_backbone(config)
358
+ self._truncate_backbone_blocks_if_needed()
359
+ self._disable_rope_train_jitter_if_needed()
360
+ self.patch_size = getattr(self.backbone, "patch_size", None)
361
+ embed_dim = getattr(self.backbone, "embed_dim", None)
362
+ if embed_dim is None:
363
+ raise ValueError("Backbone does not expose embed_dim")
364
+
365
+ hidden_dim = config.head_hidden_dim or embed_dim
366
+ layers = []
367
+ if hidden_dim != embed_dim:
368
+ layers.extend([
369
+ nn.LayerNorm(embed_dim),
370
+ nn.Linear(embed_dim, hidden_dim),
371
+ nn.GELU(),
372
+ nn.Dropout(config.head_dropout),
373
+ nn.Linear(hidden_dim, num_classes),
374
+ ])
375
+ else:
376
+ layers.extend([
377
+ nn.LayerNorm(embed_dim),
378
+ nn.Dropout(config.head_dropout),
379
+ nn.Linear(embed_dim, num_classes),
380
+ ])
381
+ self.head = nn.Sequential(*layers)
382
+
383
+ self.use_concept_head = bool(config.use_concept_head)
384
+ self.concept_mapping: Optional[nn.Linear] = None
385
+ self.concept_head: Optional[nn.Module] = None
386
+ if self.use_concept_head:
387
+ self._init_concept_modules(embed_dim, num_classes)
388
+
389
+ self.freeze_backbone = config.freeze_backbone
390
+ self.trainable_blocks = max(0, config.trainable_blocks)
391
+ self.using_lora = bool(config.use_lora and config.lora_rank > 0)
392
+ self.train_lora = bool(config.train_lora)
393
+ self.lora_target_modules: List[str] = []
394
+ if self.using_lora:
395
+ self._apply_lora_adapters()
396
+ self._configure_trainable_params()
397
+ self._enable_gradient_checkpointing_if_needed()
398
+
399
+ def _truncate_backbone_blocks_if_needed(self) -> None:
400
+ max_blocks = self.config.max_blocks
401
+ if max_blocks is None:
402
+ return
403
+
404
+ try:
405
+ max_blocks = int(max_blocks)
406
+ except (TypeError, ValueError) as exc:
407
+ raise ValueError(f"Invalid dinov3_max_blocks: {self.config.max_blocks}") from exc
408
+
409
+ if max_blocks <= 0:
410
+ raise ValueError(f"dinov3_max_blocks must be > 0, got {max_blocks}.")
411
+
412
+ blocks = getattr(self.backbone, "blocks", None)
413
+ if blocks is None:
414
+ print("[DINOv3] dinov3_max_blocks is set but backbone has no `blocks`; ignoring.")
415
+ return
416
+
417
+ total_blocks = len(blocks)
418
+ if total_blocks <= 0:
419
+ return
420
+ keep_blocks = min(max_blocks, total_blocks)
421
+
422
+ if keep_blocks < total_blocks:
423
+ self.backbone.blocks = nn.ModuleList(list(blocks)[:keep_blocks])
424
+ if hasattr(self.backbone, "n_blocks"):
425
+ self.backbone.n_blocks = keep_blocks
426
+ print(f"[DINOv3] Truncated transformer blocks: keeping first {keep_blocks}/{total_blocks}.")
427
+ else:
428
+ print(
429
+ f"[DINOv3] dinov3_max_blocks={max_blocks} >= total_blocks={total_blocks}; "
430
+ "using all blocks."
431
+ )
432
+
433
+ def _enable_gradient_checkpointing_if_needed(self) -> None:
434
+ if not bool(self.config.gradient_checkpointing):
435
+ return
436
+
437
+ def _try_enable(module) -> bool:
438
+ if module is None:
439
+ return False
440
+ for method_name in ("gradient_checkpointing_enable", "enable_gradient_checkpointing"):
441
+ method = getattr(module, method_name, None)
442
+ if callable(method):
443
+ method()
444
+ return True
445
+ setter = getattr(module, "set_gradient_checkpointing", None)
446
+ if callable(setter):
447
+ try:
448
+ setter(True)
449
+ return True
450
+ except TypeError:
451
+ return False
452
+ return False
453
+
454
+ enabled = _try_enable(self.backbone)
455
+ if not enabled:
456
+ enabled = _try_enable(getattr(self.backbone, "base_model", None))
457
+ if enabled:
458
+ print("[FullFinetune] DINOv3 gradient checkpointing enabled.")
459
+ else:
460
+ print("[FullFinetune] gradient_checkpointing requested, but backbone API does not expose it.")
461
+
462
+ def _disable_rope_train_jitter_if_needed(self) -> None:
463
+ if not bool(getattr(self.config, "disable_rope_train_jitter", False)):
464
+ return
465
+ rope = getattr(self.backbone, "rope_embed", None)
466
+ if rope is None:
467
+ return
468
+ changed = []
469
+ for attr in ("shift_coords", "jitter_coords", "rescale_coords"):
470
+ if getattr(rope, attr, None) is not None:
471
+ setattr(rope, attr, None)
472
+ changed.append(attr)
473
+ if changed:
474
+ print(f"[DINOv3] Disabled RoPE train-time coordinate jitter: {', '.join(changed)}.")
475
+
476
+ def _init_concept_modules(self, embed_dim: int, num_classes: int) -> None:
477
+ if not self.config.concept_matrix_path:
478
+ raise ValueError("use_concept_head is True but concept_matrix_path is not provided.")
479
+
480
+ matrix_path = Path(self.config.concept_matrix_path)
481
+ if not matrix_path.is_file():
482
+ raise FileNotFoundError(f"Concept matrix file not found: {matrix_path}")
483
+
484
+ concept_array = np.load(str(matrix_path), allow_pickle=False)
485
+ if concept_array.ndim != 2:
486
+ raise ValueError(
487
+ f"Concept matrix must be 2D, got shape {concept_array.shape} from {matrix_path}."
488
+ )
489
+
490
+ concept_array = concept_array.astype(np.float32, copy=False)
491
+ concept_tensor = torch.from_numpy(concept_array)
492
+ concept_dim, concept_embed_dim = concept_tensor.shape
493
+
494
+ import logging
495
+ logger = logging.getLogger(__name__)
496
+ logger.info(
497
+ f"Loaded concept matrix of shape {concept_tensor.shape} "
498
+ f"(concept_dim={concept_dim}, embed_dim={concept_embed_dim}) from {matrix_path}"
499
+ )
500
+
501
+ if concept_embed_dim != embed_dim:
502
+ raise ValueError(
503
+ "Concept matrix embedding dimension does not match backbone output: "
504
+ f"expected {embed_dim}, got {concept_embed_dim}."
505
+ )
506
+
507
+ concept_mapping = nn.Linear(
508
+ embed_dim,
509
+ concept_dim,
510
+ bias=bool(self.config.concept_mapping_bias),
511
+ )
512
+ with torch.no_grad():
513
+ concept_mapping.weight.copy_(concept_tensor)
514
+ if concept_mapping.bias is not None:
515
+ concept_mapping.bias.zero_()
516
+
517
+ if not self.config.concept_mapping_trainable:
518
+ concept_mapping.weight.requires_grad = False
519
+ if concept_mapping.bias is not None:
520
+ concept_mapping.bias.requires_grad = False
521
+
522
+ concept_hidden_dim = self.config.concept_head_hidden_dim or concept_dim
523
+ concept_dropout = (
524
+ self.config.concept_head_dropout
525
+ if self.config.concept_head_dropout is not None
526
+ else self.config.head_dropout
527
+ )
528
+
529
+ head_layers: List[nn.Module] = []
530
+ if concept_hidden_dim != concept_dim:
531
+ head_layers.extend([
532
+ nn.LayerNorm(concept_dim),
533
+ nn.Linear(concept_dim, concept_hidden_dim),
534
+ nn.GELU(),
535
+ nn.Dropout(concept_dropout),
536
+ nn.Linear(concept_hidden_dim, num_classes),
537
+ ])
538
+ else:
539
+ head_layers.extend([
540
+ nn.LayerNorm(concept_dim),
541
+ nn.Dropout(concept_dropout),
542
+ nn.Linear(concept_dim, num_classes),
543
+ ])
544
+
545
+ self.concept_mapping = concept_mapping
546
+ self.concept_head = nn.Sequential(*head_layers)
547
+
548
+ def _apply_lora_adapters(self) -> None:
549
+ try:
550
+ from peft import LoraConfig, TaskType, get_peft_model
551
+ except ImportError as exc:
552
+ try:
553
+ from importlib.metadata import version as pkg_version
554
+
555
+ peft_ver = pkg_version("peft")
556
+ except Exception:
557
+ peft_ver = "not-installed"
558
+ try:
559
+ from importlib.metadata import version as pkg_version
560
+
561
+ transformers_ver = pkg_version("transformers")
562
+ except Exception:
563
+ transformers_ver = "not-installed"
564
+ raise ImportError(
565
+ "LoRA dependency import failed. This is usually a peft/transformers version mismatch. "
566
+ f"Current versions: peft={peft_ver}, transformers={transformers_ver}. "
567
+ "Reinstall the compatible ranges from requirements.txt: "
568
+ "`python3 -m pip install -U \"transformers>=4.56,<5\" \"peft>=0.17,<0.19\"`."
569
+ ) from exc
570
+
571
+ target_modules = self.config.lora_target_modules
572
+ if not target_modules:
573
+ target_modules = self._collect_linear_module_names()
574
+ if not target_modules:
575
+ raise RuntimeError("Could not find any linear modules in DINOv3 backbone for LoRA.")
576
+
577
+ lora_config = LoraConfig(
578
+ r=self.config.lora_rank,
579
+ lora_alpha=self.config.lora_alpha,
580
+ lora_dropout=self.config.lora_dropout,
581
+ bias=self.config.lora_bias,
582
+ target_modules=target_modules,
583
+ task_type=TaskType.FEATURE_EXTRACTION,
584
+ )
585
+
586
+ self.backbone = get_peft_model(self.backbone, lora_config)
587
+ self.lora_target_modules = target_modules
588
+
589
+ def _collect_linear_module_names(self) -> List[str]:
590
+ names: List[str] = []
591
+ last_n = self.config.lora_target_last_n
592
+ total_blocks = getattr(self.backbone, "n_blocks", None)
593
+ min_block_index = None
594
+ if last_n and total_blocks:
595
+ min_block_index = max(0, total_blocks - last_n)
596
+
597
+ for name, module in self.backbone.named_modules():
598
+ if isinstance(module, nn.Linear) and name:
599
+ if min_block_index is not None:
600
+ if "blocks." in name:
601
+ match = re.search(r"blocks\.(\d+)", name)
602
+ if match and int(match.group(1)) < min_block_index:
603
+ continue
604
+ else:
605
+ # Skip non-block modules when restricting to last N blocks
606
+ continue
607
+ names.append(name)
608
+ # Deduplicate while preserving order
609
+ seen = set()
610
+ ordered: List[str] = []
611
+ for name in names:
612
+ if name not in seen:
613
+ ordered.append(name)
614
+ seen.add(name)
615
+ return ordered
616
+
617
+ def _configure_trainable_params(self):
618
+ lora_trainable = self.train_lora if self.using_lora else False
619
+ if self.freeze_backbone:
620
+ for name, param in self.backbone.named_parameters():
621
+ if self.using_lora and "lora_" in name:
622
+ param.requires_grad = lora_trainable
623
+ else:
624
+ param.requires_grad = False
625
+ if self.trainable_blocks > 0 and hasattr(self.backbone, "blocks"):
626
+ for block in self.backbone.blocks[-self.trainable_blocks:]:
627
+ for name, param in block.named_parameters():
628
+ if self.using_lora and "lora_" in name:
629
+ param.requires_grad = lora_trainable
630
+ elif not self.using_lora:
631
+ param.requires_grad = True
632
+ if hasattr(self.backbone, "norm"):
633
+ for name, param in self.backbone.norm.named_parameters():
634
+ if self.using_lora and "lora_" in name:
635
+ param.requires_grad = lora_trainable
636
+ elif not self.using_lora:
637
+ param.requires_grad = True
638
+ else:
639
+ for name, param in self.backbone.named_parameters():
640
+ if self.using_lora and "lora_" in name and not lora_trainable:
641
+ param.requires_grad = False
642
+ else:
643
+ param.requires_grad = True
644
+
645
+ def forward(self, x: torch.Tensor) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
646
+ # Use __call__/forward path first so FSDP hooks are triggered.
647
+ # Calling forward_features() directly can bypass composable-FSDP hooks.
648
+ features_dict = None
649
+ try:
650
+ # Use inference-style forward path for stability in supervised fine-tuning.
651
+ features_dict = self.backbone(x, is_training=False)
652
+ except TypeError:
653
+ # Fallback for backbones that do not expose is_training.
654
+ features_dict = self.backbone.forward_features(x)
655
+ if not isinstance(features_dict, dict) or "x_norm_clstoken" not in features_dict:
656
+ # Final fallback in case wrapper returns unexpected type.
657
+ features_dict = self.backbone.forward_features(x)
658
+ features = features_dict["x_norm_clstoken"]
659
+ logits = self.head(features)
660
+ if self.concept_mapping is None or self.concept_head is None:
661
+ return logits
662
+
663
+ concept_features_raw = self.concept_mapping(features)
664
+ concept_features = concept_features_raw
665
+ if self.config.concept_sparsity_ratio > 0.0:
666
+ concept_features = _sparse_shrink(concept_features, self.config.concept_sparsity_ratio)
667
+ concept_logits = self.concept_head(concept_features)
668
+ return {
669
+ "logits": logits,
670
+ "concept_logits": concept_logits,
671
+ "concept_features": concept_features,
672
+ "concept_features_raw": concept_features_raw,
673
+ }
674
+
675
+ def compute_concept_logits_with_ratio(
676
+ self,
677
+ concept_features_raw: torch.Tensor,
678
+ sparsity_ratio: float,
679
+ *,
680
+ return_mask: bool = False,
681
+ ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
682
+ if self.concept_head is None:
683
+ raise RuntimeError("Concept head not initialized.")
684
+ concept_features = concept_features_raw
685
+ if return_mask:
686
+ concept_features, mask = _sparse_shrink(concept_features, sparsity_ratio, return_mask=True)
687
+ else:
688
+ concept_features = _sparse_shrink(concept_features, sparsity_ratio)
689
+ mask = None
690
+ logits = self.concept_head(concept_features)
691
+ if return_mask:
692
+ return logits, mask
693
+ return logits
694
+
695
+ def train(self, mode: bool = True):
696
+ super().train(mode)
697
+ if self.freeze_backbone:
698
+ if self.using_lora:
699
+ self.backbone.train(mode)
700
+ base_model = getattr(self.backbone, "base_model", None)
701
+ if base_model is not None:
702
+ base_model.eval()
703
+ else:
704
+ self.backbone.eval()
705
+ return self
706
+
707
+ def get_trainable_parameters(self) -> Iterable[nn.Parameter]:
708
+ return (p for p in self.parameters() if p.requires_grad)
709
+
710
+ def get_lora_state_dict(self) -> Optional[Dict[str, torch.Tensor]]:
711
+ if not self.using_lora:
712
+ return None
713
+ from peft import get_peft_model_state_dict
714
+
715
+ return get_peft_model_state_dict(self.backbone)
716
+
717
+ def load_lora_state_dict(self, state_dict: Dict[str, torch.Tensor]) -> None:
718
+ if not self.using_lora:
719
+ raise RuntimeError("Attempting to load LoRA state dict while LoRA is disabled.")
720
+ from peft import get_peft_model_state_dict, set_peft_model_state_dict
721
+
722
+ set_peft_model_state_dict(self.backbone, state_dict, adapter_name="default")
723
+
724
+ # PEFT loads adapter weights non-strictly because the frozen backbone is
725
+ # intentionally absent. Re-export the adapter to make mismatches fatal.
726
+ loaded_state = get_peft_model_state_dict(self.backbone, adapter_name="default")
727
+ expected_keys = set(state_dict)
728
+ loaded_keys = set(loaded_state)
729
+ missing = sorted(expected_keys - loaded_keys)
730
+ unexpected = sorted(loaded_keys - expected_keys)
731
+ if missing or unexpected:
732
+ raise RuntimeError(
733
+ "LoRA checkpoint key mismatch after loading: "
734
+ f"missing={missing[:5]}, unexpected={unexpected[:5]}"
735
+ )
736
+
737
+ mismatched = []
738
+ for name in sorted(expected_keys):
739
+ expected = state_dict[name].detach()
740
+ actual = loaded_state[name].detach()
741
+ if expected.shape != actual.shape or not torch.equal(expected.cpu(), actual.cpu()):
742
+ mismatched.append(name)
743
+ if mismatched:
744
+ raise RuntimeError(
745
+ "LoRA checkpoint tensor mismatch after loading: "
746
+ f"{mismatched[:5]} (total={len(mismatched)})"
747
+ )
748
+ print(f"[Checkpoint] Strictly verified {len(expected_keys)} LoRA tensors.")
749
+
750
+ def supports_resolution(self, size: int) -> bool:
751
+ if self.patch_size is None:
752
+ return True
753
+ return size % self.patch_size == 0
detectors/ForensicConcept/upstream/networks/trainer.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from networks.base_model import BaseModel
6
+ from networks.dinov3_detector import Dinov3Config, Dinov3Detector
7
+ from models import get_model
8
+
9
+
10
+ CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073]
11
+ CLIP_STD = [0.26862954, 0.26130258, 0.27577711]
12
+ IMAGENET_MEAN = [0.485, 0.456, 0.406]
13
+ IMAGENET_STD = [0.229, 0.224, 0.225]
14
+
15
+
16
+ class Trainer(BaseModel):
17
+ def name(self):
18
+ return 'Trainer'
19
+
20
+ def __init__(self, opt):
21
+ super(Trainer, self).__init__(opt)
22
+ self.num_classes = getattr(opt, "num_classes", 1)
23
+ self._deepspeed_engine = None
24
+ self.augmix_js_loss = None
25
+ self._best_loss = float("inf")
26
+ self._loss_plateau_counter = 0
27
+ self.full_finetune_enable = bool(getattr(opt, "full_finetune_enable", False))
28
+ self.model = self._build_model(opt)
29
+
30
+ if opt.trainmode == "lora" and opt.modelname.startswith("CLIP:"):
31
+ if self.isTrain and not opt.continue_train:
32
+ torch.nn.init.normal_(self.model.fc.weight.data, 0.0, opt.init_gain)
33
+ self._configure_clip_trainable(opt)
34
+
35
+ if self.isTrain:
36
+ pos_weight = getattr(opt, "pos_weight", None)
37
+ if self.num_classes == 1:
38
+ if pos_weight is not None:
39
+ pos_tensor = torch.tensor(float(pos_weight), device=self.device)
40
+ self.loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_tensor)
41
+ else:
42
+ self.loss_fn = nn.BCEWithLogitsLoss()
43
+ elif self.num_classes == 2:
44
+ self.loss_fn = nn.CrossEntropyLoss()
45
+ # initialize optimizers
46
+ self.optimizer = self._build_optimizer()
47
+ self._init_full_finetune_plugin()
48
+ self.optimizer.zero_grad(set_to_none=True)
49
+
50
+ self._init_augmix_js_branch()
51
+
52
+ if not self.isTrain or opt.continue_train:
53
+ self.load_networks(opt.epoch)
54
+ self.model.to(self.device)
55
+
56
+ def _build_model(self, opt):
57
+ if opt.trainmode == "dinov3":
58
+ model = Dinov3Detector(self._build_dinov3_config(opt), num_classes=self.num_classes)
59
+ self.model = model
60
+ self._ensure_valid_resolution(opt)
61
+ return model
62
+ if opt.trainmode == "lora" and str(getattr(opt, "modelname", "")).startswith("CLIP:"):
63
+ return get_model(opt.modelname, opt)
64
+ raise ValueError(
65
+ f"Unsupported trainmode={opt.trainmode!r}. "
66
+ "This release supports 'dinov3' and CLIP 'lora' only."
67
+ )
68
+
69
+ def _configure_clip_trainable(self, opt):
70
+ train_lora = bool(getattr(opt, "clip_train_lora", True))
71
+ train_heads = bool(getattr(opt, "clip_train_fc", True))
72
+ for name, param in self.model.named_parameters():
73
+ is_visual_qkv_lora = (
74
+ train_lora and "lora_" in name and "visual" in name and "qkv" in name
75
+ )
76
+ is_head = train_heads and (
77
+ name.startswith("fc.") or name.startswith("codebook_head.")
78
+ )
79
+ param.requires_grad = is_visual_qkv_lora or is_head
80
+
81
+ def _build_dinov3_config(self, opt):
82
+ freeze_backbone = bool(getattr(opt, "freeze_backbone", True))
83
+ trainable_blocks = int(getattr(opt, "trainable_blocks", 0) or 0)
84
+ use_lora = bool(getattr(opt, "use_lora", False))
85
+ gradient_checkpointing = bool(getattr(opt, "full_finetune_gradient_checkpointing", False))
86
+
87
+ if self.full_finetune_enable:
88
+ if freeze_backbone or use_lora or trainable_blocks != 0:
89
+ print(
90
+ "[FullFinetune] Enforcing DINOv3 full fine-tune: "
91
+ "freeze_backbone=false, use_lora=false, trainable_blocks=0."
92
+ )
93
+ freeze_backbone = False
94
+ use_lora = False
95
+ trainable_blocks = 0
96
+ else:
97
+ gradient_checkpointing = False
98
+
99
+ return Dinov3Config(
100
+ variant=getattr(opt, "dinov3_variant", "vitl16"),
101
+ backend=getattr(opt, "dinov3_backend", "official"),
102
+ repo_path=getattr(opt, "dinov3_repo_path", None),
103
+ weights_path=getattr(opt, "dinov3_weights", None),
104
+ freeze_backbone=freeze_backbone,
105
+ trainable_blocks=trainable_blocks,
106
+ max_blocks=getattr(opt, "dinov3_max_blocks", None),
107
+ head_hidden_dim=getattr(opt, "head_hidden_dim", None),
108
+ head_dropout=getattr(opt, "head_dropout", 0.1),
109
+ use_lora=use_lora,
110
+ lora_rank=getattr(opt, "lora_rank", 4),
111
+ lora_alpha=getattr(opt, "lora_alpha", 8),
112
+ lora_dropout=getattr(opt, "lora_dropout", 0.0),
113
+ lora_bias=getattr(opt, "lora_bias", "none"),
114
+ lora_target_modules=getattr(opt, "lora_target_modules", None),
115
+ lora_target_last_n=getattr(opt, "lora_target_last_n", None),
116
+ use_concept_head=getattr(opt, "dinov3_use_concept_head", False),
117
+ concept_matrix_path=getattr(opt, "dinov3_concept_matrix_path", None),
118
+ concept_mapping_trainable=getattr(opt, "dinov3_concept_mapping_trainable", False),
119
+ concept_mapping_bias=getattr(opt, "dinov3_concept_mapping_bias", False),
120
+ concept_head_hidden_dim=getattr(opt, "dinov3_concept_head_hidden_dim", None),
121
+ concept_head_dropout=getattr(opt, "dinov3_concept_head_dropout", None),
122
+ concept_sparsity_ratio=getattr(opt, "dinov3_concept_sparsity_ratio", 0.0),
123
+ concept_loss_weight=getattr(opt, "dinov3_concept_loss_weight", 1.0),
124
+ concept_eval_sparsity=getattr(opt, "dinov3_concept_eval_sparsity", None),
125
+ disable_rope_train_jitter=getattr(opt, "dinov3_disable_rope_train_jitter", False),
126
+ gradient_checkpointing=gradient_checkpointing,
127
+ )
128
+
129
+ def _ensure_valid_resolution(self, opt):
130
+ if not hasattr(self.model, "supports_resolution"):
131
+ return
132
+ patch_size = getattr(self.model, "patch_size", 1)
133
+ window_size = getattr(self.model, "window_size", None)
134
+ if isinstance(window_size, (list, tuple)):
135
+ window_size = window_size[0] if window_size else None
136
+ if isinstance(window_size, int) and window_size > 0:
137
+ step = patch_size * window_size
138
+ else:
139
+ step = patch_size
140
+ for attr in ("loadSize", "cropSize"):
141
+ size = getattr(opt, attr, None)
142
+ if size is None:
143
+ continue
144
+ if not self.model.supports_resolution(size):
145
+ adjusted = max(step, (size // step) * step)
146
+ if adjusted != size:
147
+ print(
148
+ f"[Resolution] Adjusting {attr} from {size} to {adjusted} to align with step {step}."
149
+ )
150
+ setattr(opt, attr, adjusted)
151
+ if getattr(opt, "loadSize", None) and getattr(opt, "cropSize", None):
152
+ if opt.cropSize > opt.loadSize:
153
+ print(f"[Resolution] Adjusting cropSize from {opt.cropSize} to match loadSize {opt.loadSize}.")
154
+ opt.cropSize = opt.loadSize
155
+
156
+ def _init_full_finetune_plugin(self):
157
+ precision = str(getattr(self.opt, "full_finetune_precision", "fp32") or "fp32").lower()
158
+ if precision not in {"fp32", "fp16", "bf16"}:
159
+ precision = "fp32"
160
+ self.full_finetune_precision = precision
161
+ grad_accum_raw = getattr(self.opt, "full_finetune_grad_accum_steps", 1)
162
+ try:
163
+ self.grad_accum_steps = max(1, int(grad_accum_raw))
164
+ except (TypeError, ValueError):
165
+ self.grad_accum_steps = 1
166
+ self.max_grad_norm = float(getattr(self.opt, "max_grad_norm", 0.0) or 0.0)
167
+ self._grad_accum_counter = 0
168
+
169
+ self.use_amp = (
170
+ self.full_finetune_enable
171
+ and precision in {"fp16", "bf16"}
172
+ and self.device.type == "cuda"
173
+ )
174
+ if self.use_amp:
175
+ self.amp_dtype = torch.float16 if precision == "fp16" else torch.bfloat16
176
+ self.scaler = torch.cuda.amp.GradScaler(enabled=(self.amp_dtype == torch.float16))
177
+ else:
178
+ self.amp_dtype = torch.float32
179
+ self.scaler = None
180
+
181
+ if self.is_main_process and self.full_finetune_enable:
182
+ print(
183
+ f"[FullFinetune] enabled precision={self.full_finetune_precision} "
184
+ f"grad_accum_steps={self.grad_accum_steps} max_grad_norm={self.max_grad_norm}"
185
+ )
186
+
187
+ def _build_optimizer(self):
188
+ if self.opt.optim == 'adam':
189
+ return torch.optim.Adam(
190
+ filter(lambda p: p.requires_grad, self.model.parameters()),
191
+ lr=self.opt.lr,
192
+ betas=(self.opt.beta1, 0.999),
193
+ weight_decay=float(getattr(self.opt, "weight_decay", 0.0) or 0.0),
194
+ )
195
+ if self.opt.optim == 'adamw':
196
+ return torch.optim.AdamW(
197
+ filter(lambda p: p.requires_grad, self.model.parameters()),
198
+ lr=self.opt.lr,
199
+ betas=(self.opt.beta1, 0.999),
200
+ weight_decay=float(getattr(self.opt, "weight_decay", 0.0) or 0.0),
201
+ )
202
+ if self.opt.optim == 'sgd':
203
+ return torch.optim.SGD(
204
+ filter(lambda p: p.requires_grad, self.model.parameters()),
205
+ lr=self.opt.lr,
206
+ momentum=0.0,
207
+ weight_decay=float(getattr(self.opt, "weight_decay", 0.0) or 0.0),
208
+ )
209
+ raise ValueError("optim should be [adam, adamw, sgd]")
210
+
211
+ def reset_optimizer_for_wrapped_model(self):
212
+ """Rebuild optimizer after external wrappers (e.g., official FSDP plugin) change model params."""
213
+ if not self.isTrain:
214
+ return
215
+ self.optimizer = self._build_optimizer()
216
+ self.optimizer.zero_grad(set_to_none=True)
217
+ if self.is_main_process:
218
+ print("[Optimizer] Rebuilt optimizer for wrapped model.")
219
+
220
+ def _autocast_context(self):
221
+ if not self.use_amp:
222
+ return contextlib.nullcontext()
223
+ return torch.autocast(device_type="cuda", dtype=self.amp_dtype)
224
+
225
+ def _optimizer_step_impl(self):
226
+ if self.max_grad_norm > 0.0:
227
+ if self.scaler is not None and self.scaler.is_enabled():
228
+ self.scaler.unscale_(self.optimizer)
229
+ trainable_params = [
230
+ p for p in self.model.parameters()
231
+ if p.requires_grad and p.grad is not None
232
+ ]
233
+ if trainable_params:
234
+ torch.nn.utils.clip_grad_norm_(trainable_params, self.max_grad_norm)
235
+
236
+ if self.scaler is not None and self.scaler.is_enabled():
237
+ self.scaler.step(self.optimizer)
238
+ self.scaler.update()
239
+ else:
240
+ self.optimizer.step()
241
+ self.optimizer.zero_grad(set_to_none=True)
242
+
243
+ def adjust_learning_rate(self):
244
+ decay_factor = getattr(self.opt, "lr_decay_factor", 0.9)
245
+ min_lr = getattr(self.opt, "lr_min", 1e-6)
246
+ if decay_factor <= 0 or decay_factor >= 1:
247
+ print(f"[LR] Invalid decay factor {decay_factor}, falling back to 0.9")
248
+ decay_factor = 0.9
249
+
250
+ reached_min = False
251
+ prev_lr = None
252
+ for param_group in self.optimizer.param_groups:
253
+ prev_lr = param_group['lr']
254
+ new_lr = prev_lr * decay_factor
255
+ if new_lr <= min_lr:
256
+ new_lr = min_lr
257
+ reached_min = True
258
+ param_group['lr'] = new_lr
259
+
260
+ if prev_lr is None:
261
+ return False
262
+
263
+ self.lr = self.optimizer.param_groups[0]['lr']
264
+ print('*' * 25)
265
+ print(f'Changing lr from {prev_lr} to {self.lr}')
266
+ if reached_min:
267
+ print(f'[LR] Minimum lr {min_lr} reached; further decay will be skipped')
268
+ print('*' * 25)
269
+ return not reached_min
270
+
271
+ def should_adjust_lr_on_plateau(self, loss_value: float) -> bool:
272
+ patience_raw = getattr(self.opt, "lr_plateau_patience", 0)
273
+ try:
274
+ patience = int(patience_raw)
275
+ except (TypeError, ValueError):
276
+ patience = 0
277
+ if patience <= 0:
278
+ return False
279
+
280
+ warmup_raw = getattr(self.opt, "lr_plateau_warmup", 0)
281
+ delta_raw = getattr(self.opt, "lr_plateau_delta", 0.0)
282
+ try:
283
+ warmup = int(warmup_raw)
284
+ except (TypeError, ValueError):
285
+ warmup = 0
286
+ try:
287
+ delta = float(delta_raw)
288
+ except (TypeError, ValueError):
289
+ delta = 0.0
290
+ if self.total_steps < warmup:
291
+ return False
292
+
293
+ if loss_value + delta < self._best_loss:
294
+ self._best_loss = loss_value
295
+ self._loss_plateau_counter = 0
296
+ return False
297
+
298
+ self._loss_plateau_counter += 1
299
+ if self._loss_plateau_counter >= patience:
300
+ self._loss_plateau_counter = 0
301
+ self._best_loss = loss_value
302
+ return True
303
+ return False
304
+
305
+ def set_input(self, input):
306
+ self.input = input[0].to(self.device)
307
+ self.label = input[1].to(self.device)
308
+ if self.num_classes == 1:
309
+ self.label = self.label.float()
310
+
311
+
312
+ def forward(self):
313
+ self.output = self.model(self.input)
314
+
315
+
316
+ def get_loss(self):
317
+ def _compute_loss(logits: torch.Tensor) -> torch.Tensor:
318
+ if self.num_classes == 1 and logits.dim() > 1:
319
+ logits = logits.squeeze(1)
320
+ return self.loss_fn(logits, self.label)
321
+
322
+ output = self.output
323
+ if isinstance(output, dict):
324
+ main_logits = output.get("logits")
325
+ concept_logits = output.get("concept_logits")
326
+ cb_logits = output.get("cb_only")
327
+ main_loss = _compute_loss(main_logits) if main_logits is not None else None
328
+ concept_loss = _compute_loss(concept_logits) if concept_logits is not None else None
329
+ cb_loss = _compute_loss(cb_logits) if cb_logits is not None else None
330
+ if main_loss is None and concept_loss is None and cb_loss is None:
331
+ raise RuntimeError("Model output dict has no logits to compute loss.")
332
+ total_loss = main_loss
333
+ if concept_loss is not None:
334
+ weight = getattr(self.opt, "dinov3_concept_loss_weight", 1.0)
335
+ total_loss = weight * concept_loss if total_loss is None else total_loss + weight * concept_loss
336
+ if cb_loss is not None:
337
+ cb_weight = float(getattr(self.opt, "clip_cb_loss_weight", 1.0))
338
+ total_loss = cb_weight * cb_loss if total_loss is None else total_loss + cb_weight * cb_loss
339
+
340
+ return total_loss
341
+ if isinstance(output, tuple):
342
+ return _compute_loss(output[0])
343
+ return _compute_loss(output)
344
+
345
+ def _init_augmix_js_branch(self):
346
+ self.augmix_js_enable = bool(getattr(self.opt, "augmix_js_enable", False)) and bool(self.isTrain)
347
+ self.augmix_js_weight = float(getattr(self.opt, "augmix_js_weight", 12.0) or 12.0)
348
+ self.augmix_width = int(getattr(self.opt, "augmix_width", 3) or 3)
349
+ self.augmix_depth = int(getattr(self.opt, "augmix_depth", -1) or -1)
350
+ self.augmix_alpha = float(getattr(self.opt, "augmix_alpha", 1.0) or 1.0)
351
+ self.augmix_num_views = int(getattr(self.opt, "augmix_num_views", 2) or 2)
352
+ self.augmix_eps = float(getattr(self.opt, "augmix_js_eps", 1e-7) or 1e-7)
353
+ self.augmix_max_distortions = int(getattr(self.opt, "aug_utils_max_distortions", 3) or 3)
354
+ self.augmix_num_levels = int(getattr(self.opt, "aug_utils_num_levels", 5) or 5)
355
+ self._augmix_distort_images = None
356
+
357
+ trainmode = str(getattr(self.opt, "trainmode", "")).lower()
358
+ modelname = str(getattr(self.opt, "modelname", ""))
359
+ if trainmode == "lora" and modelname.startswith("CLIP:"):
360
+ mean, std = CLIP_MEAN, CLIP_STD
361
+ else:
362
+ mean, std = IMAGENET_MEAN, IMAGENET_STD
363
+ self._augmix_mean = torch.tensor(mean, dtype=torch.float32, device=self.device).view(1, 3, 1, 1)
364
+ self._augmix_std = torch.tensor(std, dtype=torch.float32, device=self.device).view(1, 3, 1, 1)
365
+
366
+ if not self.augmix_js_enable:
367
+ return
368
+ try:
369
+ from aug_utils_train.utils_data import distort_images as aug_utils_distort_images
370
+
371
+ self._augmix_distort_images = aug_utils_distort_images
372
+ print(
373
+ f"[AugMix-JS] Enabled (w={self.augmix_js_weight}, views={self.augmix_num_views}, "
374
+ f"width={self.augmix_width}, depth={self.augmix_depth}, alpha={self.augmix_alpha})"
375
+ )
376
+ except Exception as exc:
377
+ self.augmix_js_enable = False
378
+ self._augmix_distort_images = None
379
+ print(f"[AugMix-JS] Disabled because aug_utils_train import failed: {exc}")
380
+
381
+ def _extract_primary_logits(self, output):
382
+ if isinstance(output, dict):
383
+ for key in ("logits", "main", "token_logits", "concept_logits", "cb_only", "cls_only"):
384
+ logits = output.get(key)
385
+ if logits is not None:
386
+ return logits
387
+ raise RuntimeError("Cannot find usable logits in model output dict for AugMix-JS.")
388
+ if isinstance(output, tuple):
389
+ return output[0]
390
+ return output
391
+
392
+ def _logits_to_probs(self, logits: torch.Tensor) -> torch.Tensor:
393
+ if logits.dim() == 1:
394
+ logits = logits.unsqueeze(1)
395
+ if self.num_classes == 1 or logits.shape[1] == 1:
396
+ p_fake = torch.sigmoid(logits).view(-1, 1)
397
+ p_real = 1.0 - p_fake
398
+ probs = torch.cat([p_real, p_fake], dim=1)
399
+ else:
400
+ probs = F.softmax(logits, dim=1)
401
+ return probs.clamp_min(self.augmix_eps)
402
+
403
+ def _js_divergence_from_probs(self, probs_list):
404
+ if not probs_list:
405
+ return None
406
+ p_mixture = torch.stack(probs_list, dim=0).mean(dim=0).clamp_min(self.augmix_eps)
407
+ p_mixture_log = torch.log(p_mixture)
408
+ js = 0.0
409
+ for p in probs_list:
410
+ js = js + torch.sum(p_mixture * (p_mixture_log - torch.log(p.clamp_min(self.augmix_eps))), dim=1).mean()
411
+ js = js / float(len(probs_list))
412
+ return js
413
+
414
+ def _denormalize_to_unit(self, x: torch.Tensor) -> torch.Tensor:
415
+ return (x * self._augmix_std + self._augmix_mean).clamp(0.0, 1.0)
416
+
417
+ def _normalize_from_unit(self, x01: torch.Tensor) -> torch.Tensor:
418
+ return (x01 - self._augmix_mean) / self._augmix_std
419
+
420
+ def _augmix_single_image(self, img01_cpu: torch.Tensor) -> torch.Tensor:
421
+ # img01_cpu: [3,H,W] in [0,1], CPU tensor.
422
+ alpha = max(self.augmix_alpha, 1e-6)
423
+ ws = torch.distributions.Dirichlet(torch.tensor([alpha] * self.augmix_width)).sample().tolist()
424
+ m = torch.distributions.Beta(alpha, alpha).sample().item()
425
+ mix = torch.zeros_like(img01_cpu)
426
+ for i in range(self.augmix_width):
427
+ image_aug = img01_cpu.clone()
428
+ depth = self.augmix_depth if self.augmix_depth > 0 else int(torch.randint(1, 4, (1,)).item())
429
+ for _ in range(depth):
430
+ image_aug, _, _ = self._augmix_distort_images(
431
+ image_aug,
432
+ max_distortions=self.augmix_max_distortions,
433
+ num_levels=self.augmix_num_levels,
434
+ )
435
+ image_aug = image_aug.to(torch.float32).clamp(0.0, 1.0)
436
+ mix = mix + float(ws[i]) * image_aug
437
+ mixed = (1.0 - float(m)) * img01_cpu + float(m) * mix
438
+ return mixed.clamp(0.0, 1.0)
439
+
440
+ def _build_augmix_views(self, clean_input: torch.Tensor):
441
+ # Build on CPU for aug_utils compatibility, then move back to model device.
442
+ clean01 = self._denormalize_to_unit(clean_input.detach()).cpu()
443
+ views = []
444
+ for _ in range(self.augmix_num_views):
445
+ aug_batch = torch.empty_like(clean01)
446
+ for idx in range(clean01.shape[0]):
447
+ aug_batch[idx] = self._augmix_single_image(clean01[idx])
448
+ aug_batch = aug_batch.to(self.device, non_blocking=True)
449
+ aug_batch = self._normalize_from_unit(aug_batch)
450
+ views.append(aug_batch)
451
+ return views
452
+
453
+ def _compute_augmix_js_loss(self, clean_output):
454
+ if not self.augmix_js_enable or self._augmix_distort_images is None:
455
+ return None
456
+ clean_logits = self._extract_primary_logits(clean_output)
457
+ clean_probs = self._logits_to_probs(clean_logits)
458
+ aug_inputs = self._build_augmix_views(self.input)
459
+ aug_probs = []
460
+ for aug_input in aug_inputs:
461
+ aug_output = self.model(aug_input)
462
+ aug_logits = self._extract_primary_logits(aug_output)
463
+ aug_probs.append(self._logits_to_probs(aug_logits))
464
+ js_loss = self._js_divergence_from_probs([clean_probs] + aug_probs)
465
+ return js_loss
466
+
467
+ def optimize_parameters(self):
468
+ if self._deepspeed_engine is not None:
469
+ self.forward()
470
+ base_loss = self.get_loss()
471
+ js_loss = self._compute_augmix_js_loss(self.output)
472
+ if js_loss is not None:
473
+ self.augmix_js_loss = js_loss.detach()
474
+ self.loss = base_loss + self.augmix_js_weight * js_loss
475
+ else:
476
+ self.augmix_js_loss = None
477
+ self.loss = base_loss
478
+ self._deepspeed_engine.backward(self.loss)
479
+ self._deepspeed_engine.step()
480
+ return
481
+
482
+ with self._autocast_context():
483
+ self.forward()
484
+ base_loss = self.get_loss()
485
+ js_loss = self._compute_augmix_js_loss(self.output)
486
+ if js_loss is not None:
487
+ self.augmix_js_loss = js_loss.detach()
488
+ self.loss = base_loss + self.augmix_js_weight * js_loss
489
+ else:
490
+ self.augmix_js_loss = None
491
+ self.loss = base_loss
492
+
493
+ loss_for_backward = self.loss / float(self.grad_accum_steps)
494
+ if self.scaler is not None and self.scaler.is_enabled():
495
+ self.scaler.scale(loss_for_backward).backward()
496
+ else:
497
+ loss_for_backward.backward()
498
+
499
+ self._grad_accum_counter += 1
500
+ if self._grad_accum_counter % self.grad_accum_steps == 0:
501
+ self._optimizer_step_impl()
502
+
503
+ def finalize_epoch(self):
504
+ if self._deepspeed_engine is not None:
505
+ return
506
+ if not self.isTrain or self.grad_accum_steps <= 1:
507
+ return
508
+ if self._grad_accum_counter % self.grad_accum_steps == 0:
509
+ return
510
+ if self.is_main_process:
511
+ remain = self._grad_accum_counter % self.grad_accum_steps
512
+ print(f"[FullFinetune] finalize_epoch flush remaining accumulated steps: {remain}")
513
+ self._optimizer_step_impl()
detectors/ForensicConcept/upstream/options/__init__.py ADDED
File without changes