import hashlib import io import os import numpy as np import pytest import torch import _net import rawnetlite as R SHA256 = "6154d91f34f0a49d58e30bac602915f6b6853419419804be63b5274603891a9b" N_PARAMS = 240_769 # trainable parameters (BN running stats / num_batches_tracked are buffers) def test_prep_peak_norm_then_prefix(): x = np.concatenate([np.full(48000, 0.1, np.float32), np.array([-0.5], np.float32), np.zeros(999, np.float32)]) out = _net.prep_np(x) # peak over the WHOLE clip (0.5 lies beyond the 3 s crop) assert out.shape == (48000,) and out.dtype == np.float32 and np.allclose(out, 0.2) def test_prep_short_right_zero_pad(): x = np.linspace(-0.25, 0.5, 1001, dtype=np.float32) out = _net.prep_np(x) assert np.allclose(out[:1001], x / 0.5) and not out[1001:].any() and abs(out.max() - 1.0) < 1e-7 assert not _net.prep_np(np.zeros(5000, np.float32)).any() # silent clip -> zeros (source: NaN) assert not _net.prep_np(np.zeros(0, np.float32)).any() def test_checkpoint_sha256(): assert hashlib.sha256(open(R._CKPT, "rb").read()).hexdigest() == SHA256 def test_strict_load_all_tensors_used(): sd = R.load_state() assert len(sd) == 61 net = _net.RawNetLite() assert set(net.state_dict()) == set(sd) r = net.load_state_dict(sd, strict=True) assert not r.missing_keys and not r.unexpected_keys @pytest.fixture(scope="module") def model(): m = R.RawNetLite(); m.load() yield m m.unload() def test_eval_and_params(model): assert not any(mod.training for mod in model.net.modules()) assert sum(p.numel() for p in model.net.parameters()) == N_PARAMS def test_logit_matches_source_sigmoid(model): x = torch.randn(3, 1, 48000, device=model.device) * 0.3 with torch.no_grad(): assert torch.allclose(torch.sigmoid(model.net.forward_logit(x)), model.net(x), atol=1e-6) def test_shapes_and_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-4) 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_scale_invariant(model): x = np.random.default_rng(2).standard_normal(30000).astype(np.float32) * 0.1 s1, s2 = model.score_batch([x, 3 * x], [16000] * 2) assert abs(s1 - s2) < 1e-4 # peak normalisation