Wrapper code (speech-spoof-bench)
Browse filesFiles changed (15)
- .gitignoreAdded+20
- LICENSE.sourceAdded+30
- _net.pyAdded+275
- _upstream_pellav3_infer.pyAdded+235
- cmp_scores.pyAdded+22
- convert_ckpt.pyAdded+19
- implementation-notes.mdAdded+84
- meta.yamlAdded+34
- pellav3.pyAdded+65
- source_parity.pyAdded+84
- sweep.pyAdded+49
- test_pellav3.pyAdded+126
- tf_version_check.pyAdded+31
- w2vbert2_config.jsonAdded+81
- xlsr1b_config.jsonAdded+76
1234567891011121314151617181920# Hardware-specific TensorRT artifacts — rebuild per GPU with:# CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=<gpu> python trt_<module>.py export*.plan.trt_timing_*.cache
# Python__pycache__/*.py[cod].pytest_cache/
# Caches & logs.cache/*.log*.out
# Weights / exports (symlinked or rebuilt; re-hosted on the Hub)*.safetensors*.pt*.onnx*.onnx.data123456789101112131415161718192021222324252627282930Upstream: https://huggingface.co/Sadanie/pellav3-audio-deepfake-detector/tree/47b69420803c01de65af264ecdc2c5f35f2184f3The model card declares `license: mit`; the repository ships no LICENSE file, so the standard MIT text isreproduced below with the Hub owner as the copyright holder. It covers pellav3_infer.py (ported as _net.py,copied unchanged as _upstream_pellav3_infer.py for source_parity.py) and pellav3_detector.pt (re-hosted aspellav3_detector.safetensors, identical tensors).
MIT License
Copyright (c) 2026 Sadanie (Hugging Face user "Sadanie")
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.
Backbone configs (no weights): facebook/w2v-bert-2.0 @ da985ba0987f70aaeb84a80f2851cfac8c697a7b (MIT),facebook/wav2vec2-xls-r-1b @ 35eaea9a0ed0f97592277d79208e40ab8917d1e3 (Apache-2.0).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""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 mathimport os
import numpy as npimport torchimport torch.nn as nnfrom 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 = 16000CROP_S = 4.0CROP = 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235"""Pellav3 audio deepfake detector: minimal inference code.
pip install torch torchaudio transformers==4.48.3 numpy scipy pyloudnorm huggingface_hub (and ffmpeg on the PATH) python pellav3_infer.py clip1.wav clip2.mp3 ...
The weights are downloaded from the Hugging Face Hub on first use. To run from a local copy instead, pass it first:python pellav3_infer.py pellav3_detector.pt clip1.wav ...
The model reads each 4 second window with two speech encoders, XLS-R 1B on the waveform and w2v-BERT 2.0 on a melspectrogram, fuses their frames moment by moment and pools them into one score. A clip of 4 seconds or less is scoredonce; a longer clip is scored in 4 second windows every 2 seconds (the last window ends at the end of the clip) and thewindow logits are averaged."""import mathimport subprocessimport sysimport time
import numpy as npimport torchimport torch.nn as nn
SR = 16000CROP_S = 4.0CROP = int(CROP_S * SR)TARGET_LUFS = -23.0HUB_REPO = "Sadanie/pellav3-audio-deepfake-detector"WEIGHTS = "pellav3_detector.pt"XLSR = "facebook/wav2vec2-xls-r-1b"W2VBERT = "facebook/w2v-bert-2.0"
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 Wav2Vec2Config, Wav2Vec2Model self.backbone = Wav2Vec2Model(Wav2Vec2Config.from_pretrained(XLSR)) 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 Wav2Vec2BertConfig, Wav2Vec2BertModel self.backbone = Wav2Vec2BertModel(Wav2Vec2BertConfig.from_pretrained(W2VBERT)) 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): 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) 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): feats, mask = self.features(wav) 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""" def __init__(self): super().__init__() 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): hx = self.xl.frames(wav) # [B, Fx, 1280] zw, mw = self.w2v.frames(wav) # [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] 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)
def decode(path, start=0.0, dur=None): a = (["-ss", f"{start:.3f}"] if start > 0 else []) + (["-t", f"{dur:.3f}"] if dur else []) r = subprocess.run(["ffmpeg", "-v", "error", "-y"] + a + ["-i", path, "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"], capture_output=True) if r.returncode != 0: raise RuntimeError(r.stderr.decode(errors="replace")[-300:]) return np.frombuffer(r.stdout, dtype=np.float32).copy()
def loudness(x): try: import pyloudnorm as pyln
if len(x) >= int(0.4 * SR): v = pyln.Meter(SR).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): """mean removal and 20 Hz high-pass, centre 4 s crop, loudness to -23 LUFS, zero-pad to 4 s""" from scipy.signal import butter, sosfiltfilt
x = x - x.mean() if len(x) > 3 * SR // 100: x = sosfiltfilt(butter(2, 20.0, btype="highpass", fs=SR, output="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 views(path): """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""" whole = decode(path) d = len(whole) / SR if d <= CROP_S: return [view(whole)], d 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(decode(path, s, CROP_S)) for s in starts], d
def hub_weights(): from huggingface_hub import hf_hub_download
hf_hub_download(HUB_REPO, "config.json") return hf_hub_download(HUB_REPO, WEIGHTS)
def load_model(weights=None, device=None): device = device or ("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu") model = Detector().to(device) sd = torch.load(weights or hub_weights(), map_location=device) model.load_state_dict(sd["model"] if "model" in sd else sd, strict=True) return model.eval(), device
@torch.no_grad()def score(model, device, path): """-> (logit averaged over the clip's views, duration in s, seconds of model time)""" vs, d = views(path) t0 = time.time() with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=device == "cuda"): z = model(torch.from_numpy(np.stack(vs)).to(device)).float() if device == "cuda": torch.cuda.synchronize() return float(z.mean()), d, time.time() - t0
def main(): args = sys.argv[1:] weights = args.pop(0) if args and args[0].endswith(".pt") else None model, device = load_model(weights) for f in args: z, _, _ = score(model, device, f) p = 1 / (1 + math.exp(-z)) print(f"{f}: p_fake={p:.3f} -> {'FAKE' if p >= 0.5 else 'real'}")
if __name__ == "__main__": main()12345678910111213141516171819202122# cmp_scores.py A/scores.txt B/scores.txt -> n, Spearman, max |diff|import sysimport numpy as npfrom scipy.stats import spearmanr
def read(p): d = {} for line in open(p): parts = line.split() if len(parts) >= 2: try: d[parts[0]] = float(parts[-1]) except ValueError: pass return d
a, b = read(sys.argv[1]), read(sys.argv[2])k = sorted(set(a) & set(b))x, y = np.array([a[i] for i in k]), np.array([b[i] for i in k])print(f"n={len(k)} spearman={spearmanr(x, y).correlation:.6f} max_abs_diff={np.max(np.abs(x - y)):.4g}")12345678910111213141516171819"""One-time conversion: pellav3_detector.pt (plain pickled state_dict) -> pellav3_detector.safetensors (same keys/values).torch.load(weights_only=True) only (tensor-only unpickler); written next to the download, symlinked here.Usage: python -I convert_ckpt.py"""import hashlib, os, sysimport torchfrom safetensors.torch import save_file, load_fileHERE = os.path.dirname(os.path.abspath(__file__))D = os.path.join(HERE, "..", "_ckpt_dl", "Sadanie__pellav3-audio-deepfake-detector")src, out = os.path.join(D, "pellav3_detector.pt"), os.path.join(D, "pellav3_detector.safetensors")sd = torch.load(src, map_location="cpu", weights_only=True)assert isinstance(sd, dict) and all(isinstance(v, torch.Tensor) for v in sd.values())save_file({k: v.contiguous() for k, v in sd.items()}, out, metadata={"source": "HF Sadanie/pellav3-audio-deepfake-detector@47b69420803c01de65af264ecdc2c5f35f2184f3 pellav3_detector.pt"})back = load_file(out)assert back.keys() == sd.keys() and all(torch.equal(back[k], sd[k]) for k in sd)h = hashlib.sha256()with open(out, "rb") as f: for b in iter(lambda: f.read(1 << 24), b""): h.update(b)print("wrote", out, len(back), "tensors", sum(v.numel() for v in back.values()), "elements; sha256", h.hexdigest())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Pellav3 — implementation notes
Plan: `speech-spoof-bench/docs/plans/2026-11-09-thirteen-model-batch-arena-submission.md` (model #9).
## Source- HF `Sadanie/pellav3-audio-deepfake-detector` @ `47b69420803c01de65af264ecdc2c5f35f2184f3` (`_ckpt_dl/dl_batch4.py` → `_ckpt_dl/Sadanie__pellav3-audio-deepfake-detector/`). Card: `license: mit`, no LICENSE file, no paper, training data not described, "1.54 billion parameters, 16 kHz input". Files: `pellav3_detector.pt` (6.18 GB fp32, sha256 `ac6ae020ac5de06beee4f283ad1ea1fb1ae88dd8da19f483a602a032966695ec`), `pellav3_infer.py` (sha256 `c38f9a43…ae6e`), `config.json` (`{"name": …}` only), README.- Net (script): two views of each 4 s window — **XLS-R 1B** (48 layers) on the per-window standardised waveform with a softmax mix of its 49 hidden states → Linear(1280,256) + 2 Res2 blocks; **w2v-BERT 2.0** on 80-bin kaldi fbank (stacked 160-d, masked) with a 25-state mix → Linear(1024,256) + 2 Res2 blocks; frames concatenated (512) → 2 shared Res2 blocks → attentive statistics pooling → Linear(1024,1) = logit(fake).- `pellav3_infer.py` read in full (subprocess only for `ffmpeg` decoding, Hub only in `hub_weights()`); vendored into `_net.py`. Byte-identical copy `_upstream_pellav3_infer.py` (sha256 asserted) is used only by `source_parity.py`.- Backbones: the script itself builds them from configs (`Model(Config.from_pretrained(id))`, random init) and fills them from the .pt; we use the same configs, pinned and vendored: `xlsr1b_config.json` = facebook/wav2vec2-xls-r-1b @ `35eaea9a0ed0f97592277d79208e40ab8917d1e3`, `w2vbert2_config.json` = facebook/w2v-bert-2.0 @ `da985ba0987f70aaeb84a80f2851cfac8c697a7b` (only config.json downloaded, to `_ckpt_dl/facebook__*/`).- Weights: plain state_dict (1647 fp32 tensors, pos_conv already in `parametrizations.weight.original0/1` form) → `torch.load(weights_only=True)` without allow-list. `convert_ckpt.py` → `pellav3_detector.safetensors` (same keys/values, asserted; sha256 `6a721d66a0b9e1a1011193a66f245a4836dbfc036eb671cd1ff80d6e266d5a73`), symlinked here.
## transformers version (script pins 4.48.3; we run 5.3.0)4.48.3 is not available offline; the uv cache has **4.49.0**. `tf_version_check.py` builds both backbones with thePellav3 weights under 4.49.0 (dependency check stubbed) and under 5.3.0 and compares all hidden states on fixed inputs(XLS-R on a waveform batch with a zero-padded item; w2v-BERT on features with a padded attention mask), CPU FP32:**max |Δ| = 0.0 for both** (`logs_tf_version_check.txt`). 4.48.3 → 4.49.0 was not tested directly (no 4.48 wheeloffline); the wav2vec2 / wav2vec2_bert eval paths had no numerical changes in that patch range that we know of.
## Wrapper (`pellav3.py:Pellav3`, `_net.py`)- **Window**: the script scores clips ≤ 4 s once and longer clips with 4 s windows every 2 s (last window ending at the clip end), averaging window logits. Arena 4 s cap: the wrapper scores **one window, the grid's first one** (`decode(path, 0, 4.0)` == `x[:64000]`) through the script's `view()` (mean removal, 20 Hz 2nd-order Butterworth high-pass by `sosfiltfilt` on the window, centre crop (no-op), gain to −23 LUFS clipped ±40 dB, clip [−1, 1], zero-pad to 64000). For clips ≤ 4 s (all of J-SPAW_LA) this is exactly the authors' score. Zero-padding (not repeat) is kept because the w2v-BERT branch trims trailing zeros before its fbank, as the authors trained it.- **Loudness**: pyloudnorm is not installed here (see Pellav2 notes for details); the same re-implementation of `pyloudnorm.Meter(16000).integrated_loudness` is used, with the script's RMS fallback verbatim. Equality with the real package is untested (`test_matches_pyloudnorm_if_installed` is skipped).- **Batch invariance (edit 6)**: in the script's padded batch, F = min(XLS-R frames, *batch-max* w2v-BERT frames), and the XLS-R frames beyond an item's own w2v-BERT length are not zeroed, so the shared Res2 blocks' dilated convs read 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 smoke test). `Detector(batch_invariant=True)` zeros those frames; for B = 1 it is a no-op (asserted in tests), so the wrapper equals the authors' one-clip result in any batch (|Δ| 7.6e-6).- **Precision**: the script runs the net under `torch.autocast(bfloat16)` on CUDA. The wrapper is FP32 (TF32 off), per the batch instruction. Measured: the script's own bf16 `score()` vs our FP32 on the same single window (clips ≤ 4 s) differs by ≤ 0.18 logit (logits ~±20; bf16 resolution there is 0.125).- Score = −logit(fake). Strict load: all 1647 tensors map 1:1 onto `Detector.state_dict()` (set equality asserted, `strict=True`). Loaded but unused at inference (the script keeps them "for the weights file"), asserted allow-list `UNUSED_AT_INFERENCE`: `xl.backbone.masked_spec_embed`, `w2v.backbone.masked_spec_embed` (SpecAugment tokens), `xl.head.*`, `w2v.head.*`, `w2v.att.*` (per-branch auxiliary heads/pooling): 37,123 params.- Params: 1,544,130,575 total; 1,544,093,452 on the forward path.
## Checks- `test_pellav3.py`: first-window/view/window-grid, short-clip pad + RMS fallback, loudness target, reference tone, strict load + allow-list size, param count, eval mode, batch == single, batch_invariant no-op for B = 1, determinism, bona fide > spoof on J-SPAW. 11 passed, 1 skipped (pyloudnorm).- `source_parity.py` (`logs_source_parity.txt`), authors' Detector + decode (ffmpeg) + view/views/score on FLOAT wavs of 16 J-SPAW_LA clips + 0.3 s + 1.25 s + 6.6 s (3 windows) + 8.6 s (4 windows): - preprocessing identical (cap and all windows: max |Δ| 0.0); - **4 s cap** (wrapper batched FP32 vs script net on `view(decode(p, 0, 4))`, one clip, FP32): max |Δ| 7.6e-6; - **window off** (wrapper `windows()` + mean vs script `views()` + mean, FP32): max |Δ| 0.0; - script's own bf16 `score()` vs wrapper FP32 cap: 1.23 overall (long clips: different windows), 0.18 on ≤ 4 s clips.
## Batch sweep (`sweep.py`, 64000-sample view, 2026-11-10)| card | best | notes ||---|---|---|| RTX 4070 Ti SUPER (idx 2) | 26.3 utt/s @24 | plateau 8–32 → `batch_size = 24` || RTX 5060 Ti (idx 1) | 8.35 utt/s @2 | ~7 at bs ≥ 4 → 2 on 5060 |
## Sanity (PyTorch, idx 2)- Full J-SPAW_LA: **EER 0.000 %** (2397 trials, 0 skipped). Logits are saturated and fully separated (about ±20), which suggests possible training-data overlap (undisclosed). Flagged for the maintainer.
## TensorRT (`trt_pellav3.py`, sidecar `trt_pellav3.json`)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 ituses the dynamo exporter with external data. On RTX 4070 Ti SUPER, FP16 build Spearman was 0.99945, below 0.9999, soit fell back to **FP32**: build parity Spearman 1.0, max Δ 3.4e-4, best batch 8, 31.7 utt/s.Outcome (maintainer, 2026-11-10): **PyTorch only.** The full J-SPAW_LA run with `Pellav3TRT` skipped all 2397 clips(`'Detector' object has no attribute 'w2v'`: the TRT class drops a submodule the scoring path still uses), and theengine is only ~20% faster than PyTorch on the 4070 (31.7 vs 26.3 utt/s), so the class was not fixed and the 5060engine build was stopped. All drivers (lanes, EmoSpoofTTS, LRLspoof) use `pellav3:Pellav3`.12345678910111213141516171819202122232425262728293031323334system: name: "Pellav3" slug: "pellav3" description: > Pellav3 (Sadanie, November 2026): an open-weights two-view audio deepfake detector (1.54 B parameters). Each 4 s window is read by XLS-R 1B on the standardised waveform (softmax mix of all 49 hidden states) and by w2v-BERT 2.0 on 80-bin kaldi log-mel fbank features (25-state mix); each view is projected to 256-d and refined by two Res2 blocks, the frame sequences are concatenated per frame (512-d), refined by two shared Res2 blocks and pooled by attentive statistics pooling into Linear(1024,1) -> logit(fake). Authors' released checkpoint; training data undisclosed. Input as the authors' pellav3_infer.py view(): 16 kHz, mean removal, 20 Hz high-pass (zero-phase 2nd-order Butterworth), ITU-R BS.1770 loudness normalisation to -23 LUFS (pyloudnorm semantics), zero-pad to 4 s. Arena 4 s cap: one window, the first 4 s (64000 samples) of the authors' window grid (the authors average 4 s windows every 2 s over longer clips; clips <= 4 s are scored identically). score = -logit(fake), higher = bona fide. FP32 (TF32 off; the authors run bfloat16 autocast). code: "https://huggingface.co/Sadanie/pellav3-audio-deepfake-detector/blob/47b69420803c01de65af264ecdc2c5f35f2184f3/pellav3_infer.py" # Upstream (MIT): https://huggingface.co/Sadanie/pellav3-audio-deepfake-detector/blob/47b69420803c01de65af264ecdc2c5f35f2184f3/pellav3_detector.pt checkpoint: "https://huggingface.co/SpeechAntiSpoofingBenchmarks/Pellav3/blob/9bb345f5ec6dedc34f26458d5a5d545d9bb1c3ab/pellav3_detector.safetensors" 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-10notes: > Pellav3 = HF Sadanie/pellav3-audio-deepfake-detector @ 47b69420803c01de65af264ecdc2c5f35f2184f3, pellav3_detector.pt (sha256 ac6ae020ac5de06beee4f283ad1ea1fb1ae88dd8da19f483a602a032966695ec; 1647 fp32 tensors, weights_only=True, strict) re-hosted unchanged as pellav3_detector.safetensors (sha256 6a721d66a0b9e1a1011193a66f245a4836dbfc036eb671cd1ff80d6e266d5a73). MIT per the model card (no LICENSE file). Model classes and preprocessing vendored from pellav3_infer.py (sha256 c38f9a43..., read, never imported from the Hub cache); backbones built from the facebook/wav2vec2-xls-r-1b (@ 35eaea9a) and facebook/w2v-bert-2.0 (@ da985ba0) configs, as the script does, every weight from the checkpoint. The script pins transformers 4.48.3; backbone hidden states are bit-identical under 4.49.0 and the 5.3.0 used here. pyloudnorm's integrated loudness is re-implemented (not installed here). One edit: XLS-R frames past each clip's own w2v-BERT length are zeroed so a padded batch equals one-clip-at-a-time scoring (no-op for a single clip). Verified against the authors' Detector + decode/view 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' own bf16 path differs by <= 0.18 logit on the same window. Deviations: Arena 4 s cap (first window only instead of the mean over 4 s windows every 2 s; identical for clips <= 4 s), FP32 instead of bf16 autocast. Training data is undisclosed (no paper, card silent) -> no trained_on entries, but leakage cannot be ruled out: J-SPAW_LA EER is 0.0% with saturated, perfectly separated scores. No paper -> unpublished tier.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465from __future__ import annotations
import os
import numpy as npimport torchfrom safetensors.torch import load_filefrom speech_spoof_bench.model import AntiSpoofingModel
from _net import Detector, first_window
_DIR = os.path.dirname(os.path.abspath(__file__))# HF Sadanie/pellav3-audio-deepfake-detector @ 47b69420803c01de65af264ecdc2c5f35f2184f3 pellav3_detector.pt# (sha256 ac6ae020ac5de06beee4f283ad1ea1fb1ae88dd8da19f483a602a032966695ec) -> convert_ckpt.py -> safetensors# (sha256 6a721d66a0b9e1a1011193a66f245a4836dbfc036eb671cd1ff80d6e266d5a73, identical keys/values)_CKPT = os.path.join(_DIR, "pellav3_detector.safetensors")N_TENSORS = 1647# Loaded by the strict load but not on the inference path (the script keeps them "for the weights file, unused"):UNUSED_AT_INFERENCE = { "xl.backbone.masked_spec_embed": "XLS-R SpecAugment mask token (training only)", "w2v.backbone.masked_spec_embed": "w2v-BERT SpecAugment mask token (training only)", "xl.head.weight": "XLS-R branch's own head (branch-level auxiliary)", "xl.head.bias": "same", "w2v.head.weight": "w2v-BERT branch's own head (auxiliary)", "w2v.head.bias": "same", "w2v.att.0.weight": "w2v-BERT branch's own attention pooling (auxiliary)", "w2v.att.0.bias": "same", "w2v.att.2.weight": "same", "w2v.att.2.bias": "same",}
def load_state(path=_CKPT): sd = load_file(path) assert len(sd) == N_TENSORS, len(sd) return sd
def build_net(path=_CKPT): net = Detector() r = net.load_state_dict(load_state(path), strict=True) # every checkpoint tensor consumed, none missing assert not r.missing_keys and not r.unexpected_keys return net
class Pellav3(AntiSpoofingModel): name = "Pellav3" expected_sample_rate = 16000 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)
def load(self) -> None: self.device = "cuda" if torch.cuda.is_available() else "cpu" torch.backends.cudnn.allow_tf32 = False torch.backends.cuda.matmul.allow_tf32 = False self.net = build_net().to(self.device).eval() if self.device == "cuda" and "5060" in torch.cuda.get_device_name(): self.batch_size = 2 # sweep 2026-11-10: RTX 5060 Ti 8.35 utt/s @2, ~7 at bs >= 4
@torch.no_grad() def score_batch(self, audios, srs): x = np.stack([first_window(a) for a in audios]) logit_fake = self.net(torch.from_numpy(x).to(self.device)).float() # pellav3_infer.py: p_fake = sigmoid(logit) -> score = -logit(fake), higher = bona fide return (-logit_fake).cpu().tolist()
def unload(self) -> None: self.net = None if torch.cuda.is_available(): torch.cuda.empty_cache()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# 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# and two long (3x / 4x concat, multi-window) clips.# _upstream_pellav3_infer.py is a byte-identical, fully-read copy of the Hub script (sha256 asserted); it is imported# from this model dir, never from the Hub cache. Patches (no math changes):# * Wav2Vec2Config/Wav2Vec2BertConfig.from_pretrained(<hub id>) -> the vendored, commit-pinned config json# * weights: the original pellav3_detector.pt via torch.load(weights_only=True), strict, into the authors' Detector# * pyloudnorm is NOT installed here: a shim whose Meter.integrated_loudness is _net.integrated_loudness is injected# so the script takes its pyloudnorm branch (it would silently fall back to RMS otherwise). Loudness is therefore# not independently checked here; see implementation-notes.md.# * clips are written as FLOAT wavs; the script's own decode() (ffmpeg) and views() are used unchanged.# Rows printed:# cap : wrapper (first 4 s window, FP32, batched) vs script net on [view(decode(path, 0, 4.0))], FP32, one clip at a time# full : wrapper's windows() + mean of window logits (FP32) vs the script's views() + mean, FP32 ("window off")# bf16 : the script's own score() (bfloat16 autocast, all windows) vs the wrapper's FP32 cap score (information)import hashlib, io, os, sys, tempfile, typesimport numpy as np, pyarrow.parquet as pq, soundfile as sf, torch
HERE = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, HERE)import _netimport pellav3 as W
SRC = os.path.join(HERE, "_upstream_pellav3_infer.py")assert hashlib.sha256(open(SRC, "rb").read()).hexdigest() == "c38f9a431eb5fd245ddc96f8e362d275c2eca1fba8c9d88f2a0686d68362ae6e"PT = os.path.join(HERE, "..", "_ckpt_dl", "Sadanie__pellav3-audio-deepfake-detector", "pellav3_detector.pt")
shim = types.ModuleType("pyloudnorm")shim.Meter = lambda rate: types.SimpleNamespace(integrated_loudness=lambda x: _net.integrated_loudness(x, rate))sys.modules["pyloudnorm"] = shimfrom transformers import Wav2Vec2BertConfig, Wav2Vec2Config # noqa: E402Wav2Vec2Config.from_pretrained = classmethod(lambda cls, *a, **k: _net.xlsr_config())Wav2Vec2BertConfig.from_pretrained = classmethod(lambda cls, *a, **k: _net.w2vbert_config())import _upstream_pellav3_infer as U # noqa: E402
torch.backends.cudnn.allow_tf32 = Falsetorch.backends.cuda.matmul.allow_tf32 = Falsedev = "cuda"
t = pq.read_table(os.path.join(HERE, "..", "J-SPAW_LA", "data", "test-00000-of-00001.parquet"), columns=["audio", "label"]).to_pylist()rows = [x for x in t if x["label"] == 0][:8] + [x for x in t if x["label"] == 1][:8]auds = [sf.read(io.BytesIO(x["audio"]["bytes"]), dtype="float32")[0] for x in rows]auds += [auds[0][:4800], auds[1][:20000], np.concatenate([auds[9]] * 3), np.concatenate([auds[2]] * 4)]N = len(auds)
# ---- authors' path (their Detector, their decode/view/views/score) ----ref = U.Detector()r = ref.load_state_dict(torch.load(PT, map_location="cpu", weights_only=True), strict=True)print("source strict load:", r)ref = ref.to(dev).eval()src_cap, src_full, src_bf16, pre_cap, pre_full = [], [], [], 0.0, 0.0with tempfile.TemporaryDirectory() as td, torch.no_grad(): for i, a in enumerate(auds): p = os.path.join(td, f"{i}.wav"); sf.write(p, a, 16000, subtype="FLOAT") v0 = U.view(U.decode(p, 0.0, U.CROP_S)) pre_cap = max(pre_cap, float(np.max(np.abs(v0 - _net.first_window(a))))) src_cap.append(-float(ref(torch.from_numpy(v0)[None].to(dev)))) vs, _ = U.views(p) ours_vs = _net.windows(a) assert len(vs) == len(ours_vs), (len(vs), len(ours_vs)) pre_full = max(pre_full, max(float(np.max(np.abs(x - y))) for x, y in zip(vs, ours_vs))) src_full.append(-float(ref(torch.from_numpy(np.stack(vs)).to(dev)).float().mean())) src_bf16.append(-U.score(ref, dev, p)[0])del reftorch.cuda.empty_cache()
# ---- wrapper ----m = W.Pellav3(); m.load()ours_cap = np.array(m.score_batch(auds, [16000] * N))with torch.no_grad(): ours_full = np.array([-float(m.net(torch.from_numpy(np.stack(_net.windows(a))).to(dev)).float().mean()) for a in auds])src_cap, src_full, src_bf16 = map(np.array, (src_cap, src_full, src_bf16))print("lens", [len(a) for a in auds])print("n_windows", [len(_net.windows(a)) for a in auds])print("ours cap ", np.round(ours_cap, 4))print("source cap ", np.round(src_cap, 4))print("ours full ", np.round(ours_full, 4))print("source full", np.round(src_full, 4))print("source bf16", np.round(src_bf16, 4))print("preprocess max_abs_diff cap (script view(decode(p,0,4)) vs _net.first_window)", pre_cap)print("preprocess max_abs_diff full (script views() vs _net.windows)", pre_full)print("cap max_abs_diff (wrapper batched FP32 vs script FP32 one clip)", float(np.max(np.abs(ours_cap - src_cap))))print("full max_abs_diff (window off, FP32)", float(np.max(np.abs(ours_full - src_full))))print("bf16 script score() vs wrapper FP32 cap: max_abs_diff", float(np.max(np.abs(src_bf16 - ours_cap))), "| on clips <= 4 s (same window):", float(np.max(np.abs(src_bf16[:18] - ours_cap[:18]))))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# sweep.pyfrom __future__ import annotationsimport timefrom statistics import medianimport numpy as npimport torchimport os as _os, sys as _sys_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) # python -I drops the script dirimport pellav3
_CUT = 64000 # both Pella nets see exactly 64000 samples (4 s view)
def time_batch_sizes(): print("device", torch.cuda.get_device_name()) m = pellav3.Pellav3() m.load() import os if os.environ.get("SWEEP_TF32") is not None: torch.backends.cudnn.allow_tf32 = torch.backends.cuda.matmul.allow_tf32 = bool(int(os.environ["SWEEP_TF32"])) print("cudnn.allow_tf32", torch.backends.cudnn.allow_tf32) cuda = getattr(m, "device", "cpu") == "cuda" results = {} print("=== batch-size sweep ===") for bs in [1, 2, 4, 8, 12, 16, 24, 32]: audios = [np.random.randn(_CUT).astype(np.float32) for _ in range(bs)] srs = [16000] * bs try: m.score_batch(audios, srs) # warm-up if cuda: torch.cuda.synchronize() reps = [] for _ in range(5): if cuda: torch.cuda.synchronize() t0 = time.perf_counter() m.score_batch(audios, srs) if cuda: torch.cuda.synchronize() reps.append(time.perf_counter() - t0) med = median(reps); ups = bs / med results[bs] = ups print(f"bs={bs:3d} median={med*1000:8.3f} ms utt/s={ups:8.2f}") except torch.cuda.OutOfMemoryError: print(f"bs={bs:3d} OOM (skipped)") if cuda: torch.cuda.empty_cache() m.unload() best = max(results, key=results.get) print(f"best batch_size = {best} (utt/s={results[best]:.2f})") return best, results
if __name__ == "__main__": time_batch_sizes()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import ioimport os
import numpy as npimport pytestimport torch
import _netimport pellav3 as P
N_PARAMS = 1_544_130_575 # every checkpoint tensor (1647) is a Detector parameterN_PARAMS_FWD = 1_544_093_452 # minus the asserted unused-at-inference allow-list (37,123: 2 mask tokens, 2 branch heads, branch att)
# ---------------------------------------------------------------- preprocessing (CPU) ----def test_first_window_long(): rng = np.random.default_rng(1) x = rng.standard_normal(100_001).astype(np.float32) * 0.1 out = _net.first_window(x) assert out.shape == (64000,) and out.dtype == np.float32 assert np.array_equal(out, _net.view(x[:64000])) seg = x[:64000] hp = _net.sosfiltfilt(_net._HP_SOS, seg - seg.mean()).astype(np.float32) # high-pass on the window, then gain g = out[1000:2000] / hp[1000:2000] assert np.allclose(g, g[0], rtol=1e-4)
def test_view_centre_crop_and_windows_grid(): x = np.random.default_rng(4).standard_normal(16000 * 9 + 123).astype(np.float32) * 0.1 off = (len(x) - 64000) // 2 v = _net.view(x) assert v.shape == (64000,) ws = _net.windows(x) # d = 9.0077 s -> starts 0, 2, 4, 5.008 (last ends at the end) assert len(ws) == 4 and np.array_equal(ws[0], _net.first_window(x)) assert np.array_equal(ws[-1], _net.view(x[80128:80128 + 64000])) assert len(_net.windows(x[:64000])) == 1 and off > 0
def test_short_zero_pad_and_fallback(): x = np.linspace(-0.2, 0.3, 3000, dtype=np.float32) # < 0.4 s -> RMS fallback loudness out = _net.first_window(x) assert out.shape == (64000,) and not out[3000:].any() and out[:3000].any() assert np.array_equal(_net.first_window(np.zeros(0, np.float32)), np.zeros(64000, np.float32))
def test_loudness_target(): rng = np.random.default_rng(2) x = rng.standard_normal(48000).astype(np.float32) * 0.01 y = _net.first_window(x) assert abs(_net.integrated_loudness(y[:48000].astype(np.float64)) - _net.TARGET_LUFS) < 0.05
def test_bs1770_reference_tone(): t = np.arange(16000 * 5) / 16000 # pyloudnorm's cookbook K-weighting at 16 kHz: 0 dBFS 997 Hz mono sine -> -3.08 LUFS (BS.1770 48 kHz ref -3.01) assert abs(_net.integrated_loudness(np.sin(2 * np.pi * 997 * t)) - (-3.0832)) < 1e-3
def test_matches_pyloudnorm_if_installed(): pyln = pytest.importorskip("pyloudnorm") rng = np.random.default_rng(3) for n in (6400, 20000, 64000, 64000 + 77): x = rng.standard_normal(n) * np.linspace(0.001, 0.3, n) assert _net.integrated_loudness(x) == pytest.approx(pyln.Meter(16000).integrated_loudness(x), abs=1e-9)
# ---------------------------------------------------------------- weights ----def test_strict_load_all_tensors_used(): sd = P.load_state() net = _net.Detector() assert set(sd) == set(net.state_dict()) # every tensor consumed, nothing missing r = net.load_state_dict(sd, strict=True) assert not r.missing_keys and not r.unexpected_keys assert set(P.UNUSED_AT_INFERENCE) <= set(sd) assert sum(sd[k].numel() for k in P.UNUSED_AT_INFERENCE) == N_PARAMS - N_PARAMS_FWD
@pytest.fixture(scope="module")def model(): m = P.Pellav3(); m.load() yield m m.unload()
def test_eval_mode_and_params(model): assert not any(mod.training for mod in model.net.modules()) n = sum(p.numel() for p in model.net.parameters()) assert n == N_PARAMS
def test_batch_matches_single(model): rng = np.random.default_rng(0) 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))] batched = model.score_batch(a, [16000] * 4) single = [model.score_batch([x], [16000])[0] for x in a] assert len(batched) == 4 and all(np.isfinite(batched)) assert np.allclose(batched, single, atol=1e-3)
def test_batch_invariant_flag_is_noop_for_single(model): x = torch.from_numpy(np.stack([_net.first_window(np.random.default_rng(5).standard_normal(30000).astype(np.float32) * 0.1)])) x = x.to(model.device) with torch.no_grad(): a = model.net(x).item() model.net.batch_invariant = False b = model.net(x).item() model.net.batch_invariant = True assert a == b
def test_deterministic(model): a = [np.random.randn(40000).astype(np.float32) * 0.1 for _ in range(3)] assert model.score_batch(a, [16000] * 3) == model.score_batch(a, [16000] * 3)
def test_sign_bonafide_higher(model): import pyarrow.parquet as pq import soundfile as sf d = os.path.join(os.path.dirname(P.__file__), "..", "J-SPAW_LA", "data") t = pq.read_table(os.path.join(d, "test-00000-of-00001.parquet"), columns=["audio", "label"]).to_pylist() bona = [r for r in t if r["label"] == 0][:8] spoof = [r for r in t if r["label"] == 1][:8] dec = lambda rows: [sf.read(io.BytesIO(r["audio"]["bytes"]), dtype="float32")[0] for r in rows] sb = model.score_batch(dec(bona), [16000] * 8) ss = model.score_batch(dec(spoof), [16000] * 8) assert np.mean(sb) > np.mean(ss)12345678910111213141516171819202122232425262728293031# 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 filesimport sysif sys.argv[1]: import types; sys.path.insert(0, sys.argv[1]) _m = types.ModuleType("transformers.dependency_versions_check"); _m.dep_version_check = lambda *a, **k: None sys.modules["transformers.dependency_versions_check"] = _mimport numpy as np, torch, transformersfrom safetensors.torch import load_fileprint("transformers", transformers.__version__, transformers.__file__)from transformers import Wav2Vec2Config, Wav2Vec2Model, Wav2Vec2BertConfig, Wav2Vec2BertModelimport os; B = os.path.dirname(os.path.abspath(__file__)) + "/"sd = load_file(B + "pellav3_detector.safetensors")torch.manual_seed(0)wav = torch.randn(2, 64000) * 0.1wav[1, 40000:] = 0feats = torch.randn(2, 199, 160); mask = torch.ones(2, 199, dtype=torch.long); mask[1, 120:] = 0out = {}xl = Wav2Vec2Model(Wav2Vec2Config.from_json_file(B + "xlsr1b_config.json")).eval()sub = {k[len("xl.backbone."):]: v for k, v in sd.items() if k.startswith("xl.backbone.")}print(xl.load_state_dict(sub, strict=True))with torch.no_grad(): w = (wav - wav.mean(1, keepdim=True)) / (wav.std(1, keepdim=True) + 1e-7) out["xl"] = torch.stack(xl(w, output_hidden_states=True).hidden_states)del xlbt = Wav2Vec2BertModel(Wav2Vec2BertConfig.from_json_file(B + "w2vbert2_config.json")).eval()sub = {k[len("w2v.backbone."):]: v for k, v in sd.items() if k.startswith("w2v.backbone.")}print(bt.load_state_dict(sub, strict=True))with torch.no_grad(): out["w2v"] = torch.stack(bt(input_features=feats, attention_mask=mask, output_hidden_states=True).hidden_states)torch.save(out, sys.argv[2])print({k: tuple(v.shape) for k, v in out.items()})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081{ "activation_dropout": 0.0, "adapter_act": "relu", "adapter_kernel_size": 3, "adapter_stride": 2, "add_adapter": false, "apply_spec_augment": false, "architectures": [ "Wav2Vec2BertModel" ], "attention_dropout": 0.0, "bos_token_id": 1, "classifier_proj_size": 768, "codevector_dim": 768, "conformer_conv_dropout": 0.1, "contrastive_logits_temperature": 0.1, "conv_depthwise_kernel_size": 31, "ctc_loss_reduction": "sum", "ctc_zero_infinity": false, "diversity_loss_weight": 0.1, "eos_token_id": 2, "feat_proj_dropout": 0.0, "feat_quantizer_dropout": 0.0, "feature_projection_input_dim": 160, "final_dropout": 0.1, "hidden_act": "swish", "hidden_dropout": 0.0, "hidden_size": 1024, "initializer_range": 0.02, "intermediate_size": 4096, "layer_norm_eps": 1e-05, "layerdrop": 0.1, "left_max_position_embeddings": 64, "mask_feature_length": 10, "mask_feature_min_masks": 0, "mask_feature_prob": 0.0, "mask_time_length": 10, "mask_time_min_masks": 2, "mask_time_prob": 0.05, "max_source_positions": 5000, "model_type": "wav2vec2-bert", "num_adapter_layers": 1, "num_attention_heads": 16, "num_codevector_groups": 2, "num_codevectors_per_group": 320, "num_hidden_layers": 24, "num_negatives": 100, "output_hidden_size": 1024, "pad_token_id": 0, "position_embeddings_type": "relative_key", "proj_codevector_dim": 768, "right_max_position_embeddings": 8, "rotary_embedding_base": 10000, "tdnn_dilation": [ 1, 2, 3, 1, 1 ], "tdnn_dim": [ 512, 512, 512, 512, 1500 ], "tdnn_kernel": [ 5, 3, 3, 1, 1 ], "torch_dtype": "float32", "transformers_version": "4.37.0.dev0", "use_intermediate_ffn_before_adapter": false, "use_weighted_layer_sum": false, "vocab_size": null, "xvector_output_dim": 512}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576{ "activation_dropout": 0.0, "apply_spec_augment": true, "architectures": [ "Wav2Vec2ForPreTraining" ], "attention_dropout": 0.1, "bos_token_id": 1, "codevector_dim": 1024, "contrastive_logits_temperature": 0.1, "conv_bias": true, "conv_dim": [ 512, 512, 512, 512, 512, 512, 512 ], "conv_kernel": [ 10, 3, 3, 3, 3, 2, 2 ], "conv_stride": [ 5, 2, 2, 2, 2, 2, 2 ], "ctc_loss_reduction": "sum", "ctc_zero_infinity": false, "diversity_loss_weight": 0.1, "do_stable_layer_norm": true, "eos_token_id": 2, "feat_extract_activation": "gelu", "feat_extract_dropout": 0.0, "feat_extract_norm": "layer", "feat_proj_dropout": 0.1, "feat_quantizer_dropout": 0.0, "final_dropout": 0.0, "gradient_checkpointing": false, "hidden_act": "gelu", "hidden_dropout": 0.1, "hidden_size": 1280, "initializer_range": 0.02, "intermediate_size": 5120, "layer_norm_eps": 1e-05, "layerdrop": 0.1, "mask_feature_length": 10, "mask_feature_prob": 0.0, "mask_time_length": 10, "mask_time_prob": 0.075, "model_type": "wav2vec2", "num_attention_heads": 16, "num_codevector_groups": 2, "num_codevectors_per_group": 320, "num_conv_pos_embedding_groups": 16, "num_conv_pos_embeddings": 128, "num_feat_extract_layers": 7, "num_hidden_layers": 48, "num_negatives": 100, "pad_token_id": 0, "proj_codevector_dim": 1024, "torch_dtype": "float32", "transformers_version": "4.12.0.dev0", "use_weighted_layer_sum": false}.gitignoreAdded+20
LICENSE.sourceAdded+30
_net.pyAdded+275
_upstream_pellav3_infer.pyAdded+235
cmp_scores.pyAdded+22
convert_ckpt.pyAdded+19
implementation-notes.mdAdded+84
meta.yamlAdded+34
pellav3.pyAdded+65
source_parity.pyAdded+84
sweep.pyAdded+49
test_pellav3.pyAdded+126
tf_version_check.pyAdded+31
w2vbert2_config.jsonAdded+81
xlsr1b_config.jsonAdded+76