UTCN-XLSR2B-LogReg / source_parity.py
korallll's picture
Wrapper code (speech-spoof-bench)
47cc53f verified
Raw History Blame Contribute Delete
4.56 kB
# source_parity.py -- the authors' app.py inference path vs this wrapper, on 16 J-SPAW_LA clips (+ a short and a long one).
# Authors' path (HF DavidCombei/deepfake-detection @ 5f39744b, audio-detection_core/app.py), reproduced here verbatim
# (app.py lives in an HF download dir, so it is read and copied, never imported):
# CustomWav2Vec2Model.from_pretrained(<truncated dir>) (safetensors) + Wav2Vec2FeatureExtractor with the
# facebook/wav2vec2-xls-r-2b preprocessor_config (@3b6d89d0, vendored as xlsr2b_preprocessor_config.json),
# outputs.hidden_states[9] -> torch.mean(dim=1) -> sklearn LogisticRegression.decision_function ->
# sklearn MinMaxScaler.transform. The two sklearn objects are rebuilt from lr_head.npz (the joblib is never loaded),
# so sklearn's own decision_function / transform code is exercised.
# Two modes: (a) window off: whole clip as one app.py segment (clips < 60 s) vs the wrapper's net on the unpadded clip;
# (b) 4 s cap: both fed crop_repeat(clip) (first 64600 / repeat-pad), wrapper batched via score_batch.
import io, json, os, sys
import numpy as np, pyarrow.parquet as pq, soundfile as sf, torch
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import MinMaxScaler
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import _net
import utcn_xlsr2b_logreg as W
torch.backends.cudnn.allow_tf32 = False
torch.backends.cuda.matmul.allow_tf32 = False
device = torch.device("cuda")
class CustomWav2Vec2Model(Wav2Vec2Model): # app.py verbatim
def __init__(self, config):
super().__init__(config)
self.encoder.layers = self.encoder.layers[:9]
fe = Wav2Vec2FeatureExtractor(**{k: v for k, v in json.load(open(os.path.join(HERE, "xlsr2b_preprocessor_config.json"))).items()
if k != "feature_extractor_type"})
model = CustomWav2Vec2Model.from_pretrained(_net.W2V_DIR).to(device).eval()
z = np.load(_net.HEAD_NPZ)
classifier = LogisticRegression()
classifier.coef_, classifier.intercept_, classifier.classes_ = z["coef"][None], np.array([z["intercept"]]), z["classes"]
classifier.n_features_in_ = 1920
scaler = MinMaxScaler()
scaler.scale_, scaler.min_, scaler.n_features_in_, scaler.clip = np.array([z["scaler_scale"]]), np.array([z["scaler_min"]]), 1, False
def authors(segment, sr=16000): # app.py HuggingFaceFeatureExtractor.__call__ + process_audio per-segment body
inputs = fe(segment, sampling_rate=sr, return_tensors="pt", padding=True)
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
features = model(**inputs, output_hidden_states=True).hidden_states[9]
features_avg = torch.mean(features, dim=1).cpu().numpy().reshape(1, -1)
decision_score = classifier.decision_function(features_avg)
return float(scaler.transform(decision_score.reshape(-1, 1)).flatten()[0])
m = W.UTCNXLSR2BLogReg(); m.load()
d = os.path.join(HERE, "..", "J-SPAW_LA", "data")
t = pq.read_table(os.path.join(d, "test-00000-of-00001.parquet"), columns=["audio"]).slice(0, 16).column("audio").to_pylist()
auds = [sf.read(io.BytesIO(x["bytes"]), dtype="float32")[0] for x in t]
auds.append(auds[0][:20000]); auds.append(np.concatenate([auds[1]] * 4)) # short + long cases
print("lens", [len(a) for a in auds])
ours_off = np.array([m.head(m.features(_net.normalize(a)[None]))[0] for a in auds])
theirs_off = np.array([authors(a) for a in auds])
ours_cap = np.array(m.score_batch(auds, [16000] * len(auds)))
theirs_cap = np.array([authors(_net.crop_repeat(a)) for a in auds])
print("source attn_implementation (transformers default):", model.config._attn_implementation)
# Same authors' path with eager attention (what the wrapper uses; SDPA FP32 kernels jitter ~1e-3 here on the scaled score)
model.set_attn_implementation("eager")
print("source attn_implementation now:", model.config._attn_implementation)
theirs_off_e = np.array([authors(a) for a in auds])
theirs_cap_e = np.array([authors(_net.crop_repeat(a)) for a in auds])
for tag, o, s in (("window off, source sdpa", ours_off, theirs_off), ("4 s cap, source sdpa", ours_cap, theirs_cap),
("window off, source eager", ours_off, theirs_off_e), ("4 s cap, source eager", ours_cap, theirs_cap_e)):
print(f"[{tag}] ours ", np.round(o, 5))
print(f"[{tag}] source", np.round(s, 5))
print(f"[{tag}] max_abs_diff", float(np.max(np.abs(o - s))))
print("app.py threshold - 5e-3 =", float(z["threshold"]) - 5e-3)