Pellav3 / _net.py
korallll's picture
Wrapper code (speech-spoof-bench)
cc05206 verified
Raw History Blame Contribute Delete
13.9 kB
"""Ported from HF Sadanie/pellav3-audio-deepfake-detector @ 47b69420803c01de65af264ecdc2c5f35f2184f3, pellav3_infer.py
(sha256 c38f9a431eb5fd245ddc96f8e362d275c2eca1fba8c9d88f2a0686d68362ae6e), MIT (model card `license: mit`).
Read in full, never imported/executed from the Hub cache. Edits for the Arena wrapper:
1. Backbones from vendored configs, as the script already does (Model(Config.from_pretrained(id)), random init) but
without the Hub: xlsr1b_config.json = facebook/wav2vec2-xls-r-1b @ 35eaea9a0ed0f97592277d79208e40ab8917d1e3,
w2vbert2_config.json = facebook/w2v-bert-2.0 @ da985ba0987f70aaeb84a80f2851cfac8c697a7b. Every tensor comes from
pellav3_detector.pt (strict load, see the wrapper).
2. Res2Block, XlsrBranch, W2vBertBranch, Detector verbatim (forward returns logit(fake)); forward()/frames() are
split into features() + forward_feats()/frames_feats() (same ops) so the TensorRT engine takes (wav, feats, mask);
features(pad_to=199) is used only by the TRT path.
3. view() verbatim on a decoded 16 kHz mono float32 array (mean removal, 20 Hz 2nd-order Butterworth high-pass
via sosfiltfilt when len > 480, centre 4 s crop, gain to -23 LUFS clipped to +-40 dB, clip to [-1, 1], zero-pad
to 64000). windows() = the script's views() window grid (4 s windows every 2 s, last one ending at the clip end)
on the decoded array (ffmpeg -ss/-t on a 16 kHz PCM file is sample-exact; decoding is not part of the Arena path).
The Arena wrapper scores ONE window: the grid's first one, x[:64000] (= the whole clip when <= 4 s, i.e. exactly
the script for those); windows() is only used by source_parity.py ("window off").
4. loudness(): pyloudnorm is not installed here, so pyloudnorm.Meter(16000).integrated_loudness (pyloudnorm 0.1.1
K-weighting + 400 ms / 75 % gating) is re-implemented with the same op order; the RMS fallback is verbatim.
6. Detector(batch_invariant=True): see the class docstring (makes a padded batch equal one-clip-at-a-time scoring).
5. The script runs the net under torch.autocast(bfloat16) on CUDA; the wrapper runs FP32 (TF32 off) -- see
implementation-notes.md for the bf16-vs-fp32 measurement.
"""
import math
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__))
XLSR_CONFIG = os.path.join(_DIR, "xlsr1b_config.json")
W2VBERT_CONFIG = os.path.join(_DIR, "w2vbert2_config.json")
SR = 16000
CROP_S = 4.0
CROP = int(CROP_S * 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):
"""pellav3_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 view(x):
"""pellav3_infer.py:view -- mean removal and 20 Hz high-pass, centre 4 s crop, loudness to -23 LUFS, zero-pad to 4 s"""
x = np.asarray(x, dtype=np.float32).reshape(-1)
x = x - x.mean() if len(x) else x
if len(x) > 3 * SR // 100:
x = sosfiltfilt(_HP_SOS, x)
x = x.astype(np.float32)
if len(x) > CROP:
off = (len(x) - CROP) // 2
x = x[off:off + CROP]
if len(x):
gain = float(np.clip(TARGET_LUFS - loudness(x), -40.0, 40.0))
x = np.clip(x * 10 ** (gain / 20), -1.0, 1.0).astype(np.float32)
if len(x) < CROP:
x = np.concatenate([x, np.zeros(CROP - len(x), np.float32)])
return x
def first_window(x):
"""Arena 4 s cap: the first window of the script's grid (decode(path, 0, 4.0) == x[:64000]) -> view()."""
return view(np.asarray(x, dtype=np.float32).reshape(-1)[:CROP])
def windows(x):
"""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."""
x = np.asarray(x, dtype=np.float32).reshape(-1)
d = len(x) / SR
if d <= CROP_S:
return [view(x)]
starts = sorted({round(min(k * 2.0, d - CROP_S), 3) for k in range(math.ceil((d - CROP_S) / 2.0) + 1)})
return [view(x[int(round(s * SR)):int(round(s * SR)) + CROP]) for s in starts]
# ---------------------------------------------------------------- model ----
def xlsr_config():
from transformers import Wav2Vec2Config
return Wav2Vec2Config.from_json_file(XLSR_CONFIG)
def w2vbert_config():
from transformers import Wav2Vec2BertConfig
return Wav2Vec2BertConfig.from_json_file(W2VBERT_CONFIG)
class Res2Block(nn.Module):
def __init__(self, c=256, scale=4, k=3, d=2):
super().__init__()
self.scale, w = scale, c // scale
self.convs = nn.ModuleList([nn.Conv1d(w, w, k, padding=d * (k - 1) // 2, dilation=d) for _ in range(scale - 1)])
self.norm = nn.LayerNorm(c)
def forward(self, x, m):
xs = torch.chunk(x, self.scale, dim=1)
out, y = [xs[0]], None
for i in range(1, self.scale):
y = torch.relu(self.convs[i - 1](xs[i] if y is None else xs[i] + y)) * m
out.append(y)
return (self.norm(torch.cat(out, 1).transpose(1, 2)).transpose(1, 2) + x) * m
class XlsrBranch(nn.Module):
"""XLS-R 1B on the standardised waveform; a learned mix of all layer outputs -> frames [B, F, 1280]"""
def __init__(self):
super().__init__()
from transformers import Wav2Vec2Model
self.backbone = Wav2Vec2Model(xlsr_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) # the branch's own head, kept for the weights file, unused
def frames(self, wav):
wav = (wav - wav.mean(1, keepdim=True)) / (wav.std(1, keepdim=True) + 1e-7)
hs = self.backbone(wav, output_hidden_states=True).hidden_states
w = torch.softmax(self.layer_weights, dim=0)
return torch.stack(hs).mul(w[:, None, None, None]).sum(0)
class W2vBertBranch(nn.Module):
"""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]"""
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))
dim = self.backbone.config.hidden_size
self.ms_proj = nn.Linear(dim, 256)
self.ms_blocks = nn.ModuleList([Res2Block(256, 4, 3, 2), Res2Block(256, 4, 3, 3)])
self.att = nn.Sequential(nn.Linear(256, 128), nn.Tanh(), nn.Linear(128, 1)) # the branch's own pooling and head,
self.head = nn.Linear(512, 1) # kept for the weights file, unused
@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 frames(self, wav):
return self.frames_feats(*self.features(wav))
def frames_feats(self, feats, mask):
mask[mask.sum(1) == 0, 0] = 1
m = mask[:, :, None].float()
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)
z = self.ms_proj(h.float()) * m
zt, mt = z.transpose(1, 2), m.transpose(1, 2)
for b in self.ms_blocks:
zt = b(zt, mt)
return zt.transpose(1, 2), mask
class Detector(nn.Module):
"""the two branches, their frames side by side per moment (512), two shared Res2 blocks, attentive statistics pooling
batch_invariant (edit 6, default True): in a padded batch the script keeps each item's XLS-R frames beyond its own
w2v-BERT length (only F = min over the *batch-max* lengths is cut), and the f_blocks' dilated convs read them at the
mask boundary, so a clip's logit depends on its batch-mates. Zeroing those frames reproduces the one-clip-at-a-time
result exactly (for B == 1 the mask is all ones, so this is a no-op and the math is the script's)."""
def __init__(self, batch_invariant=True):
super().__init__()
self.batch_invariant = batch_invariant
self.xl = XlsrBranch()
self.w2v = W2vBertBranch()
self.x_proj = nn.Linear(1280, 256)
self.x_blocks = nn.ModuleList([Res2Block(256, 4, 3, 2), Res2Block(256, 4, 3, 3)])
self.f_blocks = nn.ModuleList([Res2Block(512, 4, 3, 2), Res2Block(512, 4, 3, 3)])
self.att = nn.Sequential(nn.Linear(512, 128), nn.Tanh(), nn.Linear(128, 1))
self.head = nn.Linear(1024, 1)
def forward(self, wav):
return self.forward_feats(wav, *self.w2v.features(wav))
def forward_feats(self, wav, feats, mask): # split so the TRT engine is FFT-free (fbank stays in torch)
hx = self.xl.frames(wav) # [B, Fx, 1280]
zw, mw = self.w2v.frames_feats(feats, mask) # [B, Fw, 256], [B, Fw]
B = wav.shape[0]
zx = self.x_proj(hx.float())
zxt, mxt = zx.transpose(1, 2), torch.ones(B, 1, hx.shape[1], device=wav.device)
for b in self.x_blocks:
zxt = b(zxt, mxt)
zx = zxt.transpose(1, 2)
F = min(zx.shape[1], zw.shape[1])
zx, zw, m = zx[:, :F], zw[:, :F].float(), mw[:, :F]
if self.batch_invariant: # edit 6: no-op for B == 1 (all m == 1 over F); see the class docstring
zx = zx * m[:, :, None].to(zx.dtype)
zt, mt = torch.cat([zx, zw], dim=2).transpose(1, 2), m[:, None, :].float()
for b in self.f_blocks:
zt = b(zt, mt)
z = zt.transpose(1, 2)
a = torch.softmax(self.att(z).squeeze(-1).masked_fill(m == 0, float("-inf")), dim=1)[:, :, None]
mu = (a * z).sum(1)
var = (a * z ** 2).sum(1) - mu ** 2
return self.head(torch.cat([mu, torch.sqrt(var.clamp(min=1e-6))], dim=1)).squeeze(-1) # logit(fake)