Make repo self-contained: inference wrapper code and arena_entry.yaml
Browse files- _hub.py +69 -0
- _net.py +107 -0
- arena_entry.yaml +7 -0
- implementation-notes.md +21 -0
- meta.yaml +31 -0
- sweep.py +25 -0
- test_xls_r_2b_antideepfake_nda.py +32 -0
- trt_xls_r_2b_antideepfake_nda.py +14 -1
- xls_r_2b_antideepfake_nda.py +62 -0
_hub.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Weight resolution for this Arena wrapper (self-contained; no machine-specific paths).
|
| 2 |
+
|
| 3 |
+
A file is taken from the wrapper's directory when it is present there (a full `snapshot_download` /
|
| 4 |
+
`git clone` of this repo, or a manual copy); otherwise it is fetched with `hf_hub_download` from a
|
| 5 |
+
commit-pinned public Hugging Face repo into the normal HF cache. Files that must be derived from a
|
| 6 |
+
third-party checkpoint (unlicensed weights the Arena links but does not re-host) are built once and
|
| 7 |
+
cached under $ARENA_CKPT_CACHE (default ~/.cache/speech_spoof_bench/<Model>/).
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import hashlib
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def local_or_hub(here: str, name: str, repo_id: str, filename: str | None = None, revision: str | None = None,
|
| 16 |
+
sha256: str | None = None) -> str:
|
| 17 |
+
"""<here>/<name> if it exists (here = the calling wrapper's directory), else
|
| 18 |
+
hf_hub_download(repo_id, filename or name, revision)."""
|
| 19 |
+
p = os.path.join(here, name)
|
| 20 |
+
if os.path.exists(p):
|
| 21 |
+
return p
|
| 22 |
+
from huggingface_hub import hf_hub_download
|
| 23 |
+
p = hf_hub_download(repo_id, filename or name, revision=revision)
|
| 24 |
+
if sha256 is not None:
|
| 25 |
+
check_sha256(p, sha256)
|
| 26 |
+
return p
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def check_sha256(path: str, expected: str) -> None:
|
| 30 |
+
h = hashlib.sha256()
|
| 31 |
+
with open(path, "rb") as f:
|
| 32 |
+
for b in iter(lambda: f.read(1 << 24), b""):
|
| 33 |
+
h.update(b)
|
| 34 |
+
if h.hexdigest() != expected:
|
| 35 |
+
raise RuntimeError(f"{path}: sha256 {h.hexdigest()} != pinned {expected}")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def cache_dir(model: str) -> str:
|
| 39 |
+
root = os.environ.get("ARENA_CKPT_CACHE") or os.path.join(os.path.expanduser("~"), ".cache", "speech_spoof_bench")
|
| 40 |
+
d = os.path.join(root, model)
|
| 41 |
+
os.makedirs(d, exist_ok=True)
|
| 42 |
+
return d
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def derived(here: str, name: str, model: str, build) -> str:
|
| 46 |
+
"""<here>/<name> if present, else <cache_dir(model)>/<name>, created once by build(out_path)."""
|
| 47 |
+
p = os.path.join(here, name)
|
| 48 |
+
if os.path.exists(p):
|
| 49 |
+
return p
|
| 50 |
+
p = os.path.join(cache_dir(model), name)
|
| 51 |
+
if not os.path.exists(p):
|
| 52 |
+
tmp = p + f".part{os.getpid()}"
|
| 53 |
+
build(tmp)
|
| 54 |
+
os.replace(tmp, p)
|
| 55 |
+
return p
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def local_or_gdrive(here: str, name: str, model: str, file_id: str, sha256: str) -> str:
|
| 59 |
+
"""<here>/<name> if present, else <cache_dir(model)>/<name> downloaded once from Google Drive with gdown
|
| 60 |
+
(pip install gdown) and sha256-checked. For weights whose only public source is the authors' Drive."""
|
| 61 |
+
def _get(out):
|
| 62 |
+
try:
|
| 63 |
+
import gdown
|
| 64 |
+
except ImportError as e:
|
| 65 |
+
raise RuntimeError(f"{name} is not in {here}: install gdown or download Google Drive file id {file_id} "
|
| 66 |
+
f"(sha256 {sha256}) to {os.path.join(here, name)}") from e
|
| 67 |
+
gdown.download(id=file_id, output=out, quiet=False)
|
| 68 |
+
check_sha256(out, sha256)
|
| 69 |
+
return derived(here, name, model, _get)
|
_net.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared network definition for the AntiDeepfake collection wrappers.
|
| 2 |
+
|
| 3 |
+
Vendored from nii-yamagishilab/AntiDeepfake (models/W2V.py, models/HBT.py,
|
| 4 |
+
models/W2V_configs.py, models/HBT_configs.py) so the state-dict keys
|
| 5 |
+
(`m_ssl.model.*`, `proj_fc.*`) match the released `model.safetensors`
|
| 6 |
+
bit-for-bit (verified: 220/220 keys, 0 missing/unexpected on w2v_small).
|
| 7 |
+
|
| 8 |
+
Architecture (identical for every backbone): a fairseq SSL frontend built from
|
| 9 |
+
the explicit config below, AdaptiveAvgPool1d(1) over time, then Linear(D, 2).
|
| 10 |
+
Output logits are [fake, real]; the bona-fide score is logit[:, 1] (real).
|
| 11 |
+
|
| 12 |
+
Upstream license: code BSD-3-Clause, checkpoints CC BY-NC-SA 4.0.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from fairseq.models.wav2vec import Wav2Vec2Model, Wav2Vec2Config
|
| 18 |
+
from fairseq.models.hubert import HubertModel, HubertConfig
|
| 19 |
+
from fairseq.tasks.hubert_pretraining import HubertPretrainingConfig
|
| 20 |
+
from fairseq.data import Dictionary
|
| 21 |
+
|
| 22 |
+
# ----------------------------------------------------------------------------
|
| 23 |
+
# wav2vec2-family configs (wav2vec small/large, MMS 300M/1B, XLS-R 1B/2B)
|
| 24 |
+
# ----------------------------------------------------------------------------
|
| 25 |
+
W2V_INPUT_DIMS = {
|
| 26 |
+
'w2v_small': 768, 'w2v_large': 1024, 'mms_300m': 1024,
|
| 27 |
+
'mms_1b': 1280, 'xlsr_1b': 1280, 'xlsr_2b': 1920,
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
W2V_CONFIGS = {
|
| 31 |
+
'w2v_small': {'_name': 'wav2vec2', 'encoder_layers': 12, 'encoder_embed_dim': 768, 'encoder_ffn_embed_dim': 3072, 'encoder_attention_heads': 12, 'final_dim': 256, 'encoder_layerdrop': 0.05, 'dropout_input': 0.1, 'dropout_features': 0.1, 'feature_grad_mult': 0.1, 'quantize_targets': True, 'latent_temp': [2.0, 0.5, 0.999995]},
|
| 32 |
+
'w2v_large': {'_name': 'wav2vec2', 'extractor_mode': 'layer_norm', 'encoder_layers': 24, 'encoder_embed_dim': 1024, 'encoder_ffn_embed_dim': 4096, 'encoder_attention_heads': 16, 'activation_fn': 'gelu', 'dropout': 0.0, 'attention_dropout': 0.0, 'activation_dropout': 0.0, 'encoder_layerdrop': 0.0, 'dropout_input': 0.0, 'dropout_features': 0.0, 'final_dim': 768, 'layer_norm_first': True, 'conv_feature_layers': '[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512,2,2)] + [(512,2,2)]', 'conv_bias': True, 'logit_temp': 0.1, 'quantize_targets': True, 'quantize_input': False, 'same_quantizer': False, 'target_glu': False, 'feature_grad_mult': 1.0, 'latent_vars': 320, 'latent_groups': 2, 'latent_dim': 0, 'mask_length': 10, 'mask_prob': 0.65, 'mask_selection': 'static', 'mask_other': 0.0, 'no_mask_overlap': False, 'mask_min_space': 1, 'mask_channel_length': 10, 'mask_channel_prob': 0.0, 'mask_channel_selection': 'static', 'mask_channel_other': 0.0, 'no_mask_channel_overlap': False, 'mask_channel_min_space': 1, 'num_negatives': 100, 'negatives_from_everywhere': False, 'cross_sample_negatives': 0, 'codebook_negatives': 0, 'conv_pos': 128, 'conv_pos_groups': 16, 'latent_temp': [2.0, 0.1, 0.999995]},
|
| 33 |
+
'mms_300m': {'_name': 'wav2vec2', 'extractor_mode': 'layer_norm', 'encoder_layers': 24, 'encoder_embed_dim': 1024, 'encoder_ffn_embed_dim': 4096, 'encoder_attention_heads': 16, 'activation_fn': 'gelu', 'dropout': 0.0, 'attention_dropout': 0.0, 'activation_dropout': 0.0, 'encoder_layerdrop': 0.0, 'dropout_input': 0.0, 'dropout_features': 0.0, 'final_dim': 768, 'layer_norm_first': True, 'conv_feature_layers': '[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512,2,2)] + [(512,2,2)]', 'conv_bias': True, 'logit_temp': 0.1, 'quantize_targets': True, 'quantize_input': False, 'same_quantizer': False, 'target_glu': False, 'feature_grad_mult': 1.0, 'quantizer_depth': 1, 'quantizer_factor': 3, 'latent_vars': 320, 'latent_groups': 2, 'latent_dim': 0, 'mask_length': 10, 'mask_prob': 0.65, 'mask_selection': 'static', 'mask_other': 0.0, 'no_mask_overlap': False, 'mask_min_space': 1, 'num_negatives': 100, 'negatives_from_everywhere': False, 'cross_sample_negatives': 0, 'codebook_negatives': 0, 'conv_pos': 128, 'conv_pos_groups': 16, 'latent_temp': [2.0, 0.1, 0.999995]},
|
| 34 |
+
'mms_1b': {'_name': 'wav2vec2', 'extractor_mode': 'layer_norm', 'encoder_layers': 48, 'encoder_embed_dim': 1280, 'encoder_ffn_embed_dim': 5120, 'encoder_attention_heads': 16, 'activation_fn': 'gelu', 'dropout': 0.0, 'attention_dropout': 0.0, 'activation_dropout': 0.0, 'encoder_layerdrop': 0.0, 'dropout_input': 0.1, 'dropout_features': 0.1, 'final_dim': 1024, 'layer_norm_first': True, 'conv_feature_layers': '[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512,2,2)] + [(512,2,2)]', 'conv_bias': True, 'logit_temp': 0.1, 'quantize_targets': True, 'quantize_input': False, 'same_quantizer': False, 'target_glu': False, 'feature_grad_mult': 1.0, 'quantizer_depth': 1, 'quantizer_factor': 3, 'latent_vars': 320, 'latent_groups': 2, 'latent_dim': 0, 'mask_length': 10, 'mask_prob': 0.65, 'mask_selection': 'static', 'mask_other': 0.0, 'no_mask_overlap': False, 'mask_min_space': 1, 'mask_channel_length': 10, 'mask_channel_prob': 0.0, 'mask_channel_before': False, 'mask_channel_selection': 'static', 'mask_channel_other': 0.0, 'no_mask_channel_overlap': False, 'mask_channel_min_space': 1, 'num_negatives': 100, 'negatives_from_everywhere': False, 'cross_sample_negatives': 0, 'codebook_negatives': 0, 'conv_pos': 128, 'conv_pos_groups': 16, 'latent_temp': [2.0, 0.1, 0.999995]},
|
| 35 |
+
'xlsr_1b': {'_name': 'wav2vec2', 'extractor_mode': 'layer_norm', 'encoder_layers': 48, 'encoder_embed_dim': 1280, 'encoder_ffn_embed_dim': 5120, 'encoder_attention_heads': 16, 'activation_fn': 'gelu', 'dropout': 0.0, 'attention_dropout': 0.0, 'activation_dropout': 0.0, 'encoder_layerdrop': 0.0, 'dropout_input': 0.1, 'dropout_features': 0.1, 'final_dim': 1024, 'layer_norm_first': True, 'conv_feature_layers': '[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512,2,2)] + [(512,2,2)]', 'conv_bias': True, 'logit_temp': 0.1, 'quantize_targets': True, 'quantize_input': False, 'same_quantizer': False, 'target_glu': False, 'feature_grad_mult': 1.0, 'quantizer_depth': 1, 'quantizer_factor': 3, 'latent_vars': 320, 'latent_groups': 2, 'latent_dim': 0, 'mask_length': 10, 'mask_prob': 0.65, 'mask_selection': 'static', 'mask_other': 0.0, 'no_mask_overlap': False, 'mask_min_space': 1, 'mask_channel_length': 10, 'mask_channel_prob': 0.0, 'mask_channel_before': False, 'mask_channel_selection': 'static', 'mask_channel_other': 0.0, 'no_mask_channel_overlap': False, 'mask_channel_min_space': 1, 'num_negatives': 100, 'negatives_from_everywhere': False, 'cross_sample_negatives': 0, 'codebook_negatives': 0, 'conv_pos': 128, 'conv_pos_groups': 16, 'latent_temp': [2.0, 0.1, 0.999995]},
|
| 36 |
+
'xlsr_2b': {'_name': 'wav2vec2', 'extractor_mode': 'layer_norm', 'encoder_layers': 48, 'encoder_embed_dim': 1920, 'encoder_ffn_embed_dim': 7680, 'encoder_attention_heads': 16, 'activation_fn': 'gelu', 'dropout': 0.0, 'attention_dropout': 0.0, 'activation_dropout': 0.0, 'encoder_layerdrop': 0.0, 'dropout_input': 0.1, 'dropout_features': 0.1, 'final_dim': 1024, 'layer_norm_first': True, 'conv_feature_layers': '[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512,2,2)] + [(512,2,2)]', 'conv_bias': True, 'logit_temp': 0.1, 'quantize_targets': True, 'quantize_input': False, 'same_quantizer': False, 'target_glu': False, 'feature_grad_mult': 1.0, 'quantizer_depth': 1, 'quantizer_factor': 3, 'latent_vars': 320, 'latent_groups': 2, 'latent_dim': 0, 'mask_length': 10, 'mask_prob': 0.65, 'mask_selection': 'static', 'mask_other': 0.0, 'no_mask_overlap': False, 'mask_min_space': 1, 'mask_channel_length': 10, 'mask_channel_prob': 0.0, 'mask_channel_before': False, 'mask_channel_selection': 'static', 'mask_channel_other': 0.0, 'no_mask_channel_overlap': False, 'mask_channel_min_space': 1, 'num_negatives': 100, 'negatives_from_everywhere': False, 'cross_sample_negatives': 0, 'codebook_negatives': 0, 'conv_pos': 128, 'conv_pos_groups': 16, 'latent_temp': [2.0, 0.1, 0.999995]},
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
# ----------------------------------------------------------------------------
|
| 40 |
+
# HuBERT-family configs (HuBERT extra-large)
|
| 41 |
+
# ----------------------------------------------------------------------------
|
| 42 |
+
HBT_INPUT_DIMS = {'hubert_large_ll60k': 1024, 'hubert_xlarge_ll60k': 1280}
|
| 43 |
+
HBT_DICTS = {'hubert_large_ll60k': 504, 'hubert_xlarge_ll60k': 504}
|
| 44 |
+
HBT_TASKS = {
|
| 45 |
+
'hubert_large_ll60k': {'_name': 'hubert_pretraining', 'data': '/checkpoint/wnhsu/data/librivox', 'labels': ['lyr9.km500'], 'label_dir': '/checkpoint/wnhsu/experiments/hubert/kmeans_20210121/km_dataset_librivox.model_iter_2.all', 'label_rate': 50, 'sample_rate': 16000, 'normalize': True, 'enable_padding': False, 'max_sample_size': 250000, 'min_sample_size': 32000, 'single_target': False, 'random_crop': True, 'pad_audio': False},
|
| 46 |
+
'hubert_xlarge_ll60k': {'_name': 'hubert_pretraining', 'data': '/checkpoint/wnhsu/data/librivox', 'labels': ['lyr9.km500'], 'label_dir': '/checkpoint/wnhsu/experiments/hubert/kmeans_20210121/km_dataset_librivox.model_iter_2.all', 'label_rate': 50, 'sample_rate': 16000, 'normalize': True, 'enable_padding': False, 'max_sample_size': 250000, 'min_sample_size': 32000, 'single_target': False, 'random_crop': True, 'pad_audio': False},
|
| 47 |
+
}
|
| 48 |
+
HBT_CONFIGS = {
|
| 49 |
+
'hubert_large_ll60k': {'_name': 'hubert', 'label_rate': 50, 'extractor_mode': 'layer_norm', 'encoder_layers': 24, 'encoder_embed_dim': 1024, 'encoder_ffn_embed_dim': 4096, 'encoder_attention_heads': 16, 'activation_fn': 'gelu', 'dropout': 0.0, 'attention_dropout': 0.0, 'activation_dropout': 0.0, 'encoder_layerdrop': 0.0, 'dropout_input': 0.0, 'dropout_features': 0.0, 'final_dim': 768, 'untie_final_proj': True, 'layer_norm_first': True, 'conv_feature_layers': '[(512,10,5)] + [(512,3,2)] * 4 + [(512,2,2)] * 2', 'conv_bias': False, 'logit_temp': 0.1, 'target_glu': False, 'feature_grad_mult': 1.0, 'mask_length': 10, 'mask_prob': 0.8, 'mask_selection': 'static', 'mask_other': 0.0, 'no_mask_overlap': False, 'mask_min_space': 1, 'mask_channel_length': 10, 'mask_channel_prob': 0.0, 'mask_channel_selection': 'static', 'mask_channel_other': 0.0, 'no_mask_channel_overlap': False, 'mask_channel_min_space': 1, 'conv_pos': 128, 'conv_pos_groups': 16, 'latent_temp': [2.0, 0.5, 0.999995], 'skip_masked': False, 'skip_nomask': True},
|
| 50 |
+
'hubert_xlarge_ll60k': {'_name': 'hubert', 'label_rate': 50, 'extractor_mode': 'layer_norm', 'encoder_layers': 48, 'encoder_embed_dim': 1280, 'encoder_ffn_embed_dim': 5120, 'encoder_attention_heads': 16, 'activation_fn': 'gelu', 'dropout': 0.0, 'attention_dropout': 0.0, 'activation_dropout': 0.0, 'encoder_layerdrop': 0.0, 'dropout_input': 0.0, 'dropout_features': 0.0, 'final_dim': 1024, 'untie_final_proj': True, 'layer_norm_first': True, 'conv_feature_layers': '[(512,10,5)] + [(512,3,2)] * 4 + [(512,2,2)] * 2', 'conv_bias': False, 'logit_temp': 0.1, 'target_glu': False, 'feature_grad_mult': 1.0, 'mask_length': 10, 'mask_prob': 0.8, 'mask_selection': 'static', 'mask_other': 0.0, 'no_mask_overlap': False, 'mask_min_space': 1, 'mask_channel_length': 10, 'mask_channel_prob': 0.0, 'mask_channel_selection': 'static', 'mask_channel_other': 0.0, 'no_mask_channel_overlap': False, 'mask_channel_min_space': 1, 'conv_pos': 128, 'conv_pos_groups': 16, 'latent_temp': [2.0, 0.5, 0.999995], 'skip_masked': False, 'skip_nomask': True},
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
# names that belong to each family
|
| 54 |
+
W2V_NAMES = set(W2V_CONFIGS)
|
| 55 |
+
HBT_NAMES = set(HBT_CONFIGS)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class _W2VSSL(torch.nn.Module):
|
| 59 |
+
def __init__(self, model_name: str):
|
| 60 |
+
super().__init__()
|
| 61 |
+
cfg = Wav2Vec2Config(**W2V_CONFIGS[model_name])
|
| 62 |
+
self.model = Wav2Vec2Model(cfg)
|
| 63 |
+
self.out_dim = W2V_INPUT_DIMS[model_name]
|
| 64 |
+
|
| 65 |
+
def extract_feat(self, x):
|
| 66 |
+
if x.ndim == 3:
|
| 67 |
+
x = x[:, :, 0]
|
| 68 |
+
return self.model(x, mask=False, features_only=True)['x']
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class _HBTSSL(torch.nn.Module):
|
| 72 |
+
def __init__(self, model_name: str):
|
| 73 |
+
super().__init__()
|
| 74 |
+
cfg = HubertConfig(**HBT_CONFIGS[model_name])
|
| 75 |
+
task = HubertPretrainingConfig(**HBT_TASKS[model_name])
|
| 76 |
+
dict_size = HBT_DICTS[model_name]
|
| 77 |
+
d = Dictionary()
|
| 78 |
+
for i in range(dict_size - len(d)):
|
| 79 |
+
d.add_symbol(i)
|
| 80 |
+
self.model = HubertModel(cfg, task, [d])
|
| 81 |
+
self.out_dim = HBT_INPUT_DIMS[model_name]
|
| 82 |
+
|
| 83 |
+
def extract_feat(self, x):
|
| 84 |
+
if x.ndim == 3:
|
| 85 |
+
x = x[:, :, 0]
|
| 86 |
+
return self.model(x, mask=False, features_only=True)['x']
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class Model(torch.nn.Module):
|
| 90 |
+
"""AntiDeepfake detector: SSL frontend + AdaptiveAvgPool1d + Linear(D, 2)."""
|
| 91 |
+
|
| 92 |
+
def __init__(self, model_name: str):
|
| 93 |
+
super().__init__()
|
| 94 |
+
if model_name in W2V_NAMES:
|
| 95 |
+
self.m_ssl = _W2VSSL(model_name)
|
| 96 |
+
elif model_name in HBT_NAMES:
|
| 97 |
+
self.m_ssl = _HBTSSL(model_name)
|
| 98 |
+
else:
|
| 99 |
+
raise ValueError(f"unknown model_name {model_name!r}")
|
| 100 |
+
self.adap_pool1d = torch.nn.AdaptiveAvgPool1d(output_size=1)
|
| 101 |
+
self.proj_fc = torch.nn.Linear(self.m_ssl.out_dim, 2)
|
| 102 |
+
|
| 103 |
+
def forward(self, wav):
|
| 104 |
+
emb = self.m_ssl.extract_feat(wav) # [B, T, D]
|
| 105 |
+
emb = emb.transpose(1, 2) # [B, D, T]
|
| 106 |
+
pooled = self.adap_pool1d(emb).view(emb.size(0), -1) # [B, D]
|
| 107 |
+
return self.proj_fc(pooled) # [B, 2] = [fake, real]
|
arena_entry.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# How Arena drivers load this model (discovered from the repo; no central registry needed)
|
| 2 |
+
module: xls_r_2b_antideepfake_nda
|
| 3 |
+
class: XLSR2BAntiDeepfakeNDA
|
| 4 |
+
trt_module: trt_xls_r_2b_antideepfake_nda
|
| 5 |
+
trt_class: XLSR2BAntiDeepfakeNDATRT
|
| 6 |
+
sample_rate: 16000
|
| 7 |
+
devices: 1
|
implementation-notes.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Implementation notes — XLS-R-2B-AntiDeepfake-NDA
|
| 2 |
+
|
| 3 |
+
- **Source:** nii-yamagishilab/AntiDeepfake (arXiv:2506.21090). Backbone `xlsr_2b`.
|
| 4 |
+
- **Load path:** `_net.Model("xlsr_2b")` builds the fairseq SSL frontend from the
|
| 5 |
+
vendored config, then `model.safetensors` (from our org copy, commit-pinned)
|
| 6 |
+
is loaded with `strict=True`. Key match verified family-wide (e.g. w2v_small:
|
| 7 |
+
220/220 keys, 0 missing/unexpected).
|
| 8 |
+
- **Score:** `logits[:, 1]` = real logit = bona fide (source `main.py`:
|
| 9 |
+
`scores = preds[:, 1]`; `evaluation.py`: Score=[fake, real], label 1=real).
|
| 10 |
+
- **Preprocessing deviation:** the paper evaluates on the *whole* utterance with
|
| 11 |
+
per-utterance `layer_norm` and **no trim**. We instead take the **first 4 s
|
| 12 |
+
(64 000 samples)**, tile-repeat if shorter, `layer_norm` over that window, and
|
| 13 |
+
batch. Reason: the whole-utterance, batch-1 path is far too slow across 14
|
| 14 |
+
models. The window makes every clip uniform length so batching introduces no
|
| 15 |
+
adaptive-pool padding artifact. **EER will not match the paper.**
|
| 16 |
+
- **Precision:** forward under CUDA autocast fp16 (matches the fp16 training
|
| 17 |
+
regime; keeps activation memory low for the large backbones); input layer_norm
|
| 18 |
+
computed in fp32.
|
| 19 |
+
- **GPUs:** RTX 4070 Ti Super only (idx 1 & 3, `CUDA_DEVICE_ORDER=PCI_BUS_ID`).
|
| 20 |
+
- **Restriction:** STRICTLY PROHIBITED on the model's in-domain corpora — see
|
| 21 |
+
README. Arena runs ArAD + In-the-Wild only.
|
meta.yaml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
system:
|
| 2 |
+
name: "XLS-R-2B-AntiDeepfake-NDA"
|
| 3 |
+
slug: "xls-r-2b-antideepfake-nda"
|
| 4 |
+
description: >
|
| 5 |
+
AntiDeepfake detector (XLS-R 2B backbone): a self-supervised speech
|
| 6 |
+
foundation model post-trained for deepfake/spoof detection, with an
|
| 7 |
+
AdaptiveAvgPool1d + single fully-connected layer head over the SSL features.
|
| 8 |
+
Released by nii-yamagishilab (arXiv:2506.21090). Trained **without** data augmentation (NDA variant). Checkpoint
|
| 9 |
+
copied bit-exactly from nii-yamagishilab/xls-r-2b-anti-deepfake-nda. Evaluated here with a deterministic first-4 s
|
| 10 |
+
window and batching (NOT the paper's whole-utterance protocol).
|
| 11 |
+
code: "https://github.com/nii-yamagishilab/AntiDeepfake"
|
| 12 |
+
checkpoint: "https://huggingface.co/SpeechAntiSpoofingBenchmarks/XLS-R-2B-AntiDeepfake-NDA"
|
| 13 |
+
params_millions: 2160.0
|
| 14 |
+
paper:
|
| 15 |
+
arxiv_id: "2506.21090"
|
| 16 |
+
url: "https://arxiv.org/abs/2506.21090"
|
| 17 |
+
bibtex: |
|
| 18 |
+
@article{ge2025posttraining,
|
| 19 |
+
title={Post-training for Deepfake Speech Detection},
|
| 20 |
+
author={Ge, Wanying and Wang, Xin and Kawahara, Tomoki and Yamamoto, Yuto and Delgado, Hector and Todisco, Massimiliano and Evans, Nicholas and Yamagishi, Junichi},
|
| 21 |
+
journal={arXiv preprint arXiv:2506.21090},
|
| 22 |
+
year={2025}
|
| 23 |
+
}
|
| 24 |
+
notes: >
|
| 25 |
+
score = output logit for class 1 (real / bona fide); higher = more bona fide.
|
| 26 |
+
Backbone built from the source fairseq config (xlsr_2b); the released
|
| 27 |
+
model.safetensors overwrites every weight (220-key exact match family-wide).
|
| 28 |
+
Input: fixed first 64000 samples (4.0 s @ 16 kHz), tile-repeated if shorter,
|
| 29 |
+
per-utterance layer_norm; no resampling. Checkpoint license: CC BY-NC-SA 4.0.
|
| 30 |
+
STRICTLY PROHIBITED on the model's in-domain corpora (see README); Arena runs
|
| 31 |
+
ArAD + In-the-Wild only.
|
sweep.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# sweep.py — batch-size sweep for XLS-R-2B-AntiDeepfake-NDA on a single RTX 4070 Ti Super
|
| 2 |
+
# Usage: CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=1 python sweep.py
|
| 3 |
+
import time, numpy as np, torch
|
| 4 |
+
from xls_r_2b_antideepfake_nda import XLSR2BAntiDeepfakeNDA, crop_fixed
|
| 5 |
+
|
| 6 |
+
def main():
|
| 7 |
+
m = XLSR2BAntiDeepfakeNDA(); m.load()
|
| 8 |
+
rng = np.random.default_rng(0)
|
| 9 |
+
pool = [rng.standard_normal(64000).astype(np.float32) for _ in range(256)]
|
| 10 |
+
for bs in [1, 2, 4, 8, 16, 24, 32, 48, 64]:
|
| 11 |
+
try:
|
| 12 |
+
torch.cuda.reset_peak_memory_stats()
|
| 13 |
+
t0 = time.time(); n = 0
|
| 14 |
+
for i in range(0, 128, bs):
|
| 15 |
+
batch = pool[i:i+bs]
|
| 16 |
+
m.score_batch(batch, [16000]*len(batch)); n += len(batch)
|
| 17 |
+
dt = time.time() - t0
|
| 18 |
+
peak = torch.cuda.max_memory_allocated()/1e9
|
| 19 |
+
print(f"bs={bs:3d} {n/dt:7.1f} utt/s peak={peak:5.2f} GB")
|
| 20 |
+
except RuntimeError as e:
|
| 21 |
+
print(f"bs={bs:3d} OOM/err: {str(e)[:60]}"); torch.cuda.empty_cache(); break
|
| 22 |
+
m.unload()
|
| 23 |
+
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
main()
|
test_xls_r_2b_antideepfake_nda.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# test_xls_r_2b_antideepfake_nda.py — smoke test for XLS-R-2B-AntiDeepfake-NDA
|
| 2 |
+
import numpy as np
|
| 3 |
+
from xls_r_2b_antideepfake_nda import XLSR2BAntiDeepfakeNDA, crop_fixed, _WINDOW
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_crop_fixed_long_and_short():
|
| 7 |
+
long = np.random.randn(70000).astype(np.float32)
|
| 8 |
+
short = np.random.randn(8000).astype(np.float32)
|
| 9 |
+
assert crop_fixed(long).shape == (_WINDOW,)
|
| 10 |
+
assert crop_fixed(short).shape == (_WINDOW,)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_load_and_batch():
|
| 14 |
+
m = XLSR2BAntiDeepfakeNDA()
|
| 15 |
+
m.load()
|
| 16 |
+
rng = np.random.default_rng(0)
|
| 17 |
+
audios = [rng.standard_normal(np.random.randint(8000, 70000)).astype(np.float32)
|
| 18 |
+
for _ in range(3)]
|
| 19 |
+
srs = [16000] * 3
|
| 20 |
+
# batch > 1
|
| 21 |
+
out = m.score_batch(audios, srs)
|
| 22 |
+
assert len(out) == 3 and all(np.isfinite(out))
|
| 23 |
+
# batch == 1 must agree with the in-batch score (determinism / no padding bug)
|
| 24 |
+
one = m.score_batch([audios[0]], [16000])[0]
|
| 25 |
+
assert abs(one - out[0]) < 1e-2, (one, out[0])
|
| 26 |
+
m.unload()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
test_crop_fixed_long_and_short()
|
| 31 |
+
test_load_and_batch()
|
| 32 |
+
print("OK")
|
trt_xls_r_2b_antideepfake_nda.py
CHANGED
|
@@ -74,13 +74,26 @@ def load_model():
|
|
| 74 |
return m
|
| 75 |
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
def real_audio(n=64):
|
| 78 |
"""Decode up to n real 16 kHz mono utterances from PARITY_DATASET/data/*.parquet."""
|
| 79 |
import pyarrow.parquet as pq
|
| 80 |
import soundfile as sf
|
| 81 |
import torchaudio.functional as AF
|
| 82 |
|
| 83 |
-
data_dir =
|
| 84 |
files = sorted(data_dir.glob("test-*.parquet")) or sorted(data_dir.glob("*.parquet"))
|
| 85 |
out = []
|
| 86 |
for f in files:
|
|
|
|
| 74 |
return m
|
| 75 |
|
| 76 |
|
| 77 |
+
def _parity_data_dir() -> Path:
|
| 78 |
+
"""Dir with the parity clips (<PARITY_DATASET> data/*.parquet; the clips used are unchanged).
|
| 79 |
+
|
| 80 |
+
$ARENA_PARITY_DIR if set, else $ARENA_DATASETS/arena/<PARITY_DATASET>/data if ARENA_DATASETS is set,
|
| 81 |
+
else the legacy sibling layout <repo>/../<PARITY_DATASET>/data.
|
| 82 |
+
"""
|
| 83 |
+
if os.environ.get("ARENA_PARITY_DIR"):
|
| 84 |
+
return Path(os.environ["ARENA_PARITY_DIR"])
|
| 85 |
+
if os.environ.get("ARENA_DATASETS"):
|
| 86 |
+
return Path(os.environ["ARENA_DATASETS"]) / "arena" / PARITY_DATASET / "data"
|
| 87 |
+
return HERE.parent / PARITY_DATASET / "data"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
def real_audio(n=64):
|
| 91 |
"""Decode up to n real 16 kHz mono utterances from PARITY_DATASET/data/*.parquet."""
|
| 92 |
import pyarrow.parquet as pq
|
| 93 |
import soundfile as sf
|
| 94 |
import torchaudio.functional as AF
|
| 95 |
|
| 96 |
+
data_dir = _parity_data_dir()
|
| 97 |
files = sorted(data_dir.glob("test-*.parquet")) or sorted(data_dir.glob("*.parquet"))
|
| 98 |
out = []
|
| 99 |
for f in files:
|
xls_r_2b_antideepfake_nda.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# xls_r_2b_antideepfake_nda.py
|
| 2 |
+
# AntiDeepfake collection wrapper — XLS-R-2B-AntiDeepfake-NDA
|
| 3 |
+
# Backbone cfg: xlsr_2b. Score = real logit (index 1); higher = bona fide.
|
| 4 |
+
# Deliberate eval deviation from the paper: fixed first-4 s window + batching
|
| 5 |
+
# (paper uses the whole utterance). See implementation-notes.md.
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
from safetensors.torch import load_file
|
| 13 |
+
|
| 14 |
+
from speech_spoof_bench.model import AntiSpoofingModel
|
| 15 |
+
from _net import Model as AntiDeepfakeNet
|
| 16 |
+
from _hub import local_or_hub
|
| 17 |
+
|
| 18 |
+
_CFG_KEY = "xlsr_2b"
|
| 19 |
+
_REPO = "SpeechAntiSpoofingBenchmarks/XLS-R-2B-AntiDeepfake-NDA"
|
| 20 |
+
_REVISION = "9d334730de258737b9fd100e39597b1e824ad034" # commit-pinned after checkpoint copy
|
| 21 |
+
_WINDOW = 64000 # 4.0 s @ 16 kHz
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def crop_fixed(x: np.ndarray, n: int = _WINDOW) -> np.ndarray:
|
| 25 |
+
"""Deterministic eval window: first n samples; tile-repeat if shorter."""
|
| 26 |
+
x = np.asarray(x, dtype=np.float32).reshape(-1)
|
| 27 |
+
k = x.shape[0]
|
| 28 |
+
if k >= n:
|
| 29 |
+
return x[:n]
|
| 30 |
+
reps = n // k + 1
|
| 31 |
+
return np.tile(x, reps)[:n].astype(np.float32)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class XLSR2BAntiDeepfakeNDA(AntiSpoofingModel):
|
| 35 |
+
name = "XLS-R-2B-AntiDeepfake-NDA"
|
| 36 |
+
expected_sample_rate = 16000
|
| 37 |
+
batch_size = 8 # sweep TBD on RTX 4070 Ti Super; nominal for xlsr_2b
|
| 38 |
+
|
| 39 |
+
def load(self) -> None:
|
| 40 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 41 |
+
net = AntiDeepfakeNet(_CFG_KEY)
|
| 42 |
+
# model.safetensors next to this file (repo snapshot/clone) if present, else the commit-pinned Hub file
|
| 43 |
+
ckpt = local_or_hub(os.path.dirname(os.path.abspath(__file__)), "model.safetensors", _REPO, revision=_REVISION)
|
| 44 |
+
net.load_state_dict(load_file(ckpt), strict=True)
|
| 45 |
+
self.net = net.to(self.device).eval()
|
| 46 |
+
|
| 47 |
+
@torch.no_grad()
|
| 48 |
+
def score_batch(self, audios, srs):
|
| 49 |
+
x = np.stack([crop_fixed(a) for a in audios]) # [B, 64000]
|
| 50 |
+
xt = torch.from_numpy(x).to(self.device, torch.float32)
|
| 51 |
+
# per-utterance layer-norm over the 4 s window (source preprocessing)
|
| 52 |
+
xt = torch.nn.functional.layer_norm(xt, (xt.shape[-1],))
|
| 53 |
+
if self.device == "cuda":
|
| 54 |
+
with torch.autocast("cuda", dtype=torch.float16):
|
| 55 |
+
logits = self.net(xt)
|
| 56 |
+
else:
|
| 57 |
+
logits = self.net(xt)
|
| 58 |
+
logits = logits.reshape(-1, 2).float() # [B, 2]=[fake, real]
|
| 59 |
+
return logits[:, 1].cpu().tolist() # real logit = bona fide
|
| 60 |
+
|
| 61 |
+
def unload(self) -> None:
|
| 62 |
+
self.net = None
|