Download source_parity.py from SpeechAntiSpoofingBenchmarks/Pellav2: direct link, hf CLI and curl.
- Browser
- Download file 3.55 kB
-
https://huggingface.co/SpeechAntiSpoofingBenchmarks/Pellav2/resolve/main/source_parity.py
- Command line
-
hf download hf://SpeechAntiSpoofingBenchmarks/Pellav2/source_parity.py
-
curl -L -o source_parity.py https://huggingface.co/SpeechAntiSpoofingBenchmarks/Pellav2/resolve/main/source_parity.py
3.55 kB
| # source_parity.py -- the authors' pellav2_infer.py path (Detector + load_clip, one clip at a time, as main()) vs this | |
| # wrapper (batched), on 16 J-SPAW_LA clips + a short (0.3 s, RMS-fallback branch) + a 1.25 s + a long (4x concat) clip. | |
| # _upstream_pellav2_infer.py is a byte-identical, fully-read copy of the Hub script (sha256 asserted below); it is | |
| # imported from this model dir, never from the Hub cache. Patches applied to it (no math changes): | |
| # * Wav2Vec2BertModel.from_pretrained("facebook/w2v-bert-2.0") -> Wav2Vec2BertModel(vendored config) (no Hub weights) | |
| # * weights: the original pellav2_detector.pt via torch.load(weights_only=True), strict, into the authors' Detector | |
| # * pyloudnorm is NOT installed here: a shim module whose Meter.integrated_loudness is _net.integrated_loudness is | |
| # injected so the script takes its pyloudnorm branch (otherwise it silently falls back to RMS). The loudness step is | |
| # therefore not independently checked here; see implementation-notes.md. | |
| # * clips are written as FLOAT wavs to a temp dir and read by the script's own load_clip (sf.read). | |
| # The script itself uses a 4 s centre crop (no full-utterance mode), so "window off" == "4 s cap" for Pellav2. | |
| import hashlib, io, os, sys, tempfile, types | |
| import 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 _net | |
| import pellav2 as W | |
| SRC = os.path.join(HERE, "_upstream_pellav2_infer.py") | |
| assert hashlib.sha256(open(SRC, "rb").read()).hexdigest() == "bf13cc97e5f0466b6dd6797afce7abe9befc61ec8817c05cbe505f88a29c6a67" | |
| PT = os.path.join(HERE, "..", "_ckpt_dl", "Sadanie__pellav2-audio-deepfake-detector", "pellav2_detector.pt") | |
| shim = types.ModuleType("pyloudnorm") | |
| shim.Meter = lambda rate: types.SimpleNamespace(integrated_loudness=lambda x: _net.integrated_loudness(x, rate)) | |
| sys.modules["pyloudnorm"] = shim | |
| from transformers import Wav2Vec2BertModel # noqa: E402 | |
| Wav2Vec2BertModel.from_pretrained = classmethod(lambda cls, *a, **k: cls(_net.w2vbert_config())) | |
| import _upstream_pellav2_infer as U # noqa: E402 | |
| torch.backends.cudnn.allow_tf32 = False | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| dev = "cuda" | |
| 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() | |
| m = W.Pellav2(); m.load() | |
| 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[2]] * 4)] | |
| ours = np.array(m.score_batch(auds, [16000] * len(auds))) | |
| theirs, pre = [], 0.0 | |
| with 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") | |
| v = U.load_clip(p) | |
| pre = max(pre, float(np.max(np.abs(v - _net.preprocess(a))))) | |
| x = torch.from_numpy(v)[None].to(dev) | |
| theirs.append(-float(ref(x))) # script: p_fake = sigmoid(logit); our score = -logit | |
| theirs = np.array(theirs) | |
| print("lens", [len(a) for a in auds]) | |
| print("ours ", np.round(ours, 4)) | |
| print("source", np.round(theirs, 4)) | |
| print("preprocess max_abs_diff (script load_clip vs _net.preprocess)", pre) | |
| print("max_abs_diff", float(np.max(np.abs(ours - theirs)))) | |