Pellav2 / _net.py
korallll's picture
Wrapper code (speech-spoof-bench)
6f93a12 verified
Raw History Blame Contribute Delete
8.25 kB
"""Ported from HF Sadanie/pellav2-audio-deepfake-detector @ b668eb4dfe4719665692c73c1d70383680afff6b, pellav2_infer.py
(sha256 bf13cc97e5f0466b6dd6797afce7abe9befc61ec8817c05cbe505f88a29c6a67), MIT (model card `license: mit`).
Read in full, never imported/executed from the Hub cache. Edits for the Arena wrapper:
1. `backbone` is Wav2Vec2BertModel(config) from the vendored facebook/w2v-bert-2.0 config (w2vbert2_config.json,
HF @ da985ba0987f70aaeb84a80f2851cfac8c697a7b) instead of from_pretrained(...): no Hub weights; every backbone
tensor comes from pellav2_detector.pt (strict load, see the wrapper).
2. Detector.features / forward verbatim (kaldi 80-bin fbank x32768, per-utterance mean/var norm, frame stacking
to 160-d, trailing-zero trimming, padded batch + attention mask, softmax layer mix over 25 hidden states,
masked mean, Linear(1024,1) -> logit(fake)). forward() is split into features() + forward_feats() (same ops) so
the TensorRT engine takes (feats, mask); features(pad_to=199) is used only by the TRT path.
3. load_clip() -> preprocess(wav): the same steps on an already-decoded 16 kHz mono float32 array (the Arena
runner delivers 16 kHz mono; the script's resample branch is a no-op then): mean removal, 2nd-order 20 Hz
Butterworth high-pass (sosfiltfilt) when len > 480, centre 4 s (64000) crop, gain to -23 LUFS (clipped to
+-40 dB), clip to [-1, 1], zero-pad to 64000.
4. loudness(): pyloudnorm is not installed in this environment, so pyloudnorm.Meter(16000).integrated_loudness
(BS.1770-4 K-weighting + 400 ms / 75 % overlap gating, pyloudnorm 0.1.1) is re-implemented below with the
same operation order; the script's RMS fallback (len < 0.4 s, or non-finite loudness) is kept verbatim.
"""
import json
import os
import numpy as np
import torch
import torch.nn as nn
from scipy.signal import butter, lfilter, sosfiltfilt
_DIR = os.path.dirname(os.path.abspath(__file__))
W2VBERT_CONFIG = os.path.join(_DIR, "w2vbert2_config.json")
SR = 16000
CROP = 4 * SR
TARGET_LUFS = -23.0
_HP_SOS = butter(2, 20.0, btype="highpass", fs=SR, output="sos")
# ---------------------------------------------------------------- BS.1770 (pyloudnorm 0.1.1 Meter, mono) ----
def _iir(G, Q, fc, rate, kind):
"""pyloudnorm.iirfilter.IIRfilter.generate_coefficients for 'high_shelf' / 'high_pass' (passband_gain 1.0)."""
A = 10 ** (G / 40.0)
w0 = 2.0 * np.pi * (fc / rate)
alpha = np.sin(w0) / (2.0 * Q)
if kind == "high_shelf":
b0 = A * ((A + 1) + (A - 1) * np.cos(w0) + 2 * np.sqrt(A) * alpha)
b1 = -2 * A * ((A - 1) + (A + 1) * np.cos(w0))
b2 = A * ((A + 1) + (A - 1) * np.cos(w0) - 2 * np.sqrt(A) * alpha)
a0 = (A + 1) - (A - 1) * np.cos(w0) + 2 * np.sqrt(A) * alpha
a1 = 2 * ((A - 1) - (A + 1) * np.cos(w0))
a2 = (A + 1) - (A - 1) * np.cos(w0) - 2 * np.sqrt(A) * alpha
elif kind == "high_pass":
b0 = (1 + np.cos(w0)) / 2
b1 = -(1 + np.cos(w0))
b2 = (1 + np.cos(w0)) / 2
a0 = 1 + alpha
a1 = -2 * np.cos(w0)
a2 = 1 - alpha
else:
raise ValueError(kind)
return np.array([b0, b1, b2]) / a0, np.array([a0, a1, a2]) / a0
# 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)
_K_FILTERS = [_iir(4.0, 1 / np.sqrt(2), 1500.0, SR, "high_shelf"), _iir(0.0, 0.5, 38.0, SR, "high_pass")]
def integrated_loudness(data, rate=SR, block_size=0.400):
"""pyloudnorm.Meter(rate).integrated_loudness(data) for a mono float64 array (same op order)."""
x = np.array(data, dtype=np.float64, copy=True).reshape(-1)
if x.shape[0] < block_size * rate:
raise ValueError("Audio must have length greater than the block size.")
for b, a in _K_FILTERS:
x = 1.0 * lfilter(b, a, x)
T_g, Gamma_a, step = block_size, -70.0, 1.0 - 0.75
T = x.shape[0] / rate
numBlocks = int(np.round(((T - T_g) / (T_g * step)))) + 1
z = np.zeros(numBlocks)
for j in range(numBlocks):
lo = int(T_g * (j * step) * rate)
hi = int(T_g * (j * step + 1) * rate)
z[j] = (1.0 / (T_g * rate)) * np.sum(np.square(x[lo:hi]))
with np.errstate(divide="ignore", invalid="ignore"):
lj = [-0.691 + 10.0 * np.log10(np.sum([1.0 * z[j]])) for j in range(numBlocks)]
J_g = [j for j, l_j in enumerate(lj) if l_j >= Gamma_a]
z_avg = np.mean([z[j] for j in J_g]) if J_g else np.nan
Gamma_r = -0.691 + 10.0 * np.log10(np.sum([1.0 * z_avg])) - 10.0
J_g = [j for j, l_j in enumerate(lj) if (l_j > Gamma_r and l_j > Gamma_a)]
z_avg = np.nan_to_num(np.array(np.mean([z[j] for j in J_g]) if J_g else np.nan))
return -0.691 + 10.0 * np.log10(np.sum([1.0 * z_avg]))
def loudness(x):
"""pellav2_infer.py:loudness (pyloudnorm path, then the RMS fallback)."""
try:
if len(x) >= int(0.4 * SR):
v = integrated_loudness(x.astype(np.float64))
if np.isfinite(v):
return float(v)
except Exception:
pass
return float(20 * np.log10(np.sqrt(np.mean(x ** 2)) + 1e-9) - 0.691)
def preprocess(wav):
"""pellav2_infer.py:load_clip after decoding (16 kHz mono float32 in, (64000,) float32 out)."""
wav = np.asarray(wav, dtype=np.float32).reshape(-1)
wav = wav - wav.mean() if len(wav) else wav
if len(wav) > 3 * SR // 100:
wav = sosfiltfilt(_HP_SOS, wav)
wav = wav.astype(np.float32)
if len(wav) > CROP:
off = (len(wav) - CROP) // 2
wav = wav[off: off + CROP]
if len(wav):
gain = float(np.clip(TARGET_LUFS - loudness(wav), -40.0, 40.0))
wav = np.clip(wav * 10 ** (gain / 20), -1.0, 1.0).astype(np.float32)
if len(wav) < CROP:
wav = np.concatenate([wav, np.zeros(CROP - len(wav), np.float32)])
return wav
# ---------------------------------------------------------------- model ----
def w2vbert_config():
from transformers import Wav2Vec2BertConfig
with open(W2VBERT_CONFIG) as f:
return Wav2Vec2BertConfig(**json.load(f))
class Detector(nn.Module):
def __init__(self):
super().__init__()
from transformers import Wav2Vec2BertModel
self.backbone = Wav2Vec2BertModel(w2vbert_config()) # edit 1
self.layer_weights = nn.Parameter(
torch.zeros(self.backbone.config.num_hidden_layers + 1))
self.head = nn.Linear(self.backbone.config.hidden_size, 1)
@staticmethod
def features(wav, pad_to=None):
import torchaudio.compliance.kaldi as K
feats, lens = [], []
with torch.autocast(device_type=wav.device.type, enabled=False):
for x in wav.float():
nz = torch.nonzero(x).flatten()
n_s = int(nz[-1]) + 1 if len(nz) else len(x)
f = K.fbank(x[None, :max(n_s, 400)] * 32768.0, num_mel_bins=80,
sample_frequency=SR, dither=0.0, window_type="povey")
f = (f - f.mean(0, keepdim=True)) / torch.sqrt(f.var(0, keepdim=True) + 1e-7)
n = f.shape[0] // 2 * 2
feats.append(f[:n].reshape(n // 2, 160))
lens.append(n // 2)
F = max(lens) if pad_to is None else int(pad_to) # pad_to: TRT path only (fixed 199 frames; extra frames masked)
out = torch.zeros(len(feats), F, 160, device=wav.device)
mask = torch.zeros(len(feats), F, dtype=torch.long, device=wav.device)
for i, (f, n) in enumerate(zip(feats, lens)):
out[i, :n] = f
mask[i, :n] = 1
return out, mask
def forward(self, wav):
feats, mask = self.features(wav)
return self.forward_feats(feats, mask)
def forward_feats(self, feats, mask): # split out so the TRT engine is FFT-free (features stay in torch)
hs = self.backbone(input_features=feats, attention_mask=mask,
output_hidden_states=True).hidden_states
w = torch.softmax(self.layer_weights, dim=0)
h = torch.stack(hs).mul(w[:, None, None, None]).sum(0)
m = mask[:, :, None].float()
h = (h * m).sum(1) / m.sum(1).clamp(min=1)
return self.head(h).squeeze(-1) # logit(fake)