Views
No views yet
🔍 Detect deepfakes with state-of-the-art accuracy
A ResNeXt-101 32×8d backbone — initialised from Instagram's weakly-supervised pretrained weights — fine-tuned to expose AI-generated and manipulated faces with high confidence.
✅ Real Face 🚨 Deepfake
────────────── ──────────────
Confidence: 97.3% Confidence: 99.1%
|
|
The backbone uses grouped convolutions with cardinality 32 — each layer splits into 32 parallel transformation paths, then aggregates. This lets the network learn diverse artefact patterns (blending seams, frequency inconsistencies, unnatural textures) simultaneously.
┌─────────────────────────────────────────────────────────────┐
│ ResNeXt-101 32×8d │
├─────────────────────────────────────────────────────────────┤
│ │
│ 📷 Input ──▶ 🌱 STEM │
│ Conv 7×7 │ BN │ ReLU │ MaxPool │
│ 3 → 64 channels │
│ │ │
│ ┌────────▼────────┐ │
│ │ 🧩 LAYER 1 │ ×3 blocks · ch 256 │
│ └────────┬────────┘ │
│ ┌────────▼────────┐ │
│ │ 🧩 LAYER 2 │ ×4 blocks · ch 512 │
│ └────────┬────────┘ │
│ ┌────────▼────────┐ │
│ │ 🧩 LAYER 3 │ ×23 blocks · ch 1024 ◀── deepest │
│ └────────┬────────┘ │
│ ┌────────▼────────┐ │
│ │ 🧩 LAYER 4 │ ×3 blocks · ch 2048 │
│ └────────┬────────┘ │
│ Global Avg Pool │
│ │ │
│ ┌─────────▼─────────┐ │
│ │ 🎯 FC HEAD │ 2048 → num_classes │
│ └───────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Each bottleneck block:
┌──────────────────────────────────────────────────┐
│ 1×1 Conv (expand) → 3×3 GroupConv (groups=32) │
│ → 1×1 Conv (compress) + Skip Connection │
└──────────────────────────────────────────────────┘1# Clone the repo
2git clone https://github.com/accel-reg/deepfake-detection.git
3cd deepfake-detection
4
5# Install requirements
6pip install -r requirements.txttorch>=1.13
torchvision>=0.14
Pillow
opencv-python
huggingface_hub1import torch
2from model import DeepfakeDetector # from the repo
3
4# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
5# Option A — load local file
6# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
7model = DeepfakeDetector()
8model.load_state_dict(torch.load("ig.bin", map_location="cpu"))
9model.eval()
10
11# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
12# Option B — pull from HuggingFace 🤗
13# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
14from huggingface_hub import hf_hub_download
15
16path = hf_hub_download(repo_id="accel69/depfake-detection", filename="ig.bin")
17model = DeepfakeDetector()
18model.load_state_dict(torch.load(path, map_location="cpu"))
19model.eval()1from torchvision import transforms
2from PIL import Image
3
4# ── Standard ImageNet preprocessing ───────────────────────────
5transform = transforms.Compose([
6 transforms.Resize(256),
7 transforms.CenterCrop(224),
8 transforms.ToTensor(),
9 transforms.Normalize(
10 mean=[0.485, 0.456, 0.406],
11 std =[0.229, 0.224, 0.225]
12 ),
13])
14
15# ── Predict ────────────────────────────────────────────────────
16img = Image.open("face.jpg").convert("RGB")
17x = transform(img).unsqueeze(0) # → (1, 3, 224, 224)
18
19with torch.no_grad():
20 probs = torch.softmax(model(x), dim=1)
21 pred = probs.argmax(dim=1).item()
22
23label = "🚨 FAKE" if pred == 1 else "✅ REAL"
24confidence = probs[0, pred].item()
25
26print(f" Result : {label}")
27print(f" Confidence : {confidence:.2%}")1from pathlib import Path
2
3image_dir = Path("frames/")
4results = {"real": 0, "fake": 0}
5
6for img_path in sorted(image_dir.glob("*.jpg")):
7 img = Image.open(img_path).convert("RGB")
8 x = transform(img).unsqueeze(0)
9
10 with torch.no_grad():
11 probs = torch.softmax(model(x), dim=1)
12
13 is_fake = probs.argmax().item() == 1
14 confidence = probs.max().item()
15 label = "🚨 FAKE" if is_fake else "✅ REAL"
16
17 results["fake" if is_fake else "real"] += 1
18 print(f" {img_path.name:<35} {label} ({confidence:.2%})")
19
20print(f"\n 📊 Summary — ✅ Real: {results['real']} | 🚨 Fake: {results['fake']}")1device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
2model = model.to(device)
3
4print(f" 🔥 Running on : {device}")
5print(f" ⚡ CUDA cores : {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'N/A'}")
6
7# Move input to same device
8x = x.to(device)
9
10with torch.no_grad():
11 probs = torch.softmax(model(x), dim=1)1import cv2
2
3cap = cv2.VideoCapture("video.mp4")
4fake_frames = 0
5total_frames = 0
6
7print(" 🎬 Analysing video...")
8
9while cap.isOpened():
10 ret, frame = cap.read()
11 if not ret:
12 break
13
14 img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
15 x = transform(img).unsqueeze(0)
16
17 with torch.no_grad():
18 pred = model(x).argmax(dim=1).item()
19
20 fake_frames += pred
21 total_frames += 1
22
23cap.release()
24
25fake_pct = fake_frames / total_frames
26verdict = "🚨 LIKELY DEEPFAKE" if fake_pct > 0.5 else "✅ LIKELY REAL"
27
28print(f"\n ┌─────────────────────────────────┐")
29print(f" │ 🎬 Total frames : {total_frames:<12}│")
30print(f" │ 🚨 Fake frames : {fake_frames:<12}│")
31print(f" │ ✅ Real frames : {total_frames-fake_frames:<12}│")
32print(f" │ 📊 Fake ratio : {fake_pct:<11.1%} │")
33print(f" │ 🏁 Verdict : {verdict:<12}│")
34print(f" └─────────────────────────────────┘") Training Pipeline
══════════════════════════════════════════════════════
📦 Backbone Instagram WSL ResNeXt-101 32×8d
🖼️ Resolution 224 × 224 RGB
📐 Normalisation ImageNet mean [0.485 0.456 0.406]
std [0.229 0.224 0.225]
📉 Loss function Cross-Entropy
🔄 Augmentation Horizontal flip · Colour jitter
Random crop · Rotation| ⚙️ Hyperparameter | 📋 Value |
|---|---|
| 🧱 Backbone init | Instagram WSL pretrained (WSL-Images) |
| 📷 Input resolution | 224 × 224 |
| 📐 Normalisation | ImageNet mean / std |
| 📉 Loss | Cross-Entropy |
| 🔄 Augmentations | Flip, colour jitter, random crop |
📖 Full configs, dataset prep scripts and training logs → GitHub Repository
🚧 Read before deploying in any production or real-world system.
| ⚠️ Risk | 📋 Details |
|---|---|
| 🆕 Novel forgery methods | May not detect unseen GAN/diffusion techniques |
| 📐 Alignment sensitivity | Poor face crop → lower accuracy. Use a dedicated face detector first |
| 🌍 Distribution shift | Different cameras, compression, or lighting may degrade results |
| ⚖️ Demographic bias | Not audited across demographic groups — evaluate independently |
| 🔁 No temporal context | Frame-level only — no multi-frame consistency modelling |
✅ Good uses
|
❌ Not intended for
|
1@misc{ig-deepfake-detection-2025,
2 author = {accel69},
3 title = {ig.bin — Deepfake Face Detection with ResNeXt-101 32x8d},
4 year = {2025},
5 publisher = {HuggingFace},
6 url = {https://huggingface.co/accel69/depfake-detection}
7}