File size: 13,018 Bytes
4f9b1ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"""Shared network definition for the AntiDeepfake collection wrappers.

Vendored from nii-yamagishilab/AntiDeepfake (models/W2V.py, models/HBT.py,
models/W2V_configs.py, models/HBT_configs.py) so the state-dict keys
(`m_ssl.model.*`, `proj_fc.*`) match the released `model.safetensors`
bit-for-bit (verified: 220/220 keys, 0 missing/unexpected on w2v_small).

Architecture (identical for every backbone): a fairseq SSL frontend built from
the explicit config below, AdaptiveAvgPool1d(1) over time, then Linear(D, 2).
Output logits are [fake, real]; the bona-fide score is logit[:, 1] (real).

Upstream license: code BSD-3-Clause, checkpoints CC BY-NC-SA 4.0.
"""
from __future__ import annotations

import torch
from fairseq.models.wav2vec import Wav2Vec2Model, Wav2Vec2Config
from fairseq.models.hubert import HubertModel, HubertConfig
from fairseq.tasks.hubert_pretraining import HubertPretrainingConfig
from fairseq.data import Dictionary

# ----------------------------------------------------------------------------
# wav2vec2-family configs (wav2vec small/large, MMS 300M/1B, XLS-R 1B/2B)
# ----------------------------------------------------------------------------
W2V_INPUT_DIMS = {
    'w2v_small': 768, 'w2v_large': 1024, 'mms_300m': 1024,
    'mms_1b': 1280, 'xlsr_1b': 1280, 'xlsr_2b': 1920,
}

W2V_CONFIGS = {
    '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]},
    '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]},
    '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]},
    '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]},
    '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]},
    '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]},
}

# ----------------------------------------------------------------------------
# HuBERT-family configs (HuBERT extra-large)
# ----------------------------------------------------------------------------
HBT_INPUT_DIMS = {'hubert_large_ll60k': 1024, 'hubert_xlarge_ll60k': 1280}
HBT_DICTS = {'hubert_large_ll60k': 504, 'hubert_xlarge_ll60k': 504}
HBT_TASKS = {
    '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},
    '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},
}
HBT_CONFIGS = {
    '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},
    '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},
}

# names that belong to each family
W2V_NAMES = set(W2V_CONFIGS)
HBT_NAMES = set(HBT_CONFIGS)


class _W2VSSL(torch.nn.Module):
    def __init__(self, model_name: str):
        super().__init__()
        cfg = Wav2Vec2Config(**W2V_CONFIGS[model_name])
        self.model = Wav2Vec2Model(cfg)
        self.out_dim = W2V_INPUT_DIMS[model_name]

    def extract_feat(self, x):
        if x.ndim == 3:
            x = x[:, :, 0]
        return self.model(x, mask=False, features_only=True)['x']


class _HBTSSL(torch.nn.Module):
    def __init__(self, model_name: str):
        super().__init__()
        cfg = HubertConfig(**HBT_CONFIGS[model_name])
        task = HubertPretrainingConfig(**HBT_TASKS[model_name])
        dict_size = HBT_DICTS[model_name]
        d = Dictionary()
        for i in range(dict_size - len(d)):
            d.add_symbol(i)
        self.model = HubertModel(cfg, task, [d])
        self.out_dim = HBT_INPUT_DIMS[model_name]

    def extract_feat(self, x):
        if x.ndim == 3:
            x = x[:, :, 0]
        return self.model(x, mask=False, features_only=True)['x']


class Model(torch.nn.Module):
    """AntiDeepfake detector: SSL frontend + AdaptiveAvgPool1d + Linear(D, 2)."""

    def __init__(self, model_name: str):
        super().__init__()
        if model_name in W2V_NAMES:
            self.m_ssl = _W2VSSL(model_name)
        elif model_name in HBT_NAMES:
            self.m_ssl = _HBTSSL(model_name)
        else:
            raise ValueError(f"unknown model_name {model_name!r}")
        self.adap_pool1d = torch.nn.AdaptiveAvgPool1d(output_size=1)
        self.proj_fc = torch.nn.Linear(self.m_ssl.out_dim, 2)

    def forward(self, wav):
        emb = self.m_ssl.extract_feat(wav)   # [B, T, D]
        emb = emb.transpose(1, 2)            # [B, D, T]
        pooled = self.adap_pool1d(emb).view(emb.size(0), -1)  # [B, D]
        return self.proj_fc(pooled)          # [B, 2] = [fake, real]