jayesh20 commited on
Commit
a600a2e
·
verified ·
1 Parent(s): eb7ccc0

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +211 -0
README.md ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ library_name: pytorch
6
+ pipeline_tag: image-classification
7
+ base_model: laion/CLIP-ViT-B-32-laion2B-s34B-b79K
8
+ datasets:
9
+ - yangsangtai/tiny-genimage
10
+ metrics:
11
+ - accuracy
12
+ - precision
13
+ - recall
14
+ - f1
15
+ - roc_auc
16
+ tags:
17
+ - image-classification
18
+ - ai-generated-image-detection
19
+ - deepfake-detection
20
+ - clip
21
+ - computer-vision
22
+ - binary-classification
23
+ ---
24
+
25
+ # CLIP-Based AI-Generated Image Detector
26
+
27
+ ## Model Description
28
+
29
+ This model is a binary image classifier that distinguishes real (natural) photographs from AI-generated images. It uses a frozen CLIP ViT-B/32 vision encoder (pretrained on LAION-2B) as a fixed feature extractor, with a lightweight multilayer perceptron classification head trained on top of the extracted image embeddings.
30
+
31
+ The model was developed and trained in a Kaggle notebook titled `complete_Fakeddit_image`. Despite the notebook name, the training data used is the `tiny-genimage` dataset rather than the Fakeddit dataset; this README describes the model as actually implemented and trained.
32
+
33
+ ## Model Details
34
+
35
+ - **Base encoder:** CLIP ViT-B-32, pretrained weights `laion2b_s34b_b79k` (loaded via `open_clip`)
36
+ - **Encoder state:** Frozen; no gradient updates applied to CLIP parameters during training
37
+ - **Classification head:** Fully connected network operating on 512-dimensional, L2-normalized CLIP image embeddings
38
+
39
+ | Layer | Output Size | Normalization | Activation | Dropout |
40
+ |---|---|---|---|---|
41
+ | Linear | 512 | BatchNorm1d | GELU | 0.4 |
42
+ | Linear | 256 | BatchNorm1d | GELU | 0.3 |
43
+ | Linear | 128 | BatchNorm1d | GELU | 0.2 |
44
+ | Linear | 2 | - | - | - |
45
+
46
+ - **Output:** Two logits corresponding to the classes `real` (label 0) and `ai-generated` (label 1)
47
+ - **Framework:** PyTorch, with `open_clip` for the CLIP backbone
48
+ - **Input resolution:** 224 x 224 pixels, RGB
49
+
50
+ ## Intended Use
51
+
52
+ The model is intended for research and experimentation in AI-generated image detection, such as:
53
+
54
+ - Screening images for likely synthetic origin
55
+ - Research on generalization of detectors across different generative model families
56
+ - Educational use in understanding CLIP-based transfer learning for detection tasks
57
+
58
+ ### Out of Scope Use
59
+
60
+ This model is not intended for:
61
+
62
+ - Legal, forensic, or high-stakes determinations of image authenticity without human review
63
+ - Detection of generative models or techniques not represented in the training distribution
64
+ - Use as a sole determinant of content moderation decisions
65
+
66
+ ## Training Data
67
+
68
+ The model was trained on the `tiny-genimage` dataset (source: `yangsangtai/tiny-genimage`), which pairs natural images with images produced by seven different generative model families.
69
+
70
+ - **Total images:** 35,000
71
+ - **Class balance:** 17,500 real images (label 0), 17,500 AI-generated images (label 1)
72
+ - **Train / validation split:** 28,000 / 7,000 images
73
+
74
+ Generators represented in the dataset, each contributing 5,000 images:
75
+
76
+ - imagenet_ai_0424_wukong
77
+ - imagenet_glide
78
+ - imagenet_ai_0419_biggan
79
+ - imagenet_ai_0419_vqdm
80
+ - imagenet_midjourney
81
+ - imagenet_ai_0424_sdv5
82
+ - imagenet_ai_0508_adm
83
+
84
+ ## Training Procedure
85
+
86
+ ### Preprocessing and Augmentation
87
+
88
+ Implemented using the `albumentations` library.
89
+
90
+ **Training transforms:**
91
+ - Resize to 224 x 224
92
+ - Horizontal flip (probability 0.5)
93
+ - Random brightness/contrast (probability 0.3)
94
+ - Normalization
95
+ - Conversion to tensor
96
+
97
+ **Validation transforms:**
98
+ - Resize to 224 x 224
99
+ - Normalization
100
+ - Conversion to tensor
101
+
102
+ ### Optimization
103
+
104
+ - **Loss function:** Cross-entropy loss
105
+ - **Optimizer:** AdamW, applied only to the classification head parameters
106
+ - **Learning rate:** 1e-4 (initial training phase), reduced to 1e-5 for a subsequent fine-tuning phase
107
+ - **Learning rate schedule:** Cosine annealing
108
+ - **Batch size:** 32
109
+ - **Maximum epochs:** 20, with early stopping (patience of 5 epochs, monitored on validation F1 score)
110
+ - **Checkpointing:** Best model saved whenever validation F1 improved; full training state (model, optimizer, scheduler, epoch, best F1) checkpointed for resumption
111
+ - **Hardware:** Single NVIDIA Tesla T4 GPU
112
+
113
+ Training was conducted in two stages within the notebook: an initial run to 18 epochs before early stopping triggered a checkpoint save, followed by a resumed run at a lower learning rate for 2 additional epochs.
114
+
115
+ ## Evaluation
116
+
117
+ Evaluation was performed on the held-out validation split (7,000 images) using the checkpoint with the best validation F1 score.
118
+
119
+ ### Final Reported Metrics
120
+
121
+ | Metric | Score |
122
+ |---|---|
123
+ | Accuracy | 0.9500 |
124
+ | Precision | 0.9474 |
125
+ | Recall | 0.9529 |
126
+ | F1 Score | 0.9501 |
127
+ | ROC AUC | 0.9894 |
128
+
129
+ A confusion matrix was also generated on the validation set to inspect class-wise performance; see the original notebook for the corresponding plot.
130
+
131
+ ## Usage
132
+
133
+ ```python
134
+ import torch
135
+ import torch.nn as nn
136
+ import torch.nn.functional as F
137
+ import open_clip
138
+ from PIL import Image
139
+ import albumentations as A
140
+ from albumentations.pytorch import ToTensorV2
141
+ import numpy as np
142
+
143
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
144
+
145
+ # Load CLIP backbone
146
+ clip_model, _, _ = open_clip.create_model_and_transforms(
147
+ "ViT-B-32",
148
+ pretrained="laion2b_s34b_b79k"
149
+ )
150
+ clip_model = clip_model.to(DEVICE)
151
+ for param in clip_model.parameters():
152
+ param.requires_grad = False
153
+
154
+ # Define classifier head
155
+ class CLIPBinaryClassifier(nn.Module):
156
+ def __init__(self):
157
+ super().__init__()
158
+ self.clip = clip_model
159
+ self.classifier = nn.Sequential(
160
+ nn.Linear(512, 512), nn.BatchNorm1d(512), nn.GELU(), nn.Dropout(0.4),
161
+ nn.Linear(512, 256), nn.BatchNorm1d(256), nn.GELU(), nn.Dropout(0.3),
162
+ nn.Linear(256, 128), nn.BatchNorm1d(128), nn.GELU(), nn.Dropout(0.2),
163
+ nn.Linear(128, 2)
164
+ )
165
+
166
+ def forward(self, images):
167
+ with torch.no_grad():
168
+ features = self.clip.encode_image(images)
169
+ features = F.normalize(features, dim=-1)
170
+ return self.classifier(features)
171
+
172
+ # Load trained weights
173
+ model = CLIPBinaryClassifier().to(DEVICE)
174
+ model.load_state_dict(torch.load("best_clip_detector.pth", map_location=DEVICE))
175
+ model.eval()
176
+
177
+ # Preprocess an image
178
+ transform = A.Compose([
179
+ A.Resize(224, 224),
180
+ A.Normalize(),
181
+ ToTensorV2()
182
+ ])
183
+
184
+ image = np.array(Image.open("example.jpg").convert("RGB"))
185
+ image_tensor = transform(image=image)["image"].unsqueeze(0).to(DEVICE)
186
+
187
+ # Run inference
188
+ with torch.no_grad():
189
+ logits = model(image_tensor)
190
+ probs = torch.softmax(logits, dim=1)
191
+ prediction = logits.argmax(1).item()
192
+
193
+ label_map = {0: "real", 1: "ai-generated"}
194
+ print(label_map[prediction], probs.cpu().numpy())
195
+ ```
196
+
197
+ ## Limitations
198
+
199
+ - The training data is derived from ImageNet-based real images paired with a fixed set of seven generative model families; performance on generators, domains, or image types outside this distribution is not established.
200
+ - The dataset is referred to as "tiny-genimage," implying it is a reduced-scale subset of a larger dataset; results may not generalize to the full-scale version.
201
+ - The classification head was trained on frozen CLIP embeddings only; the underlying CLIP encoder was not fine-tuned, which may limit adaptation to subtle generation artifacts not captured by general-purpose CLIP features.
202
+ - No adversarial robustness testing was performed against images specifically crafted to evade detection.
203
+
204
+ ## Citation
205
+
206
+ If you use this model, please cite the underlying CLIP and dataset resources:
207
+
208
+ ```
209
+ CLIP backbone: laion2b_s34b_b79k (OpenCLIP, LAION)
210
+ Dataset: tiny-genimage (yangsangtai/tiny-genimage)
211
+ ```