Wrapper code (speech-spoof-bench)
Browse files- .gitignore +20 -0
- LICENSE.source +30 -0
- _net.py +275 -0
- _upstream_pellav3_infer.py +235 -0
- cmp_scores.py +22 -0
- convert_ckpt.py +19 -0
- implementation-notes.md +84 -0
- meta.yaml +34 -0
- pellav3.py +65 -0
- source_parity.py +84 -0
- sweep.py +49 -0
- test_pellav3.py +126 -0
- tf_version_check.py +31 -0
- w2vbert2_config.json +81 -0
- xlsr1b_config.json +76 -0
.gitignore
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hardware-specific TensorRT artifacts — rebuild per GPU with:
|
| 2 |
+
# CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=<gpu> python trt_<module>.py export
|
| 3 |
+
*.plan
|
| 4 |
+
.trt_timing_*.cache
|
| 5 |
+
|
| 6 |
+
# Python
|
| 7 |
+
__pycache__/
|
| 8 |
+
*.py[cod]
|
| 9 |
+
.pytest_cache/
|
| 10 |
+
|
| 11 |
+
# Caches & logs
|
| 12 |
+
.cache/
|
| 13 |
+
*.log
|
| 14 |
+
*.out
|
| 15 |
+
|
| 16 |
+
# Weights / exports (symlinked or rebuilt; re-hosted on the Hub)
|
| 17 |
+
*.safetensors
|
| 18 |
+
*.pt
|
| 19 |
+
*.onnx
|
| 20 |
+
*.onnx.data
|
LICENSE.source
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Upstream: https://huggingface.co/Sadanie/pellav3-audio-deepfake-detector/tree/47b69420803c01de65af264ecdc2c5f35f2184f3
|
| 2 |
+
The model card declares `license: mit`; the repository ships no LICENSE file, so the standard MIT text is
|
| 3 |
+
reproduced below with the Hub owner as the copyright holder. It covers pellav3_infer.py (ported as _net.py,
|
| 4 |
+
copied unchanged as _upstream_pellav3_infer.py for source_parity.py) and pellav3_detector.pt (re-hosted as
|
| 5 |
+
pellav3_detector.safetensors, identical tensors).
|
| 6 |
+
|
| 7 |
+
MIT License
|
| 8 |
+
|
| 9 |
+
Copyright (c) 2026 Sadanie (Hugging Face user "Sadanie")
|
| 10 |
+
|
| 11 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 12 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 13 |
+
in the Software without restriction, including without limitation the rights
|
| 14 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 15 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 16 |
+
furnished to do so, subject to the following conditions:
|
| 17 |
+
|
| 18 |
+
The above copyright notice and this permission notice shall be included in all
|
| 19 |
+
copies or substantial portions of the Software.
|
| 20 |
+
|
| 21 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 22 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 23 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 24 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 25 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 26 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 27 |
+
SOFTWARE.
|
| 28 |
+
|
| 29 |
+
Backbone configs (no weights): facebook/w2v-bert-2.0 @ da985ba0987f70aaeb84a80f2851cfac8c697a7b (MIT),
|
| 30 |
+
facebook/wav2vec2-xls-r-1b @ 35eaea9a0ed0f97592277d79208e40ab8917d1e3 (Apache-2.0).
|
_net.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ported from HF Sadanie/pellav3-audio-deepfake-detector @ 47b69420803c01de65af264ecdc2c5f35f2184f3, pellav3_infer.py
|
| 2 |
+
(sha256 c38f9a431eb5fd245ddc96f8e362d275c2eca1fba8c9d88f2a0686d68362ae6e), MIT (model card `license: mit`).
|
| 3 |
+
|
| 4 |
+
Read in full, never imported/executed from the Hub cache. Edits for the Arena wrapper:
|
| 5 |
+
1. Backbones from vendored configs, as the script already does (Model(Config.from_pretrained(id)), random init) but
|
| 6 |
+
without the Hub: xlsr1b_config.json = facebook/wav2vec2-xls-r-1b @ 35eaea9a0ed0f97592277d79208e40ab8917d1e3,
|
| 7 |
+
w2vbert2_config.json = facebook/w2v-bert-2.0 @ da985ba0987f70aaeb84a80f2851cfac8c697a7b. Every tensor comes from
|
| 8 |
+
pellav3_detector.pt (strict load, see the wrapper).
|
| 9 |
+
2. Res2Block, XlsrBranch, W2vBertBranch, Detector verbatim (forward returns logit(fake)); forward()/frames() are
|
| 10 |
+
split into features() + forward_feats()/frames_feats() (same ops) so the TensorRT engine takes (wav, feats, mask);
|
| 11 |
+
features(pad_to=199) is used only by the TRT path.
|
| 12 |
+
3. view() verbatim on a decoded 16 kHz mono float32 array (mean removal, 20 Hz 2nd-order Butterworth high-pass
|
| 13 |
+
via sosfiltfilt when len > 480, centre 4 s crop, gain to -23 LUFS clipped to +-40 dB, clip to [-1, 1], zero-pad
|
| 14 |
+
to 64000). windows() = the script's views() window grid (4 s windows every 2 s, last one ending at the clip end)
|
| 15 |
+
on the decoded array (ffmpeg -ss/-t on a 16 kHz PCM file is sample-exact; decoding is not part of the Arena path).
|
| 16 |
+
The Arena wrapper scores ONE window: the grid's first one, x[:64000] (= the whole clip when <= 4 s, i.e. exactly
|
| 17 |
+
the script for those); windows() is only used by source_parity.py ("window off").
|
| 18 |
+
4. loudness(): pyloudnorm is not installed here, so pyloudnorm.Meter(16000).integrated_loudness (pyloudnorm 0.1.1
|
| 19 |
+
K-weighting + 400 ms / 75 % gating) is re-implemented with the same op order; the RMS fallback is verbatim.
|
| 20 |
+
6. Detector(batch_invariant=True): see the class docstring (makes a padded batch equal one-clip-at-a-time scoring).
|
| 21 |
+
5. The script runs the net under torch.autocast(bfloat16) on CUDA; the wrapper runs FP32 (TF32 off) -- see
|
| 22 |
+
implementation-notes.md for the bf16-vs-fp32 measurement.
|
| 23 |
+
"""
|
| 24 |
+
import math
|
| 25 |
+
import os
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn as nn
|
| 30 |
+
from scipy.signal import butter, lfilter, sosfiltfilt
|
| 31 |
+
|
| 32 |
+
_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 33 |
+
XLSR_CONFIG = os.path.join(_DIR, "xlsr1b_config.json")
|
| 34 |
+
W2VBERT_CONFIG = os.path.join(_DIR, "w2vbert2_config.json")
|
| 35 |
+
SR = 16000
|
| 36 |
+
CROP_S = 4.0
|
| 37 |
+
CROP = int(CROP_S * SR)
|
| 38 |
+
TARGET_LUFS = -23.0
|
| 39 |
+
_HP_SOS = butter(2, 20.0, btype="highpass", fs=SR, output="sos")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ---------------------------------------------------------------- BS.1770 (pyloudnorm 0.1.1 Meter, mono) ----
|
| 43 |
+
def _iir(G, Q, fc, rate, kind):
|
| 44 |
+
"""pyloudnorm.iirfilter.IIRfilter.generate_coefficients for 'high_shelf' / 'high_pass' (passband_gain 1.0)."""
|
| 45 |
+
A = 10 ** (G / 40.0)
|
| 46 |
+
w0 = 2.0 * np.pi * (fc / rate)
|
| 47 |
+
alpha = np.sin(w0) / (2.0 * Q)
|
| 48 |
+
if kind == "high_shelf":
|
| 49 |
+
b0 = A * ((A + 1) + (A - 1) * np.cos(w0) + 2 * np.sqrt(A) * alpha)
|
| 50 |
+
b1 = -2 * A * ((A - 1) + (A + 1) * np.cos(w0))
|
| 51 |
+
b2 = A * ((A + 1) + (A - 1) * np.cos(w0) - 2 * np.sqrt(A) * alpha)
|
| 52 |
+
a0 = (A + 1) - (A - 1) * np.cos(w0) + 2 * np.sqrt(A) * alpha
|
| 53 |
+
a1 = 2 * ((A - 1) - (A + 1) * np.cos(w0))
|
| 54 |
+
a2 = (A + 1) - (A - 1) * np.cos(w0) - 2 * np.sqrt(A) * alpha
|
| 55 |
+
elif kind == "high_pass":
|
| 56 |
+
b0 = (1 + np.cos(w0)) / 2
|
| 57 |
+
b1 = -(1 + np.cos(w0))
|
| 58 |
+
b2 = (1 + np.cos(w0)) / 2
|
| 59 |
+
a0 = 1 + alpha
|
| 60 |
+
a1 = -2 * np.cos(w0)
|
| 61 |
+
a2 = 1 - alpha
|
| 62 |
+
else:
|
| 63 |
+
raise ValueError(kind)
|
| 64 |
+
return np.array([b0, b1, b2]) / a0, np.array([a0, a1, a2]) / a0
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# pyloudnorm Meter(filter_class="K-weighting"): high_shelf(G=4, Q=1/sqrt2, 1500 Hz) then high_pass(G=0, Q=0.5, 38 Hz)
|
| 68 |
+
_K_FILTERS = [_iir(4.0, 1 / np.sqrt(2), 1500.0, SR, "high_shelf"), _iir(0.0, 0.5, 38.0, SR, "high_pass")]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def integrated_loudness(data, rate=SR, block_size=0.400):
|
| 72 |
+
"""pyloudnorm.Meter(rate).integrated_loudness(data) for a mono float64 array (same op order)."""
|
| 73 |
+
x = np.array(data, dtype=np.float64, copy=True).reshape(-1)
|
| 74 |
+
if x.shape[0] < block_size * rate:
|
| 75 |
+
raise ValueError("Audio must have length greater than the block size.")
|
| 76 |
+
for b, a in _K_FILTERS:
|
| 77 |
+
x = 1.0 * lfilter(b, a, x)
|
| 78 |
+
T_g, Gamma_a, step = block_size, -70.0, 1.0 - 0.75
|
| 79 |
+
T = x.shape[0] / rate
|
| 80 |
+
numBlocks = int(np.round(((T - T_g) / (T_g * step)))) + 1
|
| 81 |
+
z = np.zeros(numBlocks)
|
| 82 |
+
for j in range(numBlocks):
|
| 83 |
+
lo = int(T_g * (j * step) * rate)
|
| 84 |
+
hi = int(T_g * (j * step + 1) * rate)
|
| 85 |
+
z[j] = (1.0 / (T_g * rate)) * np.sum(np.square(x[lo:hi]))
|
| 86 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 87 |
+
lj = [-0.691 + 10.0 * np.log10(np.sum([1.0 * z[j]])) for j in range(numBlocks)]
|
| 88 |
+
J_g = [j for j, l_j in enumerate(lj) if l_j >= Gamma_a]
|
| 89 |
+
z_avg = np.mean([z[j] for j in J_g]) if J_g else np.nan
|
| 90 |
+
Gamma_r = -0.691 + 10.0 * np.log10(np.sum([1.0 * z_avg])) - 10.0
|
| 91 |
+
J_g = [j for j, l_j in enumerate(lj) if (l_j > Gamma_r and l_j > Gamma_a)]
|
| 92 |
+
z_avg = np.nan_to_num(np.array(np.mean([z[j] for j in J_g]) if J_g else np.nan))
|
| 93 |
+
return -0.691 + 10.0 * np.log10(np.sum([1.0 * z_avg]))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def loudness(x):
|
| 97 |
+
"""pellav3_infer.py:loudness (pyloudnorm path, then the RMS fallback)."""
|
| 98 |
+
try:
|
| 99 |
+
if len(x) >= int(0.4 * SR):
|
| 100 |
+
v = integrated_loudness(x.astype(np.float64))
|
| 101 |
+
if np.isfinite(v):
|
| 102 |
+
return float(v)
|
| 103 |
+
except Exception:
|
| 104 |
+
pass
|
| 105 |
+
return float(20 * np.log10(np.sqrt(np.mean(x ** 2)) + 1e-9) - 0.691)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def view(x):
|
| 109 |
+
"""pellav3_infer.py:view -- mean removal and 20 Hz high-pass, centre 4 s crop, loudness to -23 LUFS, zero-pad to 4 s"""
|
| 110 |
+
x = np.asarray(x, dtype=np.float32).reshape(-1)
|
| 111 |
+
x = x - x.mean() if len(x) else x
|
| 112 |
+
if len(x) > 3 * SR // 100:
|
| 113 |
+
x = sosfiltfilt(_HP_SOS, x)
|
| 114 |
+
x = x.astype(np.float32)
|
| 115 |
+
if len(x) > CROP:
|
| 116 |
+
off = (len(x) - CROP) // 2
|
| 117 |
+
x = x[off:off + CROP]
|
| 118 |
+
if len(x):
|
| 119 |
+
gain = float(np.clip(TARGET_LUFS - loudness(x), -40.0, 40.0))
|
| 120 |
+
x = np.clip(x * 10 ** (gain / 20), -1.0, 1.0).astype(np.float32)
|
| 121 |
+
if len(x) < CROP:
|
| 122 |
+
x = np.concatenate([x, np.zeros(CROP - len(x), np.float32)])
|
| 123 |
+
return x
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def first_window(x):
|
| 127 |
+
"""Arena 4 s cap: the first window of the script's grid (decode(path, 0, 4.0) == x[:64000]) -> view()."""
|
| 128 |
+
return view(np.asarray(x, dtype=np.float32).reshape(-1)[:CROP])
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def windows(x):
|
| 132 |
+
"""pellav3_infer.py:views on a decoded array: one view if <= 4 s, else 4 s windows every 2 s, last ending at the end."""
|
| 133 |
+
x = np.asarray(x, dtype=np.float32).reshape(-1)
|
| 134 |
+
d = len(x) / SR
|
| 135 |
+
if d <= CROP_S:
|
| 136 |
+
return [view(x)]
|
| 137 |
+
starts = sorted({round(min(k * 2.0, d - CROP_S), 3) for k in range(math.ceil((d - CROP_S) / 2.0) + 1)})
|
| 138 |
+
return [view(x[int(round(s * SR)):int(round(s * SR)) + CROP]) for s in starts]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# ---------------------------------------------------------------- model ----
|
| 142 |
+
def xlsr_config():
|
| 143 |
+
from transformers import Wav2Vec2Config
|
| 144 |
+
return Wav2Vec2Config.from_json_file(XLSR_CONFIG)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def w2vbert_config():
|
| 148 |
+
from transformers import Wav2Vec2BertConfig
|
| 149 |
+
return Wav2Vec2BertConfig.from_json_file(W2VBERT_CONFIG)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class Res2Block(nn.Module):
|
| 153 |
+
def __init__(self, c=256, scale=4, k=3, d=2):
|
| 154 |
+
super().__init__()
|
| 155 |
+
self.scale, w = scale, c // scale
|
| 156 |
+
self.convs = nn.ModuleList([nn.Conv1d(w, w, k, padding=d * (k - 1) // 2, dilation=d) for _ in range(scale - 1)])
|
| 157 |
+
self.norm = nn.LayerNorm(c)
|
| 158 |
+
|
| 159 |
+
def forward(self, x, m):
|
| 160 |
+
xs = torch.chunk(x, self.scale, dim=1)
|
| 161 |
+
out, y = [xs[0]], None
|
| 162 |
+
for i in range(1, self.scale):
|
| 163 |
+
y = torch.relu(self.convs[i - 1](xs[i] if y is None else xs[i] + y)) * m
|
| 164 |
+
out.append(y)
|
| 165 |
+
return (self.norm(torch.cat(out, 1).transpose(1, 2)).transpose(1, 2) + x) * m
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class XlsrBranch(nn.Module):
|
| 169 |
+
"""XLS-R 1B on the standardised waveform; a learned mix of all layer outputs -> frames [B, F, 1280]"""
|
| 170 |
+
def __init__(self):
|
| 171 |
+
super().__init__()
|
| 172 |
+
from transformers import Wav2Vec2Model
|
| 173 |
+
self.backbone = Wav2Vec2Model(xlsr_config()) # edit 1
|
| 174 |
+
self.layer_weights = nn.Parameter(torch.zeros(self.backbone.config.num_hidden_layers + 1))
|
| 175 |
+
self.head = nn.Linear(self.backbone.config.hidden_size, 1) # the branch's own head, kept for the weights file, unused
|
| 176 |
+
|
| 177 |
+
def frames(self, wav):
|
| 178 |
+
wav = (wav - wav.mean(1, keepdim=True)) / (wav.std(1, keepdim=True) + 1e-7)
|
| 179 |
+
hs = self.backbone(wav, output_hidden_states=True).hidden_states
|
| 180 |
+
w = torch.softmax(self.layer_weights, dim=0)
|
| 181 |
+
return torch.stack(hs).mul(w[:, None, None, None]).sum(0)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class W2vBertBranch(nn.Module):
|
| 185 |
+
"""w2v-BERT 2.0 on 80-bin mel features of the real part of the clip; layer mix, projection, two Res2 blocks -> [B, F, 256]"""
|
| 186 |
+
def __init__(self):
|
| 187 |
+
super().__init__()
|
| 188 |
+
from transformers import Wav2Vec2BertModel
|
| 189 |
+
self.backbone = Wav2Vec2BertModel(w2vbert_config()) # edit 1
|
| 190 |
+
self.layer_weights = nn.Parameter(torch.zeros(self.backbone.config.num_hidden_layers + 1))
|
| 191 |
+
dim = self.backbone.config.hidden_size
|
| 192 |
+
self.ms_proj = nn.Linear(dim, 256)
|
| 193 |
+
self.ms_blocks = nn.ModuleList([Res2Block(256, 4, 3, 2), Res2Block(256, 4, 3, 3)])
|
| 194 |
+
self.att = nn.Sequential(nn.Linear(256, 128), nn.Tanh(), nn.Linear(128, 1)) # the branch's own pooling and head,
|
| 195 |
+
self.head = nn.Linear(512, 1) # kept for the weights file, unused
|
| 196 |
+
|
| 197 |
+
@staticmethod
|
| 198 |
+
def features(wav, pad_to=None):
|
| 199 |
+
import torchaudio.compliance.kaldi as K
|
| 200 |
+
feats, lens = [], []
|
| 201 |
+
with torch.autocast(device_type=wav.device.type, enabled=False):
|
| 202 |
+
for x in wav.float():
|
| 203 |
+
nz = torch.nonzero(x).flatten()
|
| 204 |
+
n_s = int(nz[-1]) + 1 if len(nz) else len(x)
|
| 205 |
+
f = K.fbank(x[None, :max(n_s, 400)] * 32768.0, num_mel_bins=80, sample_frequency=SR, dither=0.0, window_type="povey")
|
| 206 |
+
f = (f - f.mean(0, keepdim=True)) / torch.sqrt(f.var(0, keepdim=True) + 1e-7)
|
| 207 |
+
n = f.shape[0] // 2 * 2
|
| 208 |
+
feats.append(f[:n].reshape(n // 2, 160))
|
| 209 |
+
lens.append(n // 2)
|
| 210 |
+
F = max(lens) if pad_to is None else int(pad_to) # pad_to: TRT path only (fixed 199 frames; extra frames masked)
|
| 211 |
+
out = torch.zeros(len(feats), F, 160, device=wav.device)
|
| 212 |
+
mask = torch.zeros(len(feats), F, dtype=torch.long, device=wav.device)
|
| 213 |
+
for i, (f, n) in enumerate(zip(feats, lens)):
|
| 214 |
+
out[i, :n] = f
|
| 215 |
+
mask[i, :n] = 1
|
| 216 |
+
return out, mask
|
| 217 |
+
|
| 218 |
+
def frames(self, wav):
|
| 219 |
+
return self.frames_feats(*self.features(wav))
|
| 220 |
+
|
| 221 |
+
def frames_feats(self, feats, mask):
|
| 222 |
+
mask[mask.sum(1) == 0, 0] = 1
|
| 223 |
+
m = mask[:, :, None].float()
|
| 224 |
+
hs = self.backbone(input_features=feats, attention_mask=mask, output_hidden_states=True).hidden_states
|
| 225 |
+
w = torch.softmax(self.layer_weights, dim=0)
|
| 226 |
+
h = torch.stack(hs).mul(w[:, None, None, None]).sum(0)
|
| 227 |
+
z = self.ms_proj(h.float()) * m
|
| 228 |
+
zt, mt = z.transpose(1, 2), m.transpose(1, 2)
|
| 229 |
+
for b in self.ms_blocks:
|
| 230 |
+
zt = b(zt, mt)
|
| 231 |
+
return zt.transpose(1, 2), mask
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class Detector(nn.Module):
|
| 235 |
+
"""the two branches, their frames side by side per moment (512), two shared Res2 blocks, attentive statistics pooling
|
| 236 |
+
|
| 237 |
+
batch_invariant (edit 6, default True): in a padded batch the script keeps each item's XLS-R frames beyond its own
|
| 238 |
+
w2v-BERT length (only F = min over the *batch-max* lengths is cut), and the f_blocks' dilated convs read them at the
|
| 239 |
+
mask boundary, so a clip's logit depends on its batch-mates. Zeroing those frames reproduces the one-clip-at-a-time
|
| 240 |
+
result exactly (for B == 1 the mask is all ones, so this is a no-op and the math is the script's)."""
|
| 241 |
+
def __init__(self, batch_invariant=True):
|
| 242 |
+
super().__init__()
|
| 243 |
+
self.batch_invariant = batch_invariant
|
| 244 |
+
self.xl = XlsrBranch()
|
| 245 |
+
self.w2v = W2vBertBranch()
|
| 246 |
+
self.x_proj = nn.Linear(1280, 256)
|
| 247 |
+
self.x_blocks = nn.ModuleList([Res2Block(256, 4, 3, 2), Res2Block(256, 4, 3, 3)])
|
| 248 |
+
self.f_blocks = nn.ModuleList([Res2Block(512, 4, 3, 2), Res2Block(512, 4, 3, 3)])
|
| 249 |
+
self.att = nn.Sequential(nn.Linear(512, 128), nn.Tanh(), nn.Linear(128, 1))
|
| 250 |
+
self.head = nn.Linear(1024, 1)
|
| 251 |
+
|
| 252 |
+
def forward(self, wav):
|
| 253 |
+
return self.forward_feats(wav, *self.w2v.features(wav))
|
| 254 |
+
|
| 255 |
+
def forward_feats(self, wav, feats, mask): # split so the TRT engine is FFT-free (fbank stays in torch)
|
| 256 |
+
hx = self.xl.frames(wav) # [B, Fx, 1280]
|
| 257 |
+
zw, mw = self.w2v.frames_feats(feats, mask) # [B, Fw, 256], [B, Fw]
|
| 258 |
+
B = wav.shape[0]
|
| 259 |
+
zx = self.x_proj(hx.float())
|
| 260 |
+
zxt, mxt = zx.transpose(1, 2), torch.ones(B, 1, hx.shape[1], device=wav.device)
|
| 261 |
+
for b in self.x_blocks:
|
| 262 |
+
zxt = b(zxt, mxt)
|
| 263 |
+
zx = zxt.transpose(1, 2)
|
| 264 |
+
F = min(zx.shape[1], zw.shape[1])
|
| 265 |
+
zx, zw, m = zx[:, :F], zw[:, :F].float(), mw[:, :F]
|
| 266 |
+
if self.batch_invariant: # edit 6: no-op for B == 1 (all m == 1 over F); see the class docstring
|
| 267 |
+
zx = zx * m[:, :, None].to(zx.dtype)
|
| 268 |
+
zt, mt = torch.cat([zx, zw], dim=2).transpose(1, 2), m[:, None, :].float()
|
| 269 |
+
for b in self.f_blocks:
|
| 270 |
+
zt = b(zt, mt)
|
| 271 |
+
z = zt.transpose(1, 2)
|
| 272 |
+
a = torch.softmax(self.att(z).squeeze(-1).masked_fill(m == 0, float("-inf")), dim=1)[:, :, None]
|
| 273 |
+
mu = (a * z).sum(1)
|
| 274 |
+
var = (a * z ** 2).sum(1) - mu ** 2
|
| 275 |
+
return self.head(torch.cat([mu, torch.sqrt(var.clamp(min=1e-6))], dim=1)).squeeze(-1) # logit(fake)
|
_upstream_pellav3_infer.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pellav3 audio deepfake detector: minimal inference code.
|
| 2 |
+
|
| 3 |
+
pip install torch torchaudio transformers==4.48.3 numpy scipy pyloudnorm huggingface_hub (and ffmpeg on the PATH)
|
| 4 |
+
python pellav3_infer.py clip1.wav clip2.mp3 ...
|
| 5 |
+
|
| 6 |
+
The weights are downloaded from the Hugging Face Hub on first use. To run from a local copy instead, pass it first:
|
| 7 |
+
python pellav3_infer.py pellav3_detector.pt clip1.wav ...
|
| 8 |
+
|
| 9 |
+
The model reads each 4 second window with two speech encoders, XLS-R 1B on the waveform and w2v-BERT 2.0 on a mel
|
| 10 |
+
spectrogram, fuses their frames moment by moment and pools them into one score. A clip of 4 seconds or less is scored
|
| 11 |
+
once; a longer clip is scored in 4 second windows every 2 seconds (the last window ends at the end of the clip) and the
|
| 12 |
+
window logits are averaged.
|
| 13 |
+
"""
|
| 14 |
+
import math
|
| 15 |
+
import subprocess
|
| 16 |
+
import sys
|
| 17 |
+
import time
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
|
| 23 |
+
SR = 16000
|
| 24 |
+
CROP_S = 4.0
|
| 25 |
+
CROP = int(CROP_S * SR)
|
| 26 |
+
TARGET_LUFS = -23.0
|
| 27 |
+
HUB_REPO = "Sadanie/pellav3-audio-deepfake-detector"
|
| 28 |
+
WEIGHTS = "pellav3_detector.pt"
|
| 29 |
+
XLSR = "facebook/wav2vec2-xls-r-1b"
|
| 30 |
+
W2VBERT = "facebook/w2v-bert-2.0"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Res2Block(nn.Module):
|
| 34 |
+
def __init__(self, c=256, scale=4, k=3, d=2):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.scale, w = scale, c // scale
|
| 37 |
+
self.convs = nn.ModuleList([nn.Conv1d(w, w, k, padding=d * (k - 1) // 2, dilation=d) for _ in range(scale - 1)])
|
| 38 |
+
self.norm = nn.LayerNorm(c)
|
| 39 |
+
|
| 40 |
+
def forward(self, x, m):
|
| 41 |
+
xs = torch.chunk(x, self.scale, dim=1)
|
| 42 |
+
out, y = [xs[0]], None
|
| 43 |
+
for i in range(1, self.scale):
|
| 44 |
+
y = torch.relu(self.convs[i - 1](xs[i] if y is None else xs[i] + y)) * m
|
| 45 |
+
out.append(y)
|
| 46 |
+
return (self.norm(torch.cat(out, 1).transpose(1, 2)).transpose(1, 2) + x) * m
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class XlsrBranch(nn.Module):
|
| 50 |
+
"""XLS-R 1B on the standardised waveform; a learned mix of all layer outputs -> frames [B, F, 1280]"""
|
| 51 |
+
def __init__(self):
|
| 52 |
+
super().__init__()
|
| 53 |
+
from transformers import Wav2Vec2Config, Wav2Vec2Model
|
| 54 |
+
self.backbone = Wav2Vec2Model(Wav2Vec2Config.from_pretrained(XLSR))
|
| 55 |
+
self.layer_weights = nn.Parameter(torch.zeros(self.backbone.config.num_hidden_layers + 1))
|
| 56 |
+
self.head = nn.Linear(self.backbone.config.hidden_size, 1) # the branch's own head, kept for the weights file, unused
|
| 57 |
+
|
| 58 |
+
def frames(self, wav):
|
| 59 |
+
wav = (wav - wav.mean(1, keepdim=True)) / (wav.std(1, keepdim=True) + 1e-7)
|
| 60 |
+
hs = self.backbone(wav, output_hidden_states=True).hidden_states
|
| 61 |
+
w = torch.softmax(self.layer_weights, dim=0)
|
| 62 |
+
return torch.stack(hs).mul(w[:, None, None, None]).sum(0)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class W2vBertBranch(nn.Module):
|
| 66 |
+
"""w2v-BERT 2.0 on 80-bin mel features of the real part of the clip; layer mix, projection, two Res2 blocks -> [B, F, 256]"""
|
| 67 |
+
def __init__(self):
|
| 68 |
+
super().__init__()
|
| 69 |
+
from transformers import Wav2Vec2BertConfig, Wav2Vec2BertModel
|
| 70 |
+
self.backbone = Wav2Vec2BertModel(Wav2Vec2BertConfig.from_pretrained(W2VBERT))
|
| 71 |
+
self.layer_weights = nn.Parameter(torch.zeros(self.backbone.config.num_hidden_layers + 1))
|
| 72 |
+
dim = self.backbone.config.hidden_size
|
| 73 |
+
self.ms_proj = nn.Linear(dim, 256)
|
| 74 |
+
self.ms_blocks = nn.ModuleList([Res2Block(256, 4, 3, 2), Res2Block(256, 4, 3, 3)])
|
| 75 |
+
self.att = nn.Sequential(nn.Linear(256, 128), nn.Tanh(), nn.Linear(128, 1)) # the branch's own pooling and head,
|
| 76 |
+
self.head = nn.Linear(512, 1) # kept for the weights file, unused
|
| 77 |
+
|
| 78 |
+
@staticmethod
|
| 79 |
+
def features(wav):
|
| 80 |
+
import torchaudio.compliance.kaldi as K
|
| 81 |
+
feats, lens = [], []
|
| 82 |
+
with torch.autocast(device_type=wav.device.type, enabled=False):
|
| 83 |
+
for x in wav.float():
|
| 84 |
+
nz = torch.nonzero(x).flatten()
|
| 85 |
+
n_s = int(nz[-1]) + 1 if len(nz) else len(x)
|
| 86 |
+
f = K.fbank(x[None, :max(n_s, 400)] * 32768.0, num_mel_bins=80, sample_frequency=SR, dither=0.0, window_type="povey")
|
| 87 |
+
f = (f - f.mean(0, keepdim=True)) / torch.sqrt(f.var(0, keepdim=True) + 1e-7)
|
| 88 |
+
n = f.shape[0] // 2 * 2
|
| 89 |
+
feats.append(f[:n].reshape(n // 2, 160))
|
| 90 |
+
lens.append(n // 2)
|
| 91 |
+
F = max(lens)
|
| 92 |
+
out = torch.zeros(len(feats), F, 160, device=wav.device)
|
| 93 |
+
mask = torch.zeros(len(feats), F, dtype=torch.long, device=wav.device)
|
| 94 |
+
for i, (f, n) in enumerate(zip(feats, lens)):
|
| 95 |
+
out[i, :n] = f
|
| 96 |
+
mask[i, :n] = 1
|
| 97 |
+
return out, mask
|
| 98 |
+
|
| 99 |
+
def frames(self, wav):
|
| 100 |
+
feats, mask = self.features(wav)
|
| 101 |
+
mask[mask.sum(1) == 0, 0] = 1
|
| 102 |
+
m = mask[:, :, None].float()
|
| 103 |
+
hs = self.backbone(input_features=feats, attention_mask=mask, output_hidden_states=True).hidden_states
|
| 104 |
+
w = torch.softmax(self.layer_weights, dim=0)
|
| 105 |
+
h = torch.stack(hs).mul(w[:, None, None, None]).sum(0)
|
| 106 |
+
z = self.ms_proj(h.float()) * m
|
| 107 |
+
zt, mt = z.transpose(1, 2), m.transpose(1, 2)
|
| 108 |
+
for b in self.ms_blocks:
|
| 109 |
+
zt = b(zt, mt)
|
| 110 |
+
return zt.transpose(1, 2), mask
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class Detector(nn.Module):
|
| 114 |
+
"""the two branches, their frames side by side per moment (512), two shared Res2 blocks, attentive statistics pooling"""
|
| 115 |
+
def __init__(self):
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.xl = XlsrBranch()
|
| 118 |
+
self.w2v = W2vBertBranch()
|
| 119 |
+
self.x_proj = nn.Linear(1280, 256)
|
| 120 |
+
self.x_blocks = nn.ModuleList([Res2Block(256, 4, 3, 2), Res2Block(256, 4, 3, 3)])
|
| 121 |
+
self.f_blocks = nn.ModuleList([Res2Block(512, 4, 3, 2), Res2Block(512, 4, 3, 3)])
|
| 122 |
+
self.att = nn.Sequential(nn.Linear(512, 128), nn.Tanh(), nn.Linear(128, 1))
|
| 123 |
+
self.head = nn.Linear(1024, 1)
|
| 124 |
+
|
| 125 |
+
def forward(self, wav):
|
| 126 |
+
hx = self.xl.frames(wav) # [B, Fx, 1280]
|
| 127 |
+
zw, mw = self.w2v.frames(wav) # [B, Fw, 256], [B, Fw]
|
| 128 |
+
B = wav.shape[0]
|
| 129 |
+
zx = self.x_proj(hx.float())
|
| 130 |
+
zxt, mxt = zx.transpose(1, 2), torch.ones(B, 1, hx.shape[1], device=wav.device)
|
| 131 |
+
for b in self.x_blocks:
|
| 132 |
+
zxt = b(zxt, mxt)
|
| 133 |
+
zx = zxt.transpose(1, 2)
|
| 134 |
+
F = min(zx.shape[1], zw.shape[1])
|
| 135 |
+
zx, zw, m = zx[:, :F], zw[:, :F].float(), mw[:, :F]
|
| 136 |
+
zt, mt = torch.cat([zx, zw], dim=2).transpose(1, 2), m[:, None, :].float()
|
| 137 |
+
for b in self.f_blocks:
|
| 138 |
+
zt = b(zt, mt)
|
| 139 |
+
z = zt.transpose(1, 2)
|
| 140 |
+
a = torch.softmax(self.att(z).squeeze(-1).masked_fill(m == 0, float("-inf")), dim=1)[:, :, None]
|
| 141 |
+
mu = (a * z).sum(1)
|
| 142 |
+
var = (a * z ** 2).sum(1) - mu ** 2
|
| 143 |
+
return self.head(torch.cat([mu, torch.sqrt(var.clamp(min=1e-6))], dim=1)).squeeze(-1)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def decode(path, start=0.0, dur=None):
|
| 147 |
+
a = (["-ss", f"{start:.3f}"] if start > 0 else []) + (["-t", f"{dur:.3f}"] if dur else [])
|
| 148 |
+
r = subprocess.run(["ffmpeg", "-v", "error", "-y"] + a + ["-i", path, "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"],
|
| 149 |
+
capture_output=True)
|
| 150 |
+
if r.returncode != 0:
|
| 151 |
+
raise RuntimeError(r.stderr.decode(errors="replace")[-300:])
|
| 152 |
+
return np.frombuffer(r.stdout, dtype=np.float32).copy()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def loudness(x):
|
| 156 |
+
try:
|
| 157 |
+
import pyloudnorm as pyln
|
| 158 |
+
|
| 159 |
+
if len(x) >= int(0.4 * SR):
|
| 160 |
+
v = pyln.Meter(SR).integrated_loudness(x.astype(np.float64))
|
| 161 |
+
if np.isfinite(v):
|
| 162 |
+
return float(v)
|
| 163 |
+
except Exception:
|
| 164 |
+
pass
|
| 165 |
+
return float(20 * np.log10(np.sqrt(np.mean(x ** 2)) + 1e-9) - 0.691)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def view(x):
|
| 169 |
+
"""mean removal and 20 Hz high-pass, centre 4 s crop, loudness to -23 LUFS, zero-pad to 4 s"""
|
| 170 |
+
from scipy.signal import butter, sosfiltfilt
|
| 171 |
+
|
| 172 |
+
x = x - x.mean()
|
| 173 |
+
if len(x) > 3 * SR // 100:
|
| 174 |
+
x = sosfiltfilt(butter(2, 20.0, btype="highpass", fs=SR, output="sos"), x)
|
| 175 |
+
x = x.astype(np.float32)
|
| 176 |
+
if len(x) > CROP:
|
| 177 |
+
off = (len(x) - CROP) // 2
|
| 178 |
+
x = x[off:off + CROP]
|
| 179 |
+
if len(x):
|
| 180 |
+
gain = float(np.clip(TARGET_LUFS - loudness(x), -40.0, 40.0))
|
| 181 |
+
x = np.clip(x * 10 ** (gain / 20), -1.0, 1.0).astype(np.float32)
|
| 182 |
+
if len(x) < CROP:
|
| 183 |
+
x = np.concatenate([x, np.zeros(CROP - len(x), np.float32)])
|
| 184 |
+
return x
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def views(path):
|
| 188 |
+
"""one view for a clip of 4 s or less; otherwise one per 4 s window every 2 s, the last ending at the end of the clip"""
|
| 189 |
+
whole = decode(path)
|
| 190 |
+
d = len(whole) / SR
|
| 191 |
+
if d <= CROP_S:
|
| 192 |
+
return [view(whole)], d
|
| 193 |
+
starts = sorted({round(min(k * 2.0, d - CROP_S), 3) for k in range(math.ceil((d - CROP_S) / 2.0) + 1)})
|
| 194 |
+
return [view(decode(path, s, CROP_S)) for s in starts], d
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def hub_weights():
|
| 198 |
+
from huggingface_hub import hf_hub_download
|
| 199 |
+
|
| 200 |
+
hf_hub_download(HUB_REPO, "config.json")
|
| 201 |
+
return hf_hub_download(HUB_REPO, WEIGHTS)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def load_model(weights=None, device=None):
|
| 205 |
+
device = device or ("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
|
| 206 |
+
model = Detector().to(device)
|
| 207 |
+
sd = torch.load(weights or hub_weights(), map_location=device)
|
| 208 |
+
model.load_state_dict(sd["model"] if "model" in sd else sd, strict=True)
|
| 209 |
+
return model.eval(), device
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@torch.no_grad()
|
| 213 |
+
def score(model, device, path):
|
| 214 |
+
"""-> (logit averaged over the clip's views, duration in s, seconds of model time)"""
|
| 215 |
+
vs, d = views(path)
|
| 216 |
+
t0 = time.time()
|
| 217 |
+
with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=device == "cuda"):
|
| 218 |
+
z = model(torch.from_numpy(np.stack(vs)).to(device)).float()
|
| 219 |
+
if device == "cuda":
|
| 220 |
+
torch.cuda.synchronize()
|
| 221 |
+
return float(z.mean()), d, time.time() - t0
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def main():
|
| 225 |
+
args = sys.argv[1:]
|
| 226 |
+
weights = args.pop(0) if args and args[0].endswith(".pt") else None
|
| 227 |
+
model, device = load_model(weights)
|
| 228 |
+
for f in args:
|
| 229 |
+
z, _, _ = score(model, device, f)
|
| 230 |
+
p = 1 / (1 + math.exp(-z))
|
| 231 |
+
print(f"{f}: p_fake={p:.3f} -> {'FAKE' if p >= 0.5 else 'real'}")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
main()
|
cmp_scores.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cmp_scores.py A/scores.txt B/scores.txt -> n, Spearman, max |diff|
|
| 2 |
+
import sys
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.stats import spearmanr
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def read(p):
|
| 8 |
+
d = {}
|
| 9 |
+
for line in open(p):
|
| 10 |
+
parts = line.split()
|
| 11 |
+
if len(parts) >= 2:
|
| 12 |
+
try:
|
| 13 |
+
d[parts[0]] = float(parts[-1])
|
| 14 |
+
except ValueError:
|
| 15 |
+
pass
|
| 16 |
+
return d
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
a, b = read(sys.argv[1]), read(sys.argv[2])
|
| 20 |
+
k = sorted(set(a) & set(b))
|
| 21 |
+
x, y = np.array([a[i] for i in k]), np.array([b[i] for i in k])
|
| 22 |
+
print(f"n={len(k)} spearman={spearmanr(x, y).correlation:.6f} max_abs_diff={np.max(np.abs(x - y)):.4g}")
|
convert_ckpt.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One-time conversion: pellav3_detector.pt (plain pickled state_dict) -> pellav3_detector.safetensors (same keys/values).
|
| 2 |
+
torch.load(weights_only=True) only (tensor-only unpickler); written next to the download, symlinked here.
|
| 3 |
+
Usage: python -I convert_ckpt.py"""
|
| 4 |
+
import hashlib, os, sys
|
| 5 |
+
import torch
|
| 6 |
+
from safetensors.torch import save_file, load_file
|
| 7 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 8 |
+
D = os.path.join(HERE, "..", "_ckpt_dl", "Sadanie__pellav3-audio-deepfake-detector")
|
| 9 |
+
src, out = os.path.join(D, "pellav3_detector.pt"), os.path.join(D, "pellav3_detector.safetensors")
|
| 10 |
+
sd = torch.load(src, map_location="cpu", weights_only=True)
|
| 11 |
+
assert isinstance(sd, dict) and all(isinstance(v, torch.Tensor) for v in sd.values())
|
| 12 |
+
save_file({k: v.contiguous() for k, v in sd.items()}, out,
|
| 13 |
+
metadata={"source": "HF Sadanie/pellav3-audio-deepfake-detector@47b69420803c01de65af264ecdc2c5f35f2184f3 pellav3_detector.pt"})
|
| 14 |
+
back = load_file(out)
|
| 15 |
+
assert back.keys() == sd.keys() and all(torch.equal(back[k], sd[k]) for k in sd)
|
| 16 |
+
h = hashlib.sha256()
|
| 17 |
+
with open(out, "rb") as f:
|
| 18 |
+
for b in iter(lambda: f.read(1 << 24), b""): h.update(b)
|
| 19 |
+
print("wrote", out, len(back), "tensors", sum(v.numel() for v in back.values()), "elements; sha256", h.hexdigest())
|
implementation-notes.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pellav3 — implementation notes
|
| 2 |
+
|
| 3 |
+
Plan: `speech-spoof-bench/docs/plans/2026-11-09-thirteen-model-batch-arena-submission.md` (model #9).
|
| 4 |
+
|
| 5 |
+
## Source
|
| 6 |
+
- HF `Sadanie/pellav3-audio-deepfake-detector` @ `47b69420803c01de65af264ecdc2c5f35f2184f3` (`_ckpt_dl/dl_batch4.py` →
|
| 7 |
+
`_ckpt_dl/Sadanie__pellav3-audio-deepfake-detector/`). Card: `license: mit`, no LICENSE file, no paper, training
|
| 8 |
+
data not described, "1.54 billion parameters, 16 kHz input". Files: `pellav3_detector.pt` (6.18 GB fp32, sha256
|
| 9 |
+
`ac6ae020ac5de06beee4f283ad1ea1fb1ae88dd8da19f483a602a032966695ec`), `pellav3_infer.py` (sha256 `c38f9a43…ae6e`),
|
| 10 |
+
`config.json` (`{"name": …}` only), README.
|
| 11 |
+
- Net (script): two views of each 4 s window — **XLS-R 1B** (48 layers) on the per-window standardised waveform with a
|
| 12 |
+
softmax mix of its 49 hidden states → Linear(1280,256) + 2 Res2 blocks; **w2v-BERT 2.0** on 80-bin kaldi fbank
|
| 13 |
+
(stacked 160-d, masked) with a 25-state mix → Linear(1024,256) + 2 Res2 blocks; frames concatenated (512) → 2 shared
|
| 14 |
+
Res2 blocks → attentive statistics pooling → Linear(1024,1) = logit(fake).
|
| 15 |
+
- `pellav3_infer.py` read in full (subprocess only for `ffmpeg` decoding, Hub only in `hub_weights()`); vendored into
|
| 16 |
+
`_net.py`. Byte-identical copy `_upstream_pellav3_infer.py` (sha256 asserted) is used only by `source_parity.py`.
|
| 17 |
+
- Backbones: the script itself builds them from configs (`Model(Config.from_pretrained(id))`, random init) and fills
|
| 18 |
+
them from the .pt; we use the same configs, pinned and vendored: `xlsr1b_config.json` = facebook/wav2vec2-xls-r-1b @
|
| 19 |
+
`35eaea9a0ed0f97592277d79208e40ab8917d1e3`, `w2vbert2_config.json` = facebook/w2v-bert-2.0 @
|
| 20 |
+
`da985ba0987f70aaeb84a80f2851cfac8c697a7b` (only config.json downloaded, to `_ckpt_dl/facebook__*/`).
|
| 21 |
+
- Weights: plain state_dict (1647 fp32 tensors, pos_conv already in `parametrizations.weight.original0/1` form) →
|
| 22 |
+
`torch.load(weights_only=True)` without allow-list. `convert_ckpt.py` → `pellav3_detector.safetensors` (same
|
| 23 |
+
keys/values, asserted; sha256 `6a721d66a0b9e1a1011193a66f245a4836dbfc036eb671cd1ff80d6e266d5a73`), symlinked here.
|
| 24 |
+
|
| 25 |
+
## transformers version (script pins 4.48.3; we run 5.3.0)
|
| 26 |
+
4.48.3 is not available offline; the uv cache has **4.49.0**. `tf_version_check.py` builds both backbones with the
|
| 27 |
+
Pellav3 weights under 4.49.0 (dependency check stubbed) and under 5.3.0 and compares all hidden states on fixed inputs
|
| 28 |
+
(XLS-R on a waveform batch with a zero-padded item; w2v-BERT on features with a padded attention mask), CPU FP32:
|
| 29 |
+
**max |Δ| = 0.0 for both** (`logs_tf_version_check.txt`). 4.48.3 → 4.49.0 was not tested directly (no 4.48 wheel
|
| 30 |
+
offline); the wav2vec2 / wav2vec2_bert eval paths had no numerical changes in that patch range that we know of.
|
| 31 |
+
|
| 32 |
+
## Wrapper (`pellav3.py:Pellav3`, `_net.py`)
|
| 33 |
+
- **Window**: the script scores clips ≤ 4 s once and longer clips with 4 s windows every 2 s (last window ending at the
|
| 34 |
+
clip end), averaging window logits. Arena 4 s cap: the wrapper scores **one window, the grid's first one**
|
| 35 |
+
(`decode(path, 0, 4.0)` == `x[:64000]`) through the script's `view()` (mean removal, 20 Hz 2nd-order Butterworth
|
| 36 |
+
high-pass by `sosfiltfilt` on the window, centre crop (no-op), gain to −23 LUFS clipped ±40 dB, clip [−1, 1],
|
| 37 |
+
zero-pad to 64000). For clips ≤ 4 s (all of J-SPAW_LA) this is exactly the authors' score. Zero-padding (not
|
| 38 |
+
repeat) is kept because the w2v-BERT branch trims trailing zeros before its fbank, as the authors trained it.
|
| 39 |
+
- **Loudness**: pyloudnorm is not installed here (see Pellav2 notes for details); the same re-implementation of
|
| 40 |
+
`pyloudnorm.Meter(16000).integrated_loudness` is used, with the script's RMS fallback verbatim. Equality with the real
|
| 41 |
+
package is untested (`test_matches_pyloudnorm_if_installed` is skipped).
|
| 42 |
+
- **Batch invariance (edit 6)**: in the script's padded batch, F = min(XLS-R frames, *batch-max* w2v-BERT frames), and
|
| 43 |
+
the XLS-R frames beyond an item's own w2v-BERT length are not zeroed, so the shared Res2 blocks' dilated convs read
|
| 44 |
+
them at the mask boundary — a clip's logit depended on its batch-mates (|Δ| up to 7.7e-3 vs one-at-a-time in our
|
| 45 |
+
smoke test). `Detector(batch_invariant=True)` zeros those frames; for B = 1 it is a no-op (asserted in tests), so the
|
| 46 |
+
wrapper equals the authors' one-clip result in any batch (|Δ| 7.6e-6).
|
| 47 |
+
- **Precision**: the script runs the net under `torch.autocast(bfloat16)` on CUDA. The wrapper is FP32 (TF32 off), per
|
| 48 |
+
the batch instruction. Measured: the script's own bf16 `score()` vs our FP32 on the same single window (clips ≤ 4 s)
|
| 49 |
+
differs by ≤ 0.18 logit (logits ~±20; bf16 resolution there is 0.125).
|
| 50 |
+
- Score = −logit(fake). Strict load: all 1647 tensors map 1:1 onto `Detector.state_dict()` (set equality asserted,
|
| 51 |
+
`strict=True`). Loaded but unused at inference (the script keeps them "for the weights file"), asserted allow-list
|
| 52 |
+
`UNUSED_AT_INFERENCE`: `xl.backbone.masked_spec_embed`, `w2v.backbone.masked_spec_embed` (SpecAugment tokens),
|
| 53 |
+
`xl.head.*`, `w2v.head.*`, `w2v.att.*` (per-branch auxiliary heads/pooling): 37,123 params.
|
| 54 |
+
- Params: 1,544,130,575 total; 1,544,093,452 on the forward path.
|
| 55 |
+
|
| 56 |
+
## Checks
|
| 57 |
+
- `test_pellav3.py`: first-window/view/window-grid, short-clip pad + RMS fallback, loudness target, reference tone,
|
| 58 |
+
strict load + allow-list size, param count, eval mode, batch == single, batch_invariant no-op for B = 1,
|
| 59 |
+
determinism, bona fide > spoof on J-SPAW. 11 passed, 1 skipped (pyloudnorm).
|
| 60 |
+
- `source_parity.py` (`logs_source_parity.txt`), authors' Detector + decode (ffmpeg) + view/views/score on FLOAT wavs
|
| 61 |
+
of 16 J-SPAW_LA clips + 0.3 s + 1.25 s + 6.6 s (3 windows) + 8.6 s (4 windows):
|
| 62 |
+
- preprocessing identical (cap and all windows: max |Δ| 0.0);
|
| 63 |
+
- **4 s cap** (wrapper batched FP32 vs script net on `view(decode(p, 0, 4))`, one clip, FP32): max |Δ| 7.6e-6;
|
| 64 |
+
- **window off** (wrapper `windows()` + mean vs script `views()` + mean, FP32): max |Δ| 0.0;
|
| 65 |
+
- script's own bf16 `score()` vs wrapper FP32 cap: 1.23 overall (long clips: different windows), 0.18 on ≤ 4 s clips.
|
| 66 |
+
|
| 67 |
+
## Batch sweep (`sweep.py`, 64000-sample view, 2026-11-10)
|
| 68 |
+
| card | best | notes |
|
| 69 |
+
|---|---|---|
|
| 70 |
+
| RTX 4070 Ti SUPER (idx 2) | 26.3 utt/s @24 | plateau 8–32 → `batch_size = 24` |
|
| 71 |
+
| RTX 5060 Ti (idx 1) | 8.35 utt/s @2 | ~7 at bs ≥ 4 → 2 on 5060 |
|
| 72 |
+
|
| 73 |
+
## Sanity (PyTorch, idx 2)
|
| 74 |
+
- Full J-SPAW_LA: **EER 0.000 %** (2397 trials, 0 skipped). Logits are saturated and fully separated (about ±20),
|
| 75 |
+
which suggests possible training-data overlap (undisclosed). Flagged for the maintainer.
|
| 76 |
+
|
| 77 |
+
## TensorRT (`trt_pellav3.py`, sidecar `trt_pellav3.json`)
|
| 78 |
+
The engine takes (wav[B,64000], feats[B,199,160], mask[B,199]); the fbank stays in torch. The ONNX is 5.9 GB, so it
|
| 79 |
+
uses the dynamo exporter with external data. On RTX 4070 Ti SUPER, FP16 build Spearman was 0.99945, below 0.9999, so
|
| 80 |
+
it fell back to **FP32**: build parity Spearman 1.0, max Δ 3.4e-4, best batch 8, 31.7 utt/s.
|
| 81 |
+
Outcome (maintainer, 2026-11-10): **PyTorch only.** The full J-SPAW_LA run with `Pellav3TRT` skipped all 2397 clips
|
| 82 |
+
(`'Detector' object has no attribute 'w2v'`: the TRT class drops a submodule the scoring path still uses), and the
|
| 83 |
+
engine is only ~20% faster than PyTorch on the 4070 (31.7 vs 26.3 utt/s), so the class was not fixed and the 5060
|
| 84 |
+
engine build was stopped. All drivers (lanes, EmoSpoofTTS, LRLspoof) use `pellav3:Pellav3`.
|
meta.yaml
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
system:
|
| 2 |
+
name: "Pellav3"
|
| 3 |
+
slug: "pellav3"
|
| 4 |
+
description: >
|
| 5 |
+
Pellav3 (Sadanie, November 2026): an open-weights two-view audio deepfake detector (1.54 B parameters). Each 4 s
|
| 6 |
+
window is read by XLS-R 1B on the standardised waveform (softmax mix of all 49 hidden states) and by w2v-BERT 2.0
|
| 7 |
+
on 80-bin kaldi log-mel fbank features (25-state mix); each view is projected to 256-d and refined by two Res2
|
| 8 |
+
blocks, the frame sequences are concatenated per frame (512-d), refined by two shared Res2 blocks and pooled by
|
| 9 |
+
attentive statistics pooling into Linear(1024,1) -> logit(fake). Authors' released checkpoint; training data
|
| 10 |
+
undisclosed. Input as the authors' pellav3_infer.py view(): 16 kHz, mean removal, 20 Hz high-pass (zero-phase
|
| 11 |
+
2nd-order Butterworth), ITU-R BS.1770 loudness normalisation to -23 LUFS (pyloudnorm semantics), zero-pad to
|
| 12 |
+
4 s. Arena 4 s cap: one window, the first 4 s (64000 samples) of the authors' window grid (the authors average
|
| 13 |
+
4 s windows every 2 s over longer clips; clips <= 4 s are scored identically). score = -logit(fake), higher =
|
| 14 |
+
bona fide. FP32 (TF32 off; the authors run bfloat16 autocast).
|
| 15 |
+
code: "https://huggingface.co/Sadanie/pellav3-audio-deepfake-detector/blob/47b69420803c01de65af264ecdc2c5f35f2184f3/pellav3_infer.py"
|
| 16 |
+
# Upstream (MIT): https://huggingface.co/Sadanie/pellav3-audio-deepfake-detector/blob/47b69420803c01de65af264ecdc2c5f35f2184f3/pellav3_detector.pt
|
| 17 |
+
checkpoint: "https://huggingface.co/SpeechAntiSpoofingBenchmarks/Pellav3/blob/9bb345f5ec6dedc34f26458d5a5d545d9bb1c3ab/pellav3_detector.safetensors"
|
| 18 |
+
params_millions: 1544.093452 # counted from the loaded net's forward path (1,544,093,452; 1,544,130,575 incl. 37,123 loaded-but-unused auxiliary-head/mask-token params), asserted in test_pellav3.py, 2026-11-10
|
| 19 |
+
notes: >
|
| 20 |
+
Pellav3 = HF Sadanie/pellav3-audio-deepfake-detector @ 47b69420803c01de65af264ecdc2c5f35f2184f3,
|
| 21 |
+
pellav3_detector.pt (sha256 ac6ae020ac5de06beee4f283ad1ea1fb1ae88dd8da19f483a602a032966695ec; 1647 fp32 tensors,
|
| 22 |
+
weights_only=True, strict) re-hosted unchanged as pellav3_detector.safetensors (sha256
|
| 23 |
+
6a721d66a0b9e1a1011193a66f245a4836dbfc036eb671cd1ff80d6e266d5a73). MIT per the model card (no LICENSE file).
|
| 24 |
+
Model classes and preprocessing vendored from pellav3_infer.py (sha256 c38f9a43..., read, never imported from the
|
| 25 |
+
Hub cache); backbones built from the facebook/wav2vec2-xls-r-1b (@ 35eaea9a) and facebook/w2v-bert-2.0 (@ da985ba0)
|
| 26 |
+
configs, as the script does, every weight from the checkpoint. The script pins transformers 4.48.3; backbone hidden
|
| 27 |
+
states are bit-identical under 4.49.0 and the 5.3.0 used here. pyloudnorm's integrated loudness is re-implemented
|
| 28 |
+
(not installed here). One edit: XLS-R frames past each clip's own w2v-BERT length are zeroed so a padded batch
|
| 29 |
+
equals one-clip-at-a-time scoring (no-op for a single clip). Verified against the authors' Detector + decode/view
|
| 30 |
+
on 20 J-SPAW_LA-derived clips (FP32): first-window max |d| 7.6e-6, full multi-window path max |d| 0.0; the authors'
|
| 31 |
+
own bf16 path differs by <= 0.18 logit on the same window. Deviations: Arena 4 s cap (first window only instead of
|
| 32 |
+
the mean over 4 s windows every 2 s; identical for clips <= 4 s), FP32 instead of bf16 autocast. Training data is
|
| 33 |
+
undisclosed (no paper, card silent) -> no trained_on entries, but leakage cannot be ruled out: J-SPAW_LA EER is
|
| 34 |
+
0.0% with saturated, perfectly separated scores. No paper -> unpublished tier.
|
pellav3.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from safetensors.torch import load_file
|
| 8 |
+
from speech_spoof_bench.model import AntiSpoofingModel
|
| 9 |
+
|
| 10 |
+
from _net import Detector, first_window
|
| 11 |
+
|
| 12 |
+
_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 13 |
+
# HF Sadanie/pellav3-audio-deepfake-detector @ 47b69420803c01de65af264ecdc2c5f35f2184f3 pellav3_detector.pt
|
| 14 |
+
# (sha256 ac6ae020ac5de06beee4f283ad1ea1fb1ae88dd8da19f483a602a032966695ec) -> convert_ckpt.py -> safetensors
|
| 15 |
+
# (sha256 6a721d66a0b9e1a1011193a66f245a4836dbfc036eb671cd1ff80d6e266d5a73, identical keys/values)
|
| 16 |
+
_CKPT = os.path.join(_DIR, "pellav3_detector.safetensors")
|
| 17 |
+
N_TENSORS = 1647
|
| 18 |
+
# Loaded by the strict load but not on the inference path (the script keeps them "for the weights file, unused"):
|
| 19 |
+
UNUSED_AT_INFERENCE = {
|
| 20 |
+
"xl.backbone.masked_spec_embed": "XLS-R SpecAugment mask token (training only)",
|
| 21 |
+
"w2v.backbone.masked_spec_embed": "w2v-BERT SpecAugment mask token (training only)",
|
| 22 |
+
"xl.head.weight": "XLS-R branch's own head (branch-level auxiliary)", "xl.head.bias": "same",
|
| 23 |
+
"w2v.head.weight": "w2v-BERT branch's own head (auxiliary)", "w2v.head.bias": "same",
|
| 24 |
+
"w2v.att.0.weight": "w2v-BERT branch's own attention pooling (auxiliary)", "w2v.att.0.bias": "same",
|
| 25 |
+
"w2v.att.2.weight": "same", "w2v.att.2.bias": "same",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_state(path=_CKPT):
|
| 30 |
+
sd = load_file(path)
|
| 31 |
+
assert len(sd) == N_TENSORS, len(sd)
|
| 32 |
+
return sd
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def build_net(path=_CKPT):
|
| 36 |
+
net = Detector()
|
| 37 |
+
r = net.load_state_dict(load_state(path), strict=True) # every checkpoint tensor consumed, none missing
|
| 38 |
+
assert not r.missing_keys and not r.unexpected_keys
|
| 39 |
+
return net
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Pellav3(AntiSpoofingModel):
|
| 43 |
+
name = "Pellav3"
|
| 44 |
+
expected_sample_rate = 16000
|
| 45 |
+
batch_size = 24 # sweep 2026-11-10 (64000-sample view): RTX 4070 Ti SUPER 26.3 utt/s @24 (plateau 8-32); RTX 5060 Ti -> 2 (see load)
|
| 46 |
+
|
| 47 |
+
def load(self) -> None:
|
| 48 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 49 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 50 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 51 |
+
self.net = build_net().to(self.device).eval()
|
| 52 |
+
if self.device == "cuda" and "5060" in torch.cuda.get_device_name():
|
| 53 |
+
self.batch_size = 2 # sweep 2026-11-10: RTX 5060 Ti 8.35 utt/s @2, ~7 at bs >= 4
|
| 54 |
+
|
| 55 |
+
@torch.no_grad()
|
| 56 |
+
def score_batch(self, audios, srs):
|
| 57 |
+
x = np.stack([first_window(a) for a in audios])
|
| 58 |
+
logit_fake = self.net(torch.from_numpy(x).to(self.device)).float()
|
| 59 |
+
# pellav3_infer.py: p_fake = sigmoid(logit) -> score = -logit(fake), higher = bona fide
|
| 60 |
+
return (-logit_fake).cpu().tolist()
|
| 61 |
+
|
| 62 |
+
def unload(self) -> None:
|
| 63 |
+
self.net = None
|
| 64 |
+
if torch.cuda.is_available():
|
| 65 |
+
torch.cuda.empty_cache()
|
source_parity.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# source_parity.py -- the authors' pellav3_infer.py path vs this wrapper, on 16 J-SPAW_LA clips + a 0.3 s, a 1.25 s
|
| 2 |
+
# and two long (3x / 4x concat, multi-window) clips.
|
| 3 |
+
# _upstream_pellav3_infer.py is a byte-identical, fully-read copy of the Hub script (sha256 asserted); it is imported
|
| 4 |
+
# from this model dir, never from the Hub cache. Patches (no math changes):
|
| 5 |
+
# * Wav2Vec2Config/Wav2Vec2BertConfig.from_pretrained(<hub id>) -> the vendored, commit-pinned config json
|
| 6 |
+
# * weights: the original pellav3_detector.pt via torch.load(weights_only=True), strict, into the authors' Detector
|
| 7 |
+
# * pyloudnorm is NOT installed here: a shim whose Meter.integrated_loudness is _net.integrated_loudness is injected
|
| 8 |
+
# so the script takes its pyloudnorm branch (it would silently fall back to RMS otherwise). Loudness is therefore
|
| 9 |
+
# not independently checked here; see implementation-notes.md.
|
| 10 |
+
# * clips are written as FLOAT wavs; the script's own decode() (ffmpeg) and views() are used unchanged.
|
| 11 |
+
# Rows printed:
|
| 12 |
+
# cap : wrapper (first 4 s window, FP32, batched) vs script net on [view(decode(path, 0, 4.0))], FP32, one clip at a time
|
| 13 |
+
# full : wrapper's windows() + mean of window logits (FP32) vs the script's views() + mean, FP32 ("window off")
|
| 14 |
+
# bf16 : the script's own score() (bfloat16 autocast, all windows) vs the wrapper's FP32 cap score (information)
|
| 15 |
+
import hashlib, io, os, sys, tempfile, types
|
| 16 |
+
import numpy as np, pyarrow.parquet as pq, soundfile as sf, torch
|
| 17 |
+
|
| 18 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 19 |
+
sys.path.insert(0, HERE)
|
| 20 |
+
import _net
|
| 21 |
+
import pellav3 as W
|
| 22 |
+
|
| 23 |
+
SRC = os.path.join(HERE, "_upstream_pellav3_infer.py")
|
| 24 |
+
assert hashlib.sha256(open(SRC, "rb").read()).hexdigest() == "c38f9a431eb5fd245ddc96f8e362d275c2eca1fba8c9d88f2a0686d68362ae6e"
|
| 25 |
+
PT = os.path.join(HERE, "..", "_ckpt_dl", "Sadanie__pellav3-audio-deepfake-detector", "pellav3_detector.pt")
|
| 26 |
+
|
| 27 |
+
shim = types.ModuleType("pyloudnorm")
|
| 28 |
+
shim.Meter = lambda rate: types.SimpleNamespace(integrated_loudness=lambda x: _net.integrated_loudness(x, rate))
|
| 29 |
+
sys.modules["pyloudnorm"] = shim
|
| 30 |
+
from transformers import Wav2Vec2BertConfig, Wav2Vec2Config # noqa: E402
|
| 31 |
+
Wav2Vec2Config.from_pretrained = classmethod(lambda cls, *a, **k: _net.xlsr_config())
|
| 32 |
+
Wav2Vec2BertConfig.from_pretrained = classmethod(lambda cls, *a, **k: _net.w2vbert_config())
|
| 33 |
+
import _upstream_pellav3_infer as U # noqa: E402
|
| 34 |
+
|
| 35 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 36 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 37 |
+
dev = "cuda"
|
| 38 |
+
|
| 39 |
+
t = pq.read_table(os.path.join(HERE, "..", "J-SPAW_LA", "data", "test-00000-of-00001.parquet"), columns=["audio", "label"]).to_pylist()
|
| 40 |
+
rows = [x for x in t if x["label"] == 0][:8] + [x for x in t if x["label"] == 1][:8]
|
| 41 |
+
auds = [sf.read(io.BytesIO(x["audio"]["bytes"]), dtype="float32")[0] for x in rows]
|
| 42 |
+
auds += [auds[0][:4800], auds[1][:20000], np.concatenate([auds[9]] * 3), np.concatenate([auds[2]] * 4)]
|
| 43 |
+
N = len(auds)
|
| 44 |
+
|
| 45 |
+
# ---- authors' path (their Detector, their decode/view/views/score) ----
|
| 46 |
+
ref = U.Detector()
|
| 47 |
+
r = ref.load_state_dict(torch.load(PT, map_location="cpu", weights_only=True), strict=True)
|
| 48 |
+
print("source strict load:", r)
|
| 49 |
+
ref = ref.to(dev).eval()
|
| 50 |
+
src_cap, src_full, src_bf16, pre_cap, pre_full = [], [], [], 0.0, 0.0
|
| 51 |
+
with tempfile.TemporaryDirectory() as td, torch.no_grad():
|
| 52 |
+
for i, a in enumerate(auds):
|
| 53 |
+
p = os.path.join(td, f"{i}.wav"); sf.write(p, a, 16000, subtype="FLOAT")
|
| 54 |
+
v0 = U.view(U.decode(p, 0.0, U.CROP_S))
|
| 55 |
+
pre_cap = max(pre_cap, float(np.max(np.abs(v0 - _net.first_window(a)))))
|
| 56 |
+
src_cap.append(-float(ref(torch.from_numpy(v0)[None].to(dev))))
|
| 57 |
+
vs, _ = U.views(p)
|
| 58 |
+
ours_vs = _net.windows(a)
|
| 59 |
+
assert len(vs) == len(ours_vs), (len(vs), len(ours_vs))
|
| 60 |
+
pre_full = max(pre_full, max(float(np.max(np.abs(x - y))) for x, y in zip(vs, ours_vs)))
|
| 61 |
+
src_full.append(-float(ref(torch.from_numpy(np.stack(vs)).to(dev)).float().mean()))
|
| 62 |
+
src_bf16.append(-U.score(ref, dev, p)[0])
|
| 63 |
+
del ref
|
| 64 |
+
torch.cuda.empty_cache()
|
| 65 |
+
|
| 66 |
+
# ---- wrapper ----
|
| 67 |
+
m = W.Pellav3(); m.load()
|
| 68 |
+
ours_cap = np.array(m.score_batch(auds, [16000] * N))
|
| 69 |
+
with torch.no_grad():
|
| 70 |
+
ours_full = np.array([-float(m.net(torch.from_numpy(np.stack(_net.windows(a))).to(dev)).float().mean()) for a in auds])
|
| 71 |
+
src_cap, src_full, src_bf16 = map(np.array, (src_cap, src_full, src_bf16))
|
| 72 |
+
print("lens", [len(a) for a in auds])
|
| 73 |
+
print("n_windows", [len(_net.windows(a)) for a in auds])
|
| 74 |
+
print("ours cap ", np.round(ours_cap, 4))
|
| 75 |
+
print("source cap ", np.round(src_cap, 4))
|
| 76 |
+
print("ours full ", np.round(ours_full, 4))
|
| 77 |
+
print("source full", np.round(src_full, 4))
|
| 78 |
+
print("source bf16", np.round(src_bf16, 4))
|
| 79 |
+
print("preprocess max_abs_diff cap (script view(decode(p,0,4)) vs _net.first_window)", pre_cap)
|
| 80 |
+
print("preprocess max_abs_diff full (script views() vs _net.windows)", pre_full)
|
| 81 |
+
print("cap max_abs_diff (wrapper batched FP32 vs script FP32 one clip)", float(np.max(np.abs(ours_cap - src_cap))))
|
| 82 |
+
print("full max_abs_diff (window off, FP32)", float(np.max(np.abs(ours_full - src_full))))
|
| 83 |
+
print("bf16 script score() vs wrapper FP32 cap: max_abs_diff", float(np.max(np.abs(src_bf16 - ours_cap))),
|
| 84 |
+
"| on clips <= 4 s (same window):", float(np.max(np.abs(src_bf16[:18] - ours_cap[:18]))))
|
sweep.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# sweep.py
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import time
|
| 4 |
+
from statistics import median
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
import os as _os, sys as _sys
|
| 8 |
+
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) # python -I drops the script dir
|
| 9 |
+
import pellav3
|
| 10 |
+
|
| 11 |
+
_CUT = 64000 # both Pella nets see exactly 64000 samples (4 s view)
|
| 12 |
+
|
| 13 |
+
def time_batch_sizes():
|
| 14 |
+
print("device", torch.cuda.get_device_name())
|
| 15 |
+
m = pellav3.Pellav3()
|
| 16 |
+
m.load()
|
| 17 |
+
import os
|
| 18 |
+
if os.environ.get("SWEEP_TF32") is not None:
|
| 19 |
+
torch.backends.cudnn.allow_tf32 = torch.backends.cuda.matmul.allow_tf32 = bool(int(os.environ["SWEEP_TF32"]))
|
| 20 |
+
print("cudnn.allow_tf32", torch.backends.cudnn.allow_tf32)
|
| 21 |
+
cuda = getattr(m, "device", "cpu") == "cuda"
|
| 22 |
+
results = {}
|
| 23 |
+
print("=== batch-size sweep ===")
|
| 24 |
+
for bs in [1, 2, 4, 8, 12, 16, 24, 32]:
|
| 25 |
+
audios = [np.random.randn(_CUT).astype(np.float32) for _ in range(bs)]
|
| 26 |
+
srs = [16000] * bs
|
| 27 |
+
try:
|
| 28 |
+
m.score_batch(audios, srs) # warm-up
|
| 29 |
+
if cuda: torch.cuda.synchronize()
|
| 30 |
+
reps = []
|
| 31 |
+
for _ in range(5):
|
| 32 |
+
if cuda: torch.cuda.synchronize()
|
| 33 |
+
t0 = time.perf_counter()
|
| 34 |
+
m.score_batch(audios, srs)
|
| 35 |
+
if cuda: torch.cuda.synchronize()
|
| 36 |
+
reps.append(time.perf_counter() - t0)
|
| 37 |
+
med = median(reps); ups = bs / med
|
| 38 |
+
results[bs] = ups
|
| 39 |
+
print(f"bs={bs:3d} median={med*1000:8.3f} ms utt/s={ups:8.2f}")
|
| 40 |
+
except torch.cuda.OutOfMemoryError:
|
| 41 |
+
print(f"bs={bs:3d} OOM (skipped)")
|
| 42 |
+
if cuda: torch.cuda.empty_cache()
|
| 43 |
+
m.unload()
|
| 44 |
+
best = max(results, key=results.get)
|
| 45 |
+
print(f"best batch_size = {best} (utt/s={results[best]:.2f})")
|
| 46 |
+
return best, results
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
time_batch_sizes()
|
test_pellav3.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
import _net
|
| 9 |
+
import pellav3 as P
|
| 10 |
+
|
| 11 |
+
N_PARAMS = 1_544_130_575 # every checkpoint tensor (1647) is a Detector parameter
|
| 12 |
+
N_PARAMS_FWD = 1_544_093_452 # minus the asserted unused-at-inference allow-list (37,123: 2 mask tokens, 2 branch heads, branch att)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# ---------------------------------------------------------------- preprocessing (CPU) ----
|
| 16 |
+
def test_first_window_long():
|
| 17 |
+
rng = np.random.default_rng(1)
|
| 18 |
+
x = rng.standard_normal(100_001).astype(np.float32) * 0.1
|
| 19 |
+
out = _net.first_window(x)
|
| 20 |
+
assert out.shape == (64000,) and out.dtype == np.float32
|
| 21 |
+
assert np.array_equal(out, _net.view(x[:64000]))
|
| 22 |
+
seg = x[:64000]
|
| 23 |
+
hp = _net.sosfiltfilt(_net._HP_SOS, seg - seg.mean()).astype(np.float32) # high-pass on the window, then gain
|
| 24 |
+
g = out[1000:2000] / hp[1000:2000]
|
| 25 |
+
assert np.allclose(g, g[0], rtol=1e-4)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_view_centre_crop_and_windows_grid():
|
| 29 |
+
x = np.random.default_rng(4).standard_normal(16000 * 9 + 123).astype(np.float32) * 0.1
|
| 30 |
+
off = (len(x) - 64000) // 2
|
| 31 |
+
v = _net.view(x)
|
| 32 |
+
assert v.shape == (64000,)
|
| 33 |
+
ws = _net.windows(x) # d = 9.0077 s -> starts 0, 2, 4, 5.008 (last ends at the end)
|
| 34 |
+
assert len(ws) == 4 and np.array_equal(ws[0], _net.first_window(x))
|
| 35 |
+
assert np.array_equal(ws[-1], _net.view(x[80128:80128 + 64000]))
|
| 36 |
+
assert len(_net.windows(x[:64000])) == 1 and off > 0
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_short_zero_pad_and_fallback():
|
| 40 |
+
x = np.linspace(-0.2, 0.3, 3000, dtype=np.float32) # < 0.4 s -> RMS fallback loudness
|
| 41 |
+
out = _net.first_window(x)
|
| 42 |
+
assert out.shape == (64000,) and not out[3000:].any() and out[:3000].any()
|
| 43 |
+
assert np.array_equal(_net.first_window(np.zeros(0, np.float32)), np.zeros(64000, np.float32))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_loudness_target():
|
| 47 |
+
rng = np.random.default_rng(2)
|
| 48 |
+
x = rng.standard_normal(48000).astype(np.float32) * 0.01
|
| 49 |
+
y = _net.first_window(x)
|
| 50 |
+
assert abs(_net.integrated_loudness(y[:48000].astype(np.float64)) - _net.TARGET_LUFS) < 0.05
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_bs1770_reference_tone():
|
| 54 |
+
t = np.arange(16000 * 5) / 16000
|
| 55 |
+
# pyloudnorm's cookbook K-weighting at 16 kHz: 0 dBFS 997 Hz mono sine -> -3.08 LUFS (BS.1770 48 kHz ref -3.01)
|
| 56 |
+
assert abs(_net.integrated_loudness(np.sin(2 * np.pi * 997 * t)) - (-3.0832)) < 1e-3
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_matches_pyloudnorm_if_installed():
|
| 60 |
+
pyln = pytest.importorskip("pyloudnorm")
|
| 61 |
+
rng = np.random.default_rng(3)
|
| 62 |
+
for n in (6400, 20000, 64000, 64000 + 77):
|
| 63 |
+
x = rng.standard_normal(n) * np.linspace(0.001, 0.3, n)
|
| 64 |
+
assert _net.integrated_loudness(x) == pytest.approx(pyln.Meter(16000).integrated_loudness(x), abs=1e-9)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ---------------------------------------------------------------- weights ----
|
| 68 |
+
def test_strict_load_all_tensors_used():
|
| 69 |
+
sd = P.load_state()
|
| 70 |
+
net = _net.Detector()
|
| 71 |
+
assert set(sd) == set(net.state_dict()) # every tensor consumed, nothing missing
|
| 72 |
+
r = net.load_state_dict(sd, strict=True)
|
| 73 |
+
assert not r.missing_keys and not r.unexpected_keys
|
| 74 |
+
assert set(P.UNUSED_AT_INFERENCE) <= set(sd)
|
| 75 |
+
assert sum(sd[k].numel() for k in P.UNUSED_AT_INFERENCE) == N_PARAMS - N_PARAMS_FWD
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.fixture(scope="module")
|
| 79 |
+
def model():
|
| 80 |
+
m = P.Pellav3(); m.load()
|
| 81 |
+
yield m
|
| 82 |
+
m.unload()
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_eval_mode_and_params(model):
|
| 86 |
+
assert not any(mod.training for mod in model.net.modules())
|
| 87 |
+
n = sum(p.numel() for p in model.net.parameters())
|
| 88 |
+
assert n == N_PARAMS
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_batch_matches_single(model):
|
| 92 |
+
rng = np.random.default_rng(0)
|
| 93 |
+
a = [rng.standard_normal(n).astype(np.float32) * s for n, s in ((48000, 0.1), (20000, 0.5), (90000, 0.02), (3000, 0.3))]
|
| 94 |
+
batched = model.score_batch(a, [16000] * 4)
|
| 95 |
+
single = [model.score_batch([x], [16000])[0] for x in a]
|
| 96 |
+
assert len(batched) == 4 and all(np.isfinite(batched))
|
| 97 |
+
assert np.allclose(batched, single, atol=1e-3)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_batch_invariant_flag_is_noop_for_single(model):
|
| 101 |
+
x = torch.from_numpy(np.stack([_net.first_window(np.random.default_rng(5).standard_normal(30000).astype(np.float32) * 0.1)]))
|
| 102 |
+
x = x.to(model.device)
|
| 103 |
+
with torch.no_grad():
|
| 104 |
+
a = model.net(x).item()
|
| 105 |
+
model.net.batch_invariant = False
|
| 106 |
+
b = model.net(x).item()
|
| 107 |
+
model.net.batch_invariant = True
|
| 108 |
+
assert a == b
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_deterministic(model):
|
| 112 |
+
a = [np.random.randn(40000).astype(np.float32) * 0.1 for _ in range(3)]
|
| 113 |
+
assert model.score_batch(a, [16000] * 3) == model.score_batch(a, [16000] * 3)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def test_sign_bonafide_higher(model):
|
| 117 |
+
import pyarrow.parquet as pq
|
| 118 |
+
import soundfile as sf
|
| 119 |
+
d = os.path.join(os.path.dirname(P.__file__), "..", "J-SPAW_LA", "data")
|
| 120 |
+
t = pq.read_table(os.path.join(d, "test-00000-of-00001.parquet"), columns=["audio", "label"]).to_pylist()
|
| 121 |
+
bona = [r for r in t if r["label"] == 0][:8]
|
| 122 |
+
spoof = [r for r in t if r["label"] == 1][:8]
|
| 123 |
+
dec = lambda rows: [sf.read(io.BytesIO(r["audio"]["bytes"]), dtype="float32")[0] for r in rows]
|
| 124 |
+
sb = model.score_batch(dec(bona), [16000] * 8)
|
| 125 |
+
ss = model.score_batch(dec(spoof), [16000] * 8)
|
| 126 |
+
assert np.mean(sb) > np.mean(ss)
|
tf_version_check.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# python -I tf_version_check.py <dir holding transformers-X (e.g. the uv-cache 4.49.0 archive) or ""> out.pt -- backbone hidden states (XLS-R 1B + w2v-BERT 2.0, Pellav3 weights, fixed inputs, CPU FP32); compare two out.pt files
|
| 2 |
+
import sys
|
| 3 |
+
if sys.argv[1]:
|
| 4 |
+
import types; sys.path.insert(0, sys.argv[1])
|
| 5 |
+
_m = types.ModuleType("transformers.dependency_versions_check"); _m.dep_version_check = lambda *a, **k: None
|
| 6 |
+
sys.modules["transformers.dependency_versions_check"] = _m
|
| 7 |
+
import numpy as np, torch, transformers
|
| 8 |
+
from safetensors.torch import load_file
|
| 9 |
+
print("transformers", transformers.__version__, transformers.__file__)
|
| 10 |
+
from transformers import Wav2Vec2Config, Wav2Vec2Model, Wav2Vec2BertConfig, Wav2Vec2BertModel
|
| 11 |
+
import os; B = os.path.dirname(os.path.abspath(__file__)) + "/"
|
| 12 |
+
sd = load_file(B + "pellav3_detector.safetensors")
|
| 13 |
+
torch.manual_seed(0)
|
| 14 |
+
wav = torch.randn(2, 64000) * 0.1
|
| 15 |
+
wav[1, 40000:] = 0
|
| 16 |
+
feats = torch.randn(2, 199, 160); mask = torch.ones(2, 199, dtype=torch.long); mask[1, 120:] = 0
|
| 17 |
+
out = {}
|
| 18 |
+
xl = Wav2Vec2Model(Wav2Vec2Config.from_json_file(B + "xlsr1b_config.json")).eval()
|
| 19 |
+
sub = {k[len("xl.backbone."):]: v for k, v in sd.items() if k.startswith("xl.backbone.")}
|
| 20 |
+
print(xl.load_state_dict(sub, strict=True))
|
| 21 |
+
with torch.no_grad():
|
| 22 |
+
w = (wav - wav.mean(1, keepdim=True)) / (wav.std(1, keepdim=True) + 1e-7)
|
| 23 |
+
out["xl"] = torch.stack(xl(w, output_hidden_states=True).hidden_states)
|
| 24 |
+
del xl
|
| 25 |
+
bt = Wav2Vec2BertModel(Wav2Vec2BertConfig.from_json_file(B + "w2vbert2_config.json")).eval()
|
| 26 |
+
sub = {k[len("w2v.backbone."):]: v for k, v in sd.items() if k.startswith("w2v.backbone.")}
|
| 27 |
+
print(bt.load_state_dict(sub, strict=True))
|
| 28 |
+
with torch.no_grad():
|
| 29 |
+
out["w2v"] = torch.stack(bt(input_features=feats, attention_mask=mask, output_hidden_states=True).hidden_states)
|
| 30 |
+
torch.save(out, sys.argv[2])
|
| 31 |
+
print({k: tuple(v.shape) for k, v in out.items()})
|
w2vbert2_config.json
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"activation_dropout": 0.0,
|
| 3 |
+
"adapter_act": "relu",
|
| 4 |
+
"adapter_kernel_size": 3,
|
| 5 |
+
"adapter_stride": 2,
|
| 6 |
+
"add_adapter": false,
|
| 7 |
+
"apply_spec_augment": false,
|
| 8 |
+
"architectures": [
|
| 9 |
+
"Wav2Vec2BertModel"
|
| 10 |
+
],
|
| 11 |
+
"attention_dropout": 0.0,
|
| 12 |
+
"bos_token_id": 1,
|
| 13 |
+
"classifier_proj_size": 768,
|
| 14 |
+
"codevector_dim": 768,
|
| 15 |
+
"conformer_conv_dropout": 0.1,
|
| 16 |
+
"contrastive_logits_temperature": 0.1,
|
| 17 |
+
"conv_depthwise_kernel_size": 31,
|
| 18 |
+
"ctc_loss_reduction": "sum",
|
| 19 |
+
"ctc_zero_infinity": false,
|
| 20 |
+
"diversity_loss_weight": 0.1,
|
| 21 |
+
"eos_token_id": 2,
|
| 22 |
+
"feat_proj_dropout": 0.0,
|
| 23 |
+
"feat_quantizer_dropout": 0.0,
|
| 24 |
+
"feature_projection_input_dim": 160,
|
| 25 |
+
"final_dropout": 0.1,
|
| 26 |
+
"hidden_act": "swish",
|
| 27 |
+
"hidden_dropout": 0.0,
|
| 28 |
+
"hidden_size": 1024,
|
| 29 |
+
"initializer_range": 0.02,
|
| 30 |
+
"intermediate_size": 4096,
|
| 31 |
+
"layer_norm_eps": 1e-05,
|
| 32 |
+
"layerdrop": 0.1,
|
| 33 |
+
"left_max_position_embeddings": 64,
|
| 34 |
+
"mask_feature_length": 10,
|
| 35 |
+
"mask_feature_min_masks": 0,
|
| 36 |
+
"mask_feature_prob": 0.0,
|
| 37 |
+
"mask_time_length": 10,
|
| 38 |
+
"mask_time_min_masks": 2,
|
| 39 |
+
"mask_time_prob": 0.05,
|
| 40 |
+
"max_source_positions": 5000,
|
| 41 |
+
"model_type": "wav2vec2-bert",
|
| 42 |
+
"num_adapter_layers": 1,
|
| 43 |
+
"num_attention_heads": 16,
|
| 44 |
+
"num_codevector_groups": 2,
|
| 45 |
+
"num_codevectors_per_group": 320,
|
| 46 |
+
"num_hidden_layers": 24,
|
| 47 |
+
"num_negatives": 100,
|
| 48 |
+
"output_hidden_size": 1024,
|
| 49 |
+
"pad_token_id": 0,
|
| 50 |
+
"position_embeddings_type": "relative_key",
|
| 51 |
+
"proj_codevector_dim": 768,
|
| 52 |
+
"right_max_position_embeddings": 8,
|
| 53 |
+
"rotary_embedding_base": 10000,
|
| 54 |
+
"tdnn_dilation": [
|
| 55 |
+
1,
|
| 56 |
+
2,
|
| 57 |
+
3,
|
| 58 |
+
1,
|
| 59 |
+
1
|
| 60 |
+
],
|
| 61 |
+
"tdnn_dim": [
|
| 62 |
+
512,
|
| 63 |
+
512,
|
| 64 |
+
512,
|
| 65 |
+
512,
|
| 66 |
+
1500
|
| 67 |
+
],
|
| 68 |
+
"tdnn_kernel": [
|
| 69 |
+
5,
|
| 70 |
+
3,
|
| 71 |
+
3,
|
| 72 |
+
1,
|
| 73 |
+
1
|
| 74 |
+
],
|
| 75 |
+
"torch_dtype": "float32",
|
| 76 |
+
"transformers_version": "4.37.0.dev0",
|
| 77 |
+
"use_intermediate_ffn_before_adapter": false,
|
| 78 |
+
"use_weighted_layer_sum": false,
|
| 79 |
+
"vocab_size": null,
|
| 80 |
+
"xvector_output_dim": 512
|
| 81 |
+
}
|
xlsr1b_config.json
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"activation_dropout": 0.0,
|
| 3 |
+
"apply_spec_augment": true,
|
| 4 |
+
"architectures": [
|
| 5 |
+
"Wav2Vec2ForPreTraining"
|
| 6 |
+
],
|
| 7 |
+
"attention_dropout": 0.1,
|
| 8 |
+
"bos_token_id": 1,
|
| 9 |
+
"codevector_dim": 1024,
|
| 10 |
+
"contrastive_logits_temperature": 0.1,
|
| 11 |
+
"conv_bias": true,
|
| 12 |
+
"conv_dim": [
|
| 13 |
+
512,
|
| 14 |
+
512,
|
| 15 |
+
512,
|
| 16 |
+
512,
|
| 17 |
+
512,
|
| 18 |
+
512,
|
| 19 |
+
512
|
| 20 |
+
],
|
| 21 |
+
"conv_kernel": [
|
| 22 |
+
10,
|
| 23 |
+
3,
|
| 24 |
+
3,
|
| 25 |
+
3,
|
| 26 |
+
3,
|
| 27 |
+
2,
|
| 28 |
+
2
|
| 29 |
+
],
|
| 30 |
+
"conv_stride": [
|
| 31 |
+
5,
|
| 32 |
+
2,
|
| 33 |
+
2,
|
| 34 |
+
2,
|
| 35 |
+
2,
|
| 36 |
+
2,
|
| 37 |
+
2
|
| 38 |
+
],
|
| 39 |
+
"ctc_loss_reduction": "sum",
|
| 40 |
+
"ctc_zero_infinity": false,
|
| 41 |
+
"diversity_loss_weight": 0.1,
|
| 42 |
+
"do_stable_layer_norm": true,
|
| 43 |
+
"eos_token_id": 2,
|
| 44 |
+
"feat_extract_activation": "gelu",
|
| 45 |
+
"feat_extract_dropout": 0.0,
|
| 46 |
+
"feat_extract_norm": "layer",
|
| 47 |
+
"feat_proj_dropout": 0.1,
|
| 48 |
+
"feat_quantizer_dropout": 0.0,
|
| 49 |
+
"final_dropout": 0.0,
|
| 50 |
+
"gradient_checkpointing": false,
|
| 51 |
+
"hidden_act": "gelu",
|
| 52 |
+
"hidden_dropout": 0.1,
|
| 53 |
+
"hidden_size": 1280,
|
| 54 |
+
"initializer_range": 0.02,
|
| 55 |
+
"intermediate_size": 5120,
|
| 56 |
+
"layer_norm_eps": 1e-05,
|
| 57 |
+
"layerdrop": 0.1,
|
| 58 |
+
"mask_feature_length": 10,
|
| 59 |
+
"mask_feature_prob": 0.0,
|
| 60 |
+
"mask_time_length": 10,
|
| 61 |
+
"mask_time_prob": 0.075,
|
| 62 |
+
"model_type": "wav2vec2",
|
| 63 |
+
"num_attention_heads": 16,
|
| 64 |
+
"num_codevector_groups": 2,
|
| 65 |
+
"num_codevectors_per_group": 320,
|
| 66 |
+
"num_conv_pos_embedding_groups": 16,
|
| 67 |
+
"num_conv_pos_embeddings": 128,
|
| 68 |
+
"num_feat_extract_layers": 7,
|
| 69 |
+
"num_hidden_layers": 48,
|
| 70 |
+
"num_negatives": 100,
|
| 71 |
+
"pad_token_id": 0,
|
| 72 |
+
"proj_codevector_dim": 1024,
|
| 73 |
+
"torch_dtype": "float32",
|
| 74 |
+
"transformers_version": "4.12.0.dev0",
|
| 75 |
+
"use_weighted_layer_sum": false
|
| 76 |
+
}
|