Pellav3 / source_parity.py
korallll's picture
Wrapper code (speech-spoof-bench)
cc05206 verified
Raw History Blame Contribute Delete
5.21 kB
# 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, 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 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"] = shim
from transformers import Wav2Vec2BertConfig, Wav2Vec2Config # noqa: E402
Wav2Vec2Config.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 = False
torch.backends.cuda.matmul.allow_tf32 = False
dev = "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.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")
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 ref
torch.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]))))