Parveshiiii commited on
Commit
09dcb2a
·
verified ·
1 Parent(s): 49da1ad

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assistant.wav filter=lfs diff=lfs merge=lfs -text
37
+ assets/banner.jpeg filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,257 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ pipeline_tag: audio-classification
4
+ library_name: transformers
5
+ language:
6
+ - multilingual
7
+
8
+ tags:
9
+ - audio-deepfake
10
+ - deepfake-detection
11
+ - deepfake
12
+ - voice-cloning
13
+ - anti-spoofing
14
+ - asvspoof
15
+ - wav2vec2
16
+ - speech
17
+ - audio
18
+ - synthetic-voice
19
+ - voice-conversion
20
+ - tts-detection
21
+ - trust-and-safety
22
+ - security
23
+ - SoTA
24
+ - Modotte
25
+
26
+ inference:
27
+ parameters:
28
+ function_to_apply: "softmax"
29
  ---
30
+
31
+ ## Modotte
32
+
33
+ <p align="center">
34
+ <img
35
+ src="https://huggingface.co/Modotte/AIRealNet-Audio/resolve/main/assets/banner.jpeg"
36
+ alt="AIRealNet-Audio Banner"
37
+ width="95%"
38
+ style="border-radius:15px;"
39
+ />
40
+ </p>
41
+
42
+ ## Overview
43
+
44
+ > This is the future iteration of [AIRealNet](https://huggingface.co/Modotte/AIRealNet)
45
+
46
+ In an era of rapidly advancing AI-generated speech, voice cloning, and audio deepfakes, the need for reliable detection tools has never been higher. **AIRealNet-Audio** is a binary audio classifier designed to distinguish AI-generated / spoofed audio from real human speech.
47
+
48
+ It is built on a Wav2Vec-based audio encoder that processes audio in fixed **12-second chunks**. The model uses a default decision threshold of **50%**, which can be adjusted based on your use case.
49
+
50
+ A key design choice addresses a common failure mode of public deepfake detectors: models quickly learn a shortcut based on embedding vector length (magnitude). To prevent this, all embeddings from the base model are **L1-normalized onto the unit hypersphere**, forcing the classifier to rely purely on angular (directional) information rather than magnitude.
51
+
52
+ - **Class 0**: AI-generated / spoof audio
53
+ - **Class 1**: Real human audio
54
+
55
+ **Default decision threshold**: 0.5 (tune per use-case).
56
+
57
+ ---
58
+
59
+ ## Architecture
60
+
61
+ This is a **Wav2Vec-based audio encoder** operating at **16 kHz**, paired with a projection layer that maps its base features of dimension **768** (pooled from shape `[T, 768]`) down to **256**. This 256-dimensional representation is the expected input shape for the classification head, which is a **single-layer MLP** producing 2 output logits (with softmax applied during inference).
62
+
63
+ The core innovation of this architecture is the **dual L1 unit-norm** applied to the model features:
64
+
65
+ 1. The base features are L1-normalized **once** when passed to the projector.
66
+ 2. The projected features are L1-normalized **again** when passed to the classification head.
67
+
68
+ This dual-hypersphere design completely eliminates size (magnitude) bias.
69
+
70
+ ### Why Dual L1 Normalization?
71
+
72
+ Most studies show that deepfake embeddings tend to cluster in a specific region of feature space **and** exhibit a characteristic vector magnitude. As a result, many detectors learn a shortcut: they simply detect the length of the embedding vector (or its presence in a particular cluster) instead of learning meaningful acoustic or spectral cues.
73
+
74
+ To eliminate this shortcut, we force **every** feature vector onto the unit hypersphere via L1 normalization. Consequently:
75
+
76
+ - The classification head has only one meaningful signal left to learn from — the **direction (θ)** of the vector.
77
+ - Because all vectors lie on the hypersphere, the opportunity for models to exploit magnitude-based or region-specific clustering is drastically reduced.
78
+
79
+ This approach is similar in spirit to **GenD**, which applied a single L1 normalization onto the unit hypersphere. AIRealNet-Audio extends the idea by applying the normalization **twice** (dual hypersphere), once before the projector and once before the head.
80
+
81
+ ### Training Behavior
82
+
83
+ When training **without** L1 normalization we observed a consistent pattern: the model performs well in the early stages, then begins to degrade after a fixed number of steps — even after extensive hyperparameter tuning and aggressive learning-rate reduction aimed at slower convergence.
84
+
85
+ With the **dual-hypersphere** architecture the opposite occurs:
86
+
87
+ - Steady upward trend in performance.
88
+ - The model continues to improve with each successive step instead of collapsing after a few thousand steps.
89
+
90
+ **Loss per step**
91
+
92
+ <p align="center">
93
+ <img
94
+ src="https://huggingface.co/Modotte/AIRealNet-Audio/resolve/main/assets/loss.png"
95
+ alt="loss Banner"
96
+ width="90%"
97
+ style="border-radius:15px;"
98
+ />
99
+ </p>
100
+
101
+ **Accuracy per 1000 steps**
102
+
103
+ <p align="center">
104
+ <img
105
+ src="https://huggingface.co/Modotte/AIRealNet-Audio/resolve/main/assets/accuracy.png"
106
+ alt="accuracy Banner"
107
+ width="90%"
108
+ style="border-radius:15px;"
109
+ />
110
+ </p>
111
+
112
+ ---
113
+
114
+ ## Training Data
115
+
116
+ - AI-generated speech produced by more than **100 different TTS / voice-cloning systems**.
117
+ - Large collection of real human speech drawn from varied recording conditions and sources.
118
+ - On-the-fly augmentations including multiple compression codecs, bitrate changes, and additive noise.
119
+ - Separate balanced evaluation and development sets used for monitoring.
120
+
121
+ The combination of high TTS diversity and aggressive augmentation is intended to force the model to learn genuine synthesis artifacts rather than dataset-specific fingerprints.
122
+
123
+ ---
124
+
125
+ ## Limitations
126
+
127
+ - Very short utterances (significantly under 12 s) must be padded or repeated; performance on extremely short clips may be lower.
128
+ - Highly adversarial or “nano-edit” modifications of real audio remain challenging.
129
+ - Completely unseen generators or extreme domain shifts (e.g., heavy telephony distortion not seen during training) can still reduce accuracy.
130
+ - The model is a probabilistic detector; it should not be used as the sole evidence in high-stakes forensic or legal settings without human review.
131
+
132
+ ## Performance
133
+
134
+ Across a range of standard and challenging evaluation sets the model demonstrates strong generalization. In most evaluation datasets AIRealNet-Audio maintains an **Equal error rate (EER) well below 6%**.
135
+
136
+ > We eliminated audio files below 3sec as model is trained on 12-seconds.
137
+
138
+ | Evaluation Dataset | EER (%) |
139
+ |------------------------|---------|
140
+ | ASVspoof5 | 1.21 |
141
+ | Voxness | 1.48 |
142
+ | Malaad | 2.11 |
143
+ | ASVspoof2019 DF | 3.14 |
144
+ | In-the-Wild | 3.64 |
145
+
146
+ **Additional training-time observations**
147
+ - After 2 epochs: ~**0.99 accuracy** on both the held-out evaluation set and the development set.
148
+ - Subsequent checkpoints continue to show steady gains in accuracy (see accuracy curve above).
149
+ - Training without the dual L1 normalization exhibits the classic early-peak-then-degradation pattern; the dual-hypersphere design removes this failure mode.
150
+
151
+ *Note*: Extremely high numbers on controlled evaluation sets are expected. Real-world performance depends on the distribution of generators and acoustic conditions encountered at deployment time. Always calibrate the decision threshold on data that matches your target domain.
152
+
153
+ ---
154
+
155
+ ## Usage
156
+
157
+ ### Sample Audio
158
+ The following sample was generated by **Gemini-3.8 Flash TTS** (AI-generated speech):
159
+
160
+ <audio controls src="https://huggingface.co/Modotte/AIRealNet-Audio/resolve/main/assets/assistant.wav"></audio>
161
+
162
+ ### Quick Inference
163
+
164
+ ```python
165
+ from transformers import pipeline
166
+
167
+ pipe = pipeline(
168
+ "audio-classification",
169
+ model="Modotte/AIRealNet-Audio",
170
+ trust_remote_code=True
171
+ )
172
+
173
+ result = pipe(
174
+ "https://cdn-uploads.huggingface.co/production/uploads/677fcdf29b9a9863eba3f29f/C2llrmFhlWx-oryC9wF6f.wav"
175
+ )
176
+ print(result)
177
+ ```
178
+
179
+ **Expected output:**
180
+ ```python
181
+ [
182
+ {'score': 0.9979, 'label': 'AIVoice'},
183
+ {'score': 0.0021, 'label': 'HumanVoice'}
184
+ ]
185
+ ```
186
+
187
+ | Label | Meaning |
188
+ |-------------|--------------------------|
189
+ | `AIVoice` | AI-generated / spoof audio |
190
+ | `HumanVoice`| Real human speech |
191
+
192
+ Default decision threshold is **0.5**. You can adjust it according to your precision/recall needs.
193
+
194
+ ### Notes for Production Use
195
+ 1. Resample input to **16 kHz mono**.
196
+ 2. Segment long recordings into **12-second chunks** (the training chunk size).
197
+ 3. Aggregate chunk-level scores (mean, max, or calibrated fusion) as needed.
198
+
199
+ ---
200
+
201
+ ## Intended Use
202
+
203
+ - Detection of AI-generated / spoofed speech on social media, messaging platforms, call centers, and research datasets.
204
+ - Assistance for content moderators, journalists, fact-checkers, and platform trust-and-safety teams.
205
+ - Research baseline for audio deepfake detection under a hyperspherical feature constraint.
206
+
207
+ Not intended as the sole source of evidence in legal, forensic, or high-stakes verification scenarios without corroborating human analysis.
208
+
209
+ ---
210
+
211
+ ## Ethical Considerations
212
+
213
+ - Training data construction followed the same privacy-first principles used for the original AIRealNet image model (no personal or sensitive recordings).
214
+ - Users should treat model scores as one signal among many and always apply human review near the decision threshold.
215
+ - The model card explicitly documents the dual-hypersphere design and the known length-bias failure mode so that downstream users understand both the strengths and the residual risks.
216
+
217
+ ---
218
+
219
+ ## How It Works
220
+
221
+ 1. Input audio is resampled to 16 kHz and segmented into 12-second chunks.
222
+ 2. A Wav2Vec encoder extracts frame-level features [T, 768].
223
+ 3. Features are mean-pooled, L1-normalized, and projected to 256 dimensions.
224
+ 4. The 256-dimensional vector is L1-normalized a second time and passed through a linear classification head.
225
+ 5. Softmax yields class probabilities; a threshold (default 0.5) produces the final binary decision.
226
+
227
+ ---
228
+
229
+ ## Future Work
230
+
231
+ - Improve robustness to very short utterances and adversarial nano-edits.
232
+ - Expand coverage to additional languages and emerging TTS / voice-conversion systems.
233
+ - Investigate multi-modal (audio + video / metadata) detection.
234
+ - Explore variable-length or streaming-friendly variants of the dual-hypersphere constraint.
235
+
236
+ ---
237
+
238
+ ## Citation
239
+
240
+ ```bibtex
241
+ @misc{Modotte_AIRealNet_Audio_2025,
242
+ title = {AIRealNet-Audio: Dual-Hypersphere Constrained Wav2Vec for Detecting AI-Generated vs Real Speech},
243
+ author = {Parvesh Rawal},
244
+ year = {2025},
245
+ publisher = {Hugging Face},
246
+ url = {https://huggingface.co/Modotte/AIRealNet-Audio}
247
+ }
248
+ ```
249
+
250
+ ---
251
+
252
+ ## References
253
+
254
+ - Yermakov, A., Cech, J., Matas, J., & Fritz, M. (2026). *Deepfake Detection that Generalizes Across Benchmarks* (GenD). Proceedings of the IEEE/CVF Winter Conference on Applications of Computer Vision (WACV).
255
+ [arXiv:2508.06248](https://arxiv.org/abs/2508.06248) · [GitHub](https://github.com/yermandy/GenD)
256
+ - Microsoft / Facebook Wav2Vec 2.0 and related self-supervised speech models.
257
+ - [AIRealNet](https://huggingface.co/Modotte/AIRealNet) — the image counterpart that motivated this audio extension.
assets/accuracy.png ADDED
assets/assistant.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:976d73c3fe17f77ba1626c44bf3cf0f10a32d4c73e8057c6e426a4696fbee6da
3
+ size 1384364
assets/banner.jpeg ADDED

Git LFS Details

  • SHA256: 707280e3c0a60c7d82a245cfafc7b0006f75c3130d69e2d09c271b45b77bf38d
  • Pointer size: 131 Bytes
  • Size of remote file: 531 kB
assets/loss.png ADDED
config.json ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "facebook/wav2vec2-base",
3
+ "activation_dropout": 0.0,
4
+ "adapter_attn_dim": null,
5
+ "adapter_kernel_size": 3,
6
+ "adapter_stride": 2,
7
+ "add_adapter": false,
8
+ "apply_spec_augment": true,
9
+ "architectures": [
10
+ "Wav2Vec2DualHypersphereForAudioClassification"
11
+ ],
12
+ "auto_map": {
13
+ "AutoConfig": "configuration.Wav2Vec2DualHypersphereConfig",
14
+ "AutoModelForAudioClassification": "modeling.Wav2Vec2DualHypersphereForAudioClassification"
15
+ },
16
+ "attention_dropout": 0.1,
17
+ "bos_token_id": 1,
18
+ "classifier_proj_size": 256,
19
+ "codevector_dim": 256,
20
+ "contrastive_logits_temperature": 0.1,
21
+ "conv_bias": false,
22
+ "conv_dim": [
23
+ 512,
24
+ 512,
25
+ 512,
26
+ 512,
27
+ 512,
28
+ 512,
29
+ 512
30
+ ],
31
+ "conv_kernel": [
32
+ 10,
33
+ 3,
34
+ 3,
35
+ 3,
36
+ 3,
37
+ 2,
38
+ 2
39
+ ],
40
+ "conv_stride": [
41
+ 5,
42
+ 2,
43
+ 2,
44
+ 2,
45
+ 2,
46
+ 2,
47
+ 2
48
+ ],
49
+ "ctc_loss_reduction": "sum",
50
+ "ctc_zero_infinity": false,
51
+ "diversity_loss_weight": 0.1,
52
+ "do_stable_layer_norm": false,
53
+ "eos_token_id": 2,
54
+ "feat_extract_activation": "gelu",
55
+ "feat_extract_norm": "group",
56
+ "feat_proj_dropout": 0.1,
57
+ "feat_quantizer_dropout": 0.0,
58
+ "final_dropout": 0.0,
59
+ "freeze_feat_extract_train": true,
60
+ "hidden_act": "gelu",
61
+ "hidden_dropout": 0.1,
62
+ "hidden_size": 768,
63
+ "id2label": {
64
+ "0": "AIVoice",
65
+ "1": "HumanVoice"
66
+ },
67
+ "initializer_range": 0.02,
68
+ "intermediate_size": 3072,
69
+ "label2id": {
70
+ "AIVoice": "0",
71
+ "HumanVoice": "1"
72
+ },
73
+ "layer_norm_eps": 1e-05,
74
+ "layerdrop": 0.0,
75
+ "mask_channel_length": 10,
76
+ "mask_channel_min_space": 1,
77
+ "mask_channel_other": 0.0,
78
+ "mask_channel_prob": 0.0,
79
+ "mask_channel_selection": "static",
80
+ "mask_feature_length": 10,
81
+ "mask_feature_min_masks": 0,
82
+ "mask_feature_prob": 0.0,
83
+ "mask_time_length": 10,
84
+ "mask_time_min_masks": 2,
85
+ "mask_time_min_space": 1,
86
+ "mask_time_other": 0.0,
87
+ "mask_time_prob": 0.05,
88
+ "mask_time_selection": "static",
89
+ "model_type": "wav2vec2-dual-hypersphere",
90
+ "no_mask_channel_overlap": false,
91
+ "no_mask_time_overlap": false,
92
+ "num_adapter_layers": 3,
93
+ "num_attention_heads": 12,
94
+ "num_codevector_groups": 2,
95
+ "num_codevectors_per_group": 320,
96
+ "num_conv_pos_embedding_groups": 16,
97
+ "num_conv_pos_embeddings": 128,
98
+ "num_feat_extract_layers": 7,
99
+ "num_hidden_layers": 12,
100
+ "num_negatives": 100,
101
+ "output_hidden_size": 768,
102
+ "pad_token_id": 0,
103
+ "proj_codevector_dim": 256,
104
+ "tdnn_dilation": [
105
+ 1,
106
+ 2,
107
+ 3,
108
+ 1,
109
+ 1
110
+ ],
111
+ "tdnn_dim": [
112
+ 512,
113
+ 512,
114
+ 512,
115
+ 512,
116
+ 1500
117
+ ],
118
+ "tdnn_kernel": [
119
+ 5,
120
+ 3,
121
+ 3,
122
+ 1,
123
+ 1
124
+ ],
125
+ "torch_dtype": "float32",
126
+ "transformers_version": "4.39.2",
127
+ "use_weighted_layer_sum": false,
128
+ "vocab_size": 32,
129
+ "xvector_output_dim": 512
130
+ }
configuration.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import Wav2Vec2Config
2
+
3
+
4
+ class Wav2Vec2DualHypersphereConfig(Wav2Vec2Config):
5
+ model_type = "wav2vec2-dual-hypersphere"
6
+
7
+ def __init__(
8
+ self,
9
+ classifier_proj_size=256,
10
+ final_dropout=0.1,
11
+ freeze_feat_extract_train=True,
12
+ **kwargs,
13
+ ):
14
+ # Ensure default classification metadata is set before calling super
15
+ if "num_labels" not in kwargs:
16
+ kwargs["num_labels"] = 2
17
+
18
+ if "id2label" not in kwargs:
19
+ kwargs["id2label"] = {0: "AI Voice (Fake)", 1: "Human Voice (Real)"}
20
+
21
+ if "label2id" not in kwargs:
22
+ kwargs["label2id"] = {"AI Voice (Fake)": 0, "Human Voice (Real)": 1}
23
+
24
+ super().__init__(**kwargs)
25
+ self.classifier_proj_size = classifier_proj_size
26
+ self.final_dropout = final_dropout
27
+ self.freeze_feat_extract_train = freeze_feat_extract_train
28
+
29
+
30
+ __all__ = ["Wav2Vec2DualHypersphereConfig"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:219378a69e2a2f590676f89a2ce73f9ed8c12d0c3e2ab41db8884598c0be633b
3
+ size 378302360
modeling.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from transformers import Wav2Vec2Model, Wav2Vec2PreTrainedModel
6
+ from transformers.modeling_outputs import SequenceClassifierOutput
7
+ from transformers.models.auto import AutoConfig, AutoModelForAudioClassification
8
+
9
+ from .configuration import Wav2Vec2DualHypersphereConfig
10
+
11
+
12
+ class Wav2Vec2DualHypersphereForAudioClassification(Wav2Vec2PreTrainedModel):
13
+ config_class = Wav2Vec2DualHypersphereConfig
14
+
15
+ def __init__(self, config: Wav2Vec2DualHypersphereConfig):
16
+ super().__init__(config)
17
+ self.num_labels = config.num_labels
18
+
19
+ self.wav2vec2 = Wav2Vec2Model(config)
20
+ proj_dim = getattr(config, "classifier_proj_size", 256)
21
+ self.projector = nn.Linear(config.hidden_size, proj_dim)
22
+ self.dropout = nn.Dropout(getattr(config, "final_dropout", 0.1))
23
+ self.classifier = nn.Linear(proj_dim, self.num_labels)
24
+
25
+ # Initialize weights and apply final processing
26
+ self.post_init()
27
+
28
+ def freeze_feature_extractor(self):
29
+ self.wav2vec2.feature_extractor._freeze_parameters()
30
+
31
+ def forward(
32
+ self,
33
+ input_values: Optional[torch.Tensor] = None,
34
+ attention_mask: Optional[torch.Tensor] = None,
35
+ output_attentions: Optional[bool] = None,
36
+ output_hidden_states: Optional[bool] = None,
37
+ return_dict: Optional[bool] = None,
38
+ labels: Optional[torch.Tensor] = None,
39
+ ) -> Union[Tuple, SequenceClassifierOutput]:
40
+ r"""
41
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
42
+ Labels for computing the sequence classification/regression loss.
43
+ """
44
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
45
+
46
+ outputs = self.wav2vec2(
47
+ input_values,
48
+ attention_mask=attention_mask,
49
+ output_attentions=output_attentions,
50
+ output_hidden_states=output_hidden_states,
51
+ return_dict=return_dict,
52
+ )
53
+ hidden_states = outputs[0]
54
+
55
+ # 1. Temporal Pooling with Attention Mask support
56
+ if attention_mask is not None:
57
+ mask = self.wav2vec2._get_feature_vector_attention_mask(
58
+ hidden_states.shape[1], attention_mask
59
+ )
60
+ mask = mask.unsqueeze(-1).expand_as(hidden_states)
61
+ pooled_768 = (hidden_states * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1e-9)
62
+ else:
63
+ pooled_768 = hidden_states.mean(dim=1)
64
+
65
+ # 2. First Hypersphere Projection (L2 Normalize 768-D)
66
+ norm_pooled_768 = F.normalize(pooled_768, p=2, dim=-1)
67
+
68
+ # 3. Intermediate Projection & Dropout
69
+ projected_256 = self.dropout(self.projector(norm_pooled_768))
70
+
71
+ # 4. Second Hypersphere Projection (L2 Normalize 256-D)
72
+ norm_projected_256 = F.normalize(projected_256, p=2, dim=-1)
73
+
74
+ # 5. Final Classification Logits
75
+ logits = self.classifier(norm_projected_256)
76
+
77
+ loss = None
78
+ if labels is not None:
79
+ if self.config.problem_type is None:
80
+ if self.num_labels == 1:
81
+ self.config.problem_type = "regression"
82
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
83
+ self.config.problem_type = "single_label_classification"
84
+ else:
85
+ self.config.problem_type = "multi_label_classification"
86
+
87
+ if self.config.problem_type == "regression":
88
+ loss_fct = nn.MSELoss()
89
+ if self.num_labels == 1:
90
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
91
+ else:
92
+ loss = loss_fct(logits, labels)
93
+ elif self.config.problem_type == "single_label_classification":
94
+ loss_fct = nn.CrossEntropyLoss()
95
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
96
+ elif self.config.problem_type == "multi_label_classification":
97
+ loss_fct = nn.BCEWithLogitsLoss()
98
+ loss = loss_fct(logits, labels)
99
+
100
+ if not return_dict:
101
+ output = (logits,) + outputs[2:]
102
+ return ((loss,) + output) if loss is not None else output
103
+
104
+ return SequenceClassifierOutput(
105
+ loss=loss,
106
+ logits=logits,
107
+ hidden_states=outputs.hidden_states if hasattr(outputs, "hidden_states") else None,
108
+ attentions=outputs.attentions if hasattr(outputs, "attentions") else None,
109
+ )
110
+
111
+
112
+ # Register model & config with Auto classes
113
+ AutoConfig.register("wav2vec2-dual-hypersphere", Wav2Vec2DualHypersphereConfig)
114
+ AutoModelForAudioClassification.register(
115
+ Wav2Vec2DualHypersphereConfig, Wav2Vec2DualHypersphereForAudioClassification
116
+ )
117
+
118
+ Wav2Vec2DualHypersphereClassifier = Wav2Vec2DualHypersphereForAudioClassification
119
+
120
+ __all__ = [
121
+ "Wav2Vec2DualHypersphereConfig",
122
+ "Wav2Vec2DualHypersphereForAudioClassification",
123
+ "Wav2Vec2DualHypersphereClassifier",
124
+ ]
preprocessor_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_normalize": true,
3
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
4
+ "feature_size": 1,
5
+ "max_length": 192000,
6
+ "padding_side": "right",
7
+ "padding_value": 0.0,
8
+ "return_attention_mask": true,
9
+ "sampling_rate": 16000,
10
+ "truncation": true
11
+ }