thecho7 commited on
Commit
43a23a4
1 Parent(s): c426e13
Files changed (1) hide show
  1. README.md +12 -171
README.md CHANGED
@@ -1,171 +1,12 @@
1
- ## DeepFake Detection (DFDC) Solution by @selimsef
2
-
3
- ## Challenge details:
4
-
5
- [Kaggle Challenge Page](https://www.kaggle.com/c/deepfake-detection-challenge)
6
-
7
-
8
- ### Fake detection articles
9
- - [The Deepfake Detection Challenge (DFDC) Preview Dataset](https://arxiv.org/abs/1910.08854)
10
- - [Deep Fake Image Detection Based on Pairwise Learning](https://www.mdpi.com/2076-3417/10/1/370)
11
- - [DeeperForensics-1.0: A Large-Scale Dataset for Real-World Face Forgery Detection](https://arxiv.org/abs/2001.03024)
12
- - [DeepFakes and Beyond: A Survey of Face Manipulation and Fake Detection](https://arxiv.org/abs/2001.00179)
13
- - [Real or Fake? Spoofing State-Of-The-Art Face Synthesis Detection Systems](https://arxiv.org/abs/1911.05351)
14
- - [CNN-generated images are surprisingly easy to spot... for now](https://arxiv.org/abs/1912.11035)
15
- - [FakeSpotter: A Simple yet Robust Baseline for Spotting AI-Synthesized Fake Faces](https://arxiv.org/abs/1909.06122)
16
- - [FakeLocator: Robust Localization of GAN-Based Face Manipulations via Semantic Segmentation Networks with Bells and Whistles](https://arxiv.org/abs/2001.09598)
17
- - [Media Forensics and DeepFakes: an overview](https://arxiv.org/abs/2001.06564)
18
- - [Face X-ray for More General Face Forgery Detection](https://arxiv.org/abs/1912.13458)
19
-
20
- ## Solution description
21
- In general solution is based on frame-by-frame classification approach. Other complex things did not work so well on public leaderboard.
22
-
23
- #### Face-Detector
24
- MTCNN detector is chosen due to kernel time limits. It would be better to use S3FD detector as more precise and robust, but opensource Pytorch implementations don't have a license.
25
-
26
- Input size for face detector was calculated for each video depending on video resolution.
27
-
28
- - 2x scale for videos with less than 300 pixels wider side
29
- - no rescale for videos with wider side between 300 and 1000
30
- - 0.5x scale for videos with wider side > 1000 pixels
31
- - 0.33x scale for videos with wider side > 1900 pixels
32
-
33
- ### Input size
34
- As soon as I discovered that EfficientNets significantly outperform other encoders I used only them in my solution.
35
- As I started with B4 I decided to use "native" size for that network (380x380).
36
- Due to memory costraints I did not increase input size even for B7 encoder.
37
-
38
- ### Margin
39
- When I generated crops for training I added 30% of face crop size from each side and used only this setting during the competition.
40
- See [extract_crops.py](preprocessing/extract_crops.py) for the details
41
-
42
- ### Encoders
43
- The winning encoder is current state-of-the-art model (EfficientNet B7) pretrained with ImageNet and noisy student [Self-training with Noisy Student improves ImageNet classification
44
- ](https://arxiv.org/abs/1911.04252)
45
-
46
- ### Averaging predictions
47
- I used 32 frames for each video.
48
- For each model output instead of simple averaging I used the following heuristic which worked quite well on public leaderbord (0.25 -> 0.22 solo B5).
49
- ```python
50
- import numpy as np
51
-
52
- def confident_strategy(pred, t=0.8):
53
- pred = np.array(pred)
54
- sz = len(pred)
55
- fakes = np.count_nonzero(pred > t)
56
- # 11 frames are detected as fakes with high probability
57
- if fakes > sz // 2.5 and fakes > 11:
58
- return np.mean(pred[pred > t])
59
- elif np.count_nonzero(pred < 0.2) > 0.9 * sz:
60
- return np.mean(pred[pred < 0.2])
61
- else:
62
- return np.mean(pred)
63
- ```
64
-
65
- ### Augmentations
66
-
67
- I used heavy augmentations by default.
68
- [Albumentations](https://github.com/albumentations-team/albumentations) library supports most of the augmentations out of the box. Only needed to add IsotropicResize augmentation.
69
- ```
70
-
71
- def create_train_transforms(size=300):
72
- return Compose([
73
- ImageCompression(quality_lower=60, quality_upper=100, p=0.5),
74
- GaussNoise(p=0.1),
75
- GaussianBlur(blur_limit=3, p=0.05),
76
- HorizontalFlip(),
77
- OneOf([
78
- IsotropicResize(max_side=size, interpolation_down=cv2.INTER_AREA, interpolation_up=cv2.INTER_CUBIC),
79
- IsotropicResize(max_side=size, interpolation_down=cv2.INTER_AREA, interpolation_up=cv2.INTER_LINEAR),
80
- IsotropicResize(max_side=size, interpolation_down=cv2.INTER_LINEAR, interpolation_up=cv2.INTER_LINEAR),
81
- ], p=1),
82
- PadIfNeeded(min_height=size, min_width=size, border_mode=cv2.BORDER_CONSTANT),
83
- OneOf([RandomBrightnessContrast(), FancyPCA(), HueSaturationValue()], p=0.7),
84
- ToGray(p=0.2),
85
- ShiftScaleRotate(shift_limit=0.1, scale_limit=0.2, rotate_limit=10, border_mode=cv2.BORDER_CONSTANT, p=0.5),
86
- ]
87
- )
88
- ```
89
- In addition to these augmentations I wanted to achieve better generalization with
90
- - Cutout like augmentations (dropping artefacts and parts of face)
91
- - Dropout part of the image, inspired by [GridMask](https://arxiv.org/abs/2001.04086) and [Severstal Winning Solution](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/114254)
92
-
93
- ![augmentations](images/augmentations.jpg "Dropout augmentations")
94
-
95
- ## Building docker image
96
- All libraries and enviroment is already configured with Dockerfile. It requires docker engine https://docs.docker.com/engine/install/ubuntu/ and nvidia docker in your system https://github.com/NVIDIA/nvidia-docker.
97
-
98
- To build a docker image run `docker build -t df .`
99
-
100
- ## Running docker
101
- `docker run --runtime=nvidia --ipc=host --rm --volume <DATA_ROOT>:/dataset -it df`
102
-
103
- ## Data preparation
104
-
105
- Once DFDC dataset is downloaded all the scripts expect to have `dfdc_train_xxx` folders under data root directory.
106
-
107
- Preprocessing is done in a single script **`preprocess_data.sh`** which requires dataset directory as first argument.
108
- It will execute the steps below:
109
-
110
- ##### 1. Find face bboxes
111
- To extract face bboxes I used facenet library, basically only MTCNN.
112
- `python preprocessing/detect_original_faces.py --root-dir DATA_ROOT`
113
- This script will detect faces in real videos and store them as jsons in DATA_ROOT/bboxes directory
114
-
115
- ##### 2. Extract crops from videos
116
- To extract image crops I used bboxes saved before. It will use bounding boxes from original videos for face videos as well.
117
- `python preprocessing/extract_crops.py --root-dir DATA_ROOT --crops-dir crops`
118
- This script will extract face crops from videos and save them in DATA_ROOT/crops directory
119
-
120
- ##### 3. Generate landmarks
121
- From the saved crops it is quite fast to process crops with MTCNN and extract landmarks
122
- `python preprocessing/generate_landmarks.py --root-dir DATA_ROOT`
123
- This script will extract landmarks and save them in DATA_ROOT/landmarks directory
124
-
125
- ##### 4. Generate diff SSIM masks
126
- `python preprocessing/generate_diffs.py --root-dir DATA_ROOT`
127
- This script will extract SSIM difference masks between real and fake images and save them in DATA_ROOT/diffs directory
128
-
129
- ##### 5. Generate folds
130
- `python preprocessing/generate_folds.py --root-dir DATA_ROOT --out folds.csv`
131
- By default it will use 16 splits to have 0-2 folders as a holdout set. Though only 400 videos can be used for validation as well.
132
-
133
-
134
- ## Training
135
-
136
- Training 5 B7 models with different seeds is done in **`train.sh`** script.
137
-
138
- During training checkpoints are saved for every epoch.
139
-
140
- ## Hardware requirements
141
- Mostly trained on devbox configuration with 4xTitan V, thanks to Nvidia and DSB2018 competition where I got these gpus https://www.kaggle.com/c/data-science-bowl-2018/
142
-
143
- Overall training requires 4 GPUs with 12gb+ memory.
144
- Batch size needs to be adjusted for standard 1080Ti or 2080Ti graphic cards.
145
-
146
- As I computed fake loss and real loss separately inside each batch, results might be better with larger batch size, for example on V100 gpus.
147
- Even though SyncBN is used larger batch on each GPU will lead to less noise as DFDC dataset has some fakes where face detector failed and face crops are not really fakes.
148
-
149
- ## Plotting losses to select checkpoints
150
-
151
- `python plot_loss.py --log-file logs/<log file>`
152
-
153
- ![loss plot](images/loss_plot.png "Weighted loss")
154
-
155
- ## Inference
156
-
157
-
158
- Kernel is reproduced with `predict_folder.py` script.
159
-
160
-
161
- ## Pretrained models
162
- `download_weights.sh` script will download trained models to `weights/` folder. They should be downloaded before building a docker image.
163
-
164
- Ensemble inference is already preconfigured with `predict_submission.sh` bash script. It expects a directory with videos as first argument and an output csv file as second argument.
165
-
166
- For example `./predict_submission.sh /mnt/datasets/deepfake/test_videos submission.csv`
167
-
168
-
169
-
170
-
171
-
 
1
+ title: Deepfake
2
+ emoji: 🔥
3
+ colorFrom: indigo
4
+ colorTo: purple
5
+ sdk: gradio
6
+ sdk_version: 3.29.0
7
+ app_file: app.py
8
+ pinned: false
9
+ license: unlicense
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference