The AntiDeepfake project provides a series of powerful foundation models post-trained for deepfake detection. The AntiDeepfake model can be used for feature extraction for deepfake detection in a zero-shot manner, or it may be further fine-tuned and optimized for a specific database or deepfake-related task.
1import os
2import torch
3import torchaudio
4from fairseq.models.wav2vec import Wav2Vec2Model, Wav2Vec2Config
5from huggingface_hub import PyTorchModelHubMixin
67# This is the only part of the script you need to modify.8# Set this to the path where your audio files are stored.9folder_path ="/path/to/folder/contains/wavs/"10audio_formats =(".mp3",".wav",".flac",".m4a")1112# === Set device (use GPU if available) ===13device = torch.device("cuda"if torch.cuda.is_available()else"cpu")14print(f"Using device: {device}")1516# === Wrapper for the SSL model ===17classSSLModel(torch.nn.Module):18def__init__(self):19super().__init__()20# Model config used to build SSL architecture21 cfg = Wav2Vec2Config(22 encoder_layers=12,23 encoder_embed_dim=768,24 quantize_targets=True,25 latent_dim=256,26 final_dim=256,27)28# Initialize SSL model with random weights29 self.model = Wav2Vec2Model(cfg)3031defextract_feat(self, input_data):32# If input has shape (B, T, 1), squeeze the last dim33if input_data.ndim ==3:34 input_data = input_data[:,:,0]35# Extract features36with torch.no_grad():37 features = self.model(input_data.to(device), mask=False, features_only=True)['x']38return features
3940# === Function for reading and pre-processing waveforms ===41defload_wav_and_preprocess(wav_path, target_sr=16000):42# Load audio file43 wav, sr = torchaudio.load(wav_path)44# Convert to mono if stereo45 wav = wav.mean(dim=0)46# Resample to target sampling rate47 wav = torchaudio.functional.resample(wav, sr, new_freq=target_sr)48# Normalize waveform49with torch.no_grad():50 wav = torch.nn.functional.layer_norm(wav, wav.shape)51# Add batch dimension and return52return wav.unsqueeze(0).to(device)5354# === The actual deepfake detection model using SSL frontend + FC backend ===55classDeepfakeDetector(torch.nn.Module, PyTorchModelHubMixin):56def__init__(self):57super().__init__()58 self.ssl_orig_output_dim =76859 self.num_classes =26061# Frontend: SSL model62 self.m_ssl = SSLModel()6364# Backend: Pooling + Classification65 self.adap_pool1d = torch.nn.AdaptiveAvgPool1d(output_size=1)66 self.proj_fc = torch.nn.Linear(67 in_features=self.ssl_orig_output_dim,68 out_features=self.num_classes,69)7071defforward(self, wav):72 emb = self.m_ssl.extract_feat(wav)# [B, T, D]73 emb = emb.transpose(1,2)# [B, D, T]74 pooled_emb = self.adap_pool1d(emb)# [B, D, 1]75 pooled_emb = pooled_emb.squeeze(-1)# [B, D]76 logits = self.proj_fc(pooled_emb)# [B, 2]77return logits
7879# === Load AntiDeepfake model from Hugging Face===80model = DeepfakeDetector.from_pretrained("nii-yamagishilab/wav2vec-small-anti-deepfake-nda")81model.to(device)82model.eval()8384# === Inference on a folder of audio files ===85results =[]86for root, _, files in os.walk(folder_path):87forfilein files:88iffile.lower().endswith(audio_formats):89 input_path = os.path.join(root,file)90with torch.no_grad():91 wav = load_wav_and_preprocess(input_path)92 logits = model(wav)93 probs = torch.nn.functional.softmax(logits, dim=1)94 results.append((file, probs.cpu().numpy()[0]))9596# Sort results alphabetically by filename97results.sort(key=lambda x: x[0])9899# Print formatted results100print("\n=== Deepfake Detection Results ===")101for file_name, prob in results:102print(f"{file_name}: real prob = {prob[1]:.3f}, fake prob = {prob[0]:.3f}")
📊 Performance Metrics
Results shown below can be reproduced using scripts provided in our GitHub repository.
Test Database
ROC AUC
Accuracy
Precision
Recall
F1-score
FPR
FNR
EER (%) @ Threshold
ADD2023
0.895
0.867
0.899
0.924
0.911
0.294
0.076
19.41 @ 0.9151
DeepVoice
0.923
0.405
0.170
0.991
0.290
0.677
0.009
16.20 @ 1.0000
FakeOrReal
0.999
0.956
0.997
0.913
0.953
0.003
0.087
1.06 @ 0.0430
FakeOrReal-norm
0.982
0.931
0.941
0.916
0.928
0.055
0.084
6.48 @ 0.3893
In-the-Wild
0.990
0.957
0.945
0.989
0.967
0.096
0.011
4.65 @ 0.9497
Deepfake-Eval-2024
0.759
0.701
0.696
0.962
0.808
0.793
0.038
31.97 @ 0.9995
You can also fine-tune this model on a specific database, the corresponding code is provided in our GitHub repository. Fine-tuning will follow a similar process to training a new model, except that model weights will be initialized as AntiDeepfake checkpoints.
Below are the evaluation results of this model fine-tuned on the Deepfake-Eval-2024 training set and tested on its corresponding test set (as shown in the previous table):
Test Input Length
ROC AUC
Accuracy
Precision
Recall
F1-score
FPR
FNR
EER (%) @ Threshold
4s
0.8826
0.8284
0.8492
0.8968
0.8724
0.3010
0.1032
18.67 @ 0.9049
10s
0.9173
0.8684
0.8916
0.9088
0.9001
0.2071
0.0912
14.88 @ 0.8852
13s
0.9255
0.8721
0.8959
0.9093
0.9026
0.1976
0.0907
13.88 @ 0.8760
30s
0.9330
0.8911
0.9144
0.9175
0.9159
0.1573
0.0825
12.22 @ 0.8724
50s
0.9309
0.8904
0.9109
0.9173
0.9141
0.1567
0.0827
12.44 @ 0.8401
Training Set
Below is a breakdown of the training set used for post-training of speech SSL models.
📚 Database
🌍 Language
✅ Genuine (hrs)
❌ Fake (hrs)
AISHELL3
zh
85.62
0
ASVspoof2019-LA
en
11.85
97.80
ASVspoof2021-LA
en
16.40
116.10
ASVspoof2021-DF
en
20.73
487.00
ASVspoof5
en
413.49
1808.48
CFAD
zh
171.25
224.55
CNCeleb2
zh
1084.34
0
Codecfake
en, zh
129.66
808.32
CodecFake
en
0
660.92
CVoiceFake
en, fr, de, it, zh
315.14
1561.16
DECRO
en, zh
35.18
102.44
DFADD
en
41.62
66.01
Diffuse or Confuse
en
0
231.66
DiffSSD
en
0
139.73
DSD
en, ja, ko
100.98
60.23
FLEURS
102 languages
1388.97
0
FLEURS-R
102 languages
0
1238.83
HABLA
es
35.56
87.83
LibriTTS
en
585.83
0
LibriTTS-R
en
0
583.15
LibriTTS-Vocoded
en
0
2345.14
LJSpeech
en
23.92
0
MLAAD
38 languages
0
377.96
MLS
8 languages
50558.11
0
SpoofCeleb
Multilingual
173.00
1916.20
VoiceMOS
en
0
448.44
VoxCeleb2
Multilingual
1179.62
0
VoxCeleb2-Vocoded
Multilingual
0
4721.46
WaveFake
en, ja
0
198.65
Train Set
Over 100 languages
56370.00
18280.00
Attribution
All AntiDeepfake models were developed by Yamagishi Lab at the National Institute of Informatics (NII), Japan.
All model weights are the intellectual property of NII and are made available for research and educational purposes under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license.
Acknowledgments
This project is based on results obtained from project JPNP22007, commissioned by the New Energy and Industrial Technology Development Organization (NEDO).
It is also partially supported by the following grants from the Japan Science and Technology Agency (JST):
AIP Acceleration Research (Grant No. JPMJCR24U3)
PRESTO (Grant No. JPMJPR23P9)
This study was carried out using the TSUBAME4.0 supercomputer at Institute of Science Tokyo.