Downloads · 30 days
7.7K
15% of all-time downloads
garystafford/wav2vec2-deepfake-voice-detector
wav2vec2-deepfake-voice-detector is a audio classification model from garystafford. Use it for the audio classification task on the model card, and read the license before you ship it in a product. It is set up for transformers. The card lists the license as apache-2.0.
Fine-tuned Wav2Vec2 model for detecting AI-generated speech. Determines if audio was spoken by a human or created by AI text-to-speech/voice cloning software.
Downloads · 30 days
7.7K
15% of all-time downloads
All-time downloads
50.1K
Public
Parameters
316M
16.4 GB on disk
Likes
6
Public
Click a slice to open those files.
.safetensors1.3 GB · 100%
From the Hugging Face model README
Fine-tuned Wav2Vec2 model for detecting AI-generated speech. Determines if audio was spoken by a human or created by AI text-to-speech/voice cloning software.
Fine-tuned Wav2Vec2 transformer for binary audio classification (real vs AI-generated speech). Trained to distinguish authentic human speech from synthetic audio generated by AI text-to-speech and voice cloning services including:
Developed by: Gary A. Stafford
Note: This model uses transfer learning from a base model already trained for deepfake detection. Fast convergence is expected due to task similarity and TTS engine overlap with the base model's training data.
Install the required dependencies:
pip install transformers torch librosa
Optional: For GPU acceleration (recommended):
# For CUDA 11.8
pip install torch --index-url https://download.pytorch.org/whl/cu118
# For CUDA 12.1
pip install torch --index-url https://download.pytorch.org/whl/cu121
import torch
import librosa
from transformers import AutoModelForAudioClassification, AutoFeatureExtractor
# Load model and feature extractor
model_name = "garystafford/wav2vec2-deepfake-voice-detector"
model = AutoModelForAudioClassification.from_pretrained(model_name)
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
# Move to GPU if available
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
model.eval()
# Load and preprocess audio (automatically resamples to 16kHz)
audio, sr = librosa.load("path/to/audio.wav", sr=16000, mono=True)
inputs = feature_extractor(audio, sampling_rate=16000, return_tensors="pt", padding=True)
inputs = {k: v.to(device) for k, v in inputs.items()}
# Run inference
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
probs = torch.nn.functional.softmax(logits, dim=-1)
# Get prediction
prob_real = probs[0][0].item()
prob_fake = probs[0][1].item()
prediction = "fake" if prob_fake > 0.5 else "real"
print(f"Prediction: {prediction}")
print(f"Confidence: {max(prob_real, prob_fake):.2%}")
print(f"Probabilities - Real: {prob_real:.2%}, Fake: {prob_fake:.2%}")
The model outputs logits (raw, unnormalized scores) for two classes:
Converting Logits to Probabilities:
Apply softmax to convert raw logits into interpretable probability scores:
probs = torch.nn.functional.softmax(logits, dim=-1)
logits.shape = (1, 2) → probs.shape = (1, 2) where probs[0] contains [prob_real, prob_fake] summing to 1.0logits.shape = (N, 2) → probs.shape = (N, 2) where each sample's probabilities sum to 1.0 independentlydim=-1: Applies softmax across classes for each sample, not across samplesimport glob
audio_files = glob.glob("audio_folder/*.wav")
for audio_path in audio_files:
audio, _ = librosa.load(audio_path, sr=16000, mono=True)
inputs = feature_extractor(audio, sampling_rate=16000, return_tensors="pt", padding=True)
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
prediction = "fake" if probs[0][1] > 0.5 else "real"
print(f"{audio_path}: {prediction} ({probs[0][1]:.2%} fake)")
Source: garystafford/deepfake-audio-detection
Composition:
Split:
| Split | Real | Fake | Total | Percentage |
|---|---|---|---|---|
| Train | 746 | 746 | 1,492 | 80% |
| Validation | 93 | 94 | 187 | 10% |
| Test | 94 | 93 | 187 | 10% |
Stratified splitting applied to ensure balanced class distribution across all splits.
Base Model: Gustking/wav2vec2-large-xlsr-deepfake-audio-classification - A Wav2Vec2-XLSR model pre-trained on 53 languages and already fine-tuned for deepfake audio detection.
Method: Transfer learning with selective layer freezing:
| Parameter | Value |
|---|---|
| Learning rate | 3e-5 |
| Epochs (max) | 5 |
| Early stopping patience | 3 evaluations |
| Evaluation frequency | Every 30 steps |
| Per-device batch size | 4 |
| Gradient accumulation steps | 4 |
| Effective batch size | 16 |
| Optimizer | AdamW |
| Warmup ratio | 0.1 (10%) |
| Weight decay | 0.01 |
| Save strategy | Every 30 steps |
| Metric for best model | ROC-AUC |
| Precision | FP16 |
Training Statistics:
The model uses AutoModelForAudioClassification with a two-class output (0=real, 1=fake):
This architecture balances efficiency with adaptability—frozen layers preserve general audio understanding while trained layers (~160M parameters) learn dataset-specific deepfake detection patterns.
⚠️ IMPORTANT CONTEXT: These high-performance metrics reflect fine-tuning a specialist model on its own domain. The base model (
Gustking/wav2vec2-large-xlsr-deepfake-audio-classification) was already trained for deepfake detection, likely on similar TTS engines. These results demonstrate successful adaptation to this specific dataset of 1,866 samples, NOT general deepfake detection capability from scratch. The excellent ROC-AUC (0.998) indicates near-perfect class separation, though 4 samples (2.1%) are still misclassified at the default 0.5 threshold.
The model performs well on the validation set of 187 audio clips (94 real, 93 fake):
Validation Results (at threshold 0.5):
Per-Class Metrics (threshold 0.5):
| Class | Precision | Recall | F1-Score | Support |
|---|---|---|---|---|
| Real | 1.00 | 0.96 | 0.98 | 94 |
| Fake | 0.96 | 1.00 | 0.98 | 93 |
Confusion Matrix (threshold 0.5):
| Pred Real | Pred Fake | |
|---|---|---|
| True Real | 90 | 4 |
| True Fake | 0 | 93 |
Note: Best balanced accuracy of 98.4% achieved at threshold 0.9 (96.8% real recall, 100% fake recall).
Context for High Performance:
Generalization Limitations:
Estimated based on model architecture: