ReDimNet2-ONNX / example.py
lzrhahahahaha's picture
Add ReDimNet2 ONNX graphs, FP32 and FP16, for all 20 released checkpoints
e562d0b
Raw History Blame Contribute Delete
4.2 kB
"""Score two speech clips with a ReDimNet2 ONNX graph: same speaker or not?
pip install onnxruntime numpy soundfile soxr huggingface_hub
python example.py a.wav b.wav # B6 (VoxCeleb2, lm), FP32, CPU
pip install "onnxruntime-gpu[cuda,cudnn]" numpy soundfile soxr huggingface_hub
python example.py a.wav b.wav --cuda # FP32 on an NVIDIA GPU
python example.py a.wav b.wav --cuda --fp16 # FP16 graph on an NVIDIA GPU
python example.py a.wav b.wav --model b3-vb2+vox2+cnc2_v0-lm
Prints both embeddings' shapes and their cosine score: the higher, the more
likely the two clips are the same speaker. Pick a decision threshold on your
own data; it depends on the checkpoint and the recording conditions.
"""
from __future__ import annotations
import argparse
import time
from pathlib import Path
import numpy as np
import onnxruntime as ort
import soundfile as sf
import soxr
REPO_ID = "lzrhahahahaha/ReDimNet2-ONNX"
SAMPLE_RATE = 16_000
MIN_SAMPLES = 720 # 45 ms: the shortest input the model accepts
def load_audio(path: Path) -> np.ndarray:
"""Any soundfile-readable file -> float32 mono 16 kHz, shape [1, N]."""
audio, rate = sf.read(path, dtype="float32", always_2d=True)
audio = audio.mean(axis=1)
if rate != SAMPLE_RATE:
audio = soxr.resample(audio, rate, SAMPLE_RATE)
if audio.shape[0] < MIN_SAMPLES:
raise ValueError(f"{path}: {audio.shape[0]} samples at 16 kHz; at least {MIN_SAMPLES} are needed")
return np.ascontiguousarray(audio[None], dtype=np.float32)
def session(path: Path, cuda: bool) -> ort.InferenceSession:
options = ort.SessionOptions()
# Flush denormal floats to zero on CPU. Some checkpoints produce them, and
# x86 CPUs process them many times slower; the embeddings do not change.
options.add_session_config_entry("session.set_denormal_as_zero", "1")
providers = ["CPUExecutionProvider"]
if cuda:
# Load the CUDA and cuDNN libraries installed by pip (onnxruntime-gpu[cuda,cudnn]).
ort.preload_dlls()
# ONNX Runtime's CUDA provider uses TF32 for FP32 convolutions and matrix
# products by default. use_tf32=0 keeps full FP32 accuracy (no effect on FP16).
providers.insert(0, ("CUDAExecutionProvider", {"use_tf32": "0"}))
return ort.InferenceSession(str(path), options, providers=providers)
def embed(model: ort.InferenceSession, wave: np.ndarray) -> np.ndarray:
"""float32 [1, N] at 16 kHz -> float32 [192] speaker embedding."""
return model.run(None, {"input_values": wave})[0][0]
def cosine(a: np.ndarray, b: np.ndarray) -> float:
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("first", type=Path)
parser.add_argument("second", type=Path)
parser.add_argument("--model", default="b6-vox2-lm", help="checkpoint name, e.g. b0-vox2-lm (see the README)")
parser.add_argument("--fp16", action="store_true", help="use the FP16 graph (meant for GPUs)")
parser.add_argument("--cuda", action="store_true")
parser.add_argument("--model-dir", type=Path, help="local copy of the repo (default: download the one file)")
args = parser.parse_args()
filename = f"{'fp16' if args.fp16 else 'fp32'}/{args.model}.onnx"
if args.model_dir is not None:
path = args.model_dir / filename
else:
from huggingface_hub import hf_hub_download
path = Path(hf_hub_download(REPO_ID, filename))
model = session(path, args.cuda)
first, second = load_audio(args.first), load_audio(args.second)
embed(model, first) # warm-up: the first call initialises the runtime
start = time.perf_counter()
a = embed(model, first)
elapsed = time.perf_counter() - start
b = embed(model, second)
print(f"{filename}: embeddings {a.shape} and {b.shape} "
f"({1000 * elapsed:.1f} ms for {first.shape[1] / SAMPLE_RATE:.2f} s of audio)")
print(f"cosine score: {cosine(a, b):.4f}")
if __name__ == "__main__":
main()