"""Offline unit tests: pure logic, no network. Must stay fast (<60s total).""" import json import os import shutil import struct import sys import tempfile import unittest from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from _helpers import IsolatedVoices, ns, voice # noqa: E402 from vlib.pack import _resolve_pack_tensors # noqa: E402 from vlib import della as voice_della # noqa: E402 import numpy as np def write_st(path, tensors): header, off = {}, 0 for name, (arr, dt) in tensors.items(): b = arr.tobytes() header[name] = {"dtype": dt, "shape": list(arr.shape), "data_offsets": [off, off + len(b)]} off += len(b) hj = json.dumps(header).encode() Path(path).write_bytes(struct.pack("> 16).astype(np.uint16).astype(np.uint32) << 16).view(np.float32) back = voice.decode_to_f32(voice.encode_from_f32(arr, "BF16"), "BF16", arr.shape) self.assertLessEqual(float(np.abs(arr - back).max()), float(np.abs(arr - trunc).max()) + 1e-7) def test_rejects_garbage(self): with self.assertRaises(ValueError): voice.dtype_bytes("Q4_0") with self.assertRaises(ValueError): voice.decode_to_f32(b"\x00" * 4, "F32", (2,)) with self.assertRaises(ValueError): voice.encode_from_f32(np.zeros(4, dtype=np.float32), "Q8_0") class TestHeaders(unittest.TestCase): def test_validate_catches(self): good = {"a": {"dtype": "F32", "shape": [2], "data_offsets": [0, 8]}} voice._validate_safetensors_header(dict(good), 100, 50) with self.assertRaises(ValueError): # overlap voice._validate_safetensors_header( {"a": {"dtype": "F32", "shape": [2], "data_offsets": [0, 8]}, "b": {"dtype": "F32", "shape": [2], "data_offsets": [4, 12]}}, 100, 50) with self.assertRaises(ValueError): # size mismatch voice._validate_safetensors_header( {"a": {"dtype": "F32", "shape": [4], "data_offsets": [0, 8]}}, 100, 50) with self.assertRaises(ValueError): # unknown dtype voice._validate_safetensors_header( {"a": {"dtype": "Q4_0", "shape": [2], "data_offsets": [0, 8]}}, 100, 50) with self.assertRaises(ValueError): # out of bounds voice._validate_safetensors_header( {"a": {"dtype": "F32", "shape": [2], "data_offsets": [0, 999]}}, 100, 50) def test_write_read_roundtrip(self): p = _mktmp(self) / "t.safetensors" write_st(p, {"output.weight": (np.ones((4, 4), dtype=np.float16), "F16")}) hdr, tens = voice.read_safetensors(str(p)) self.assertIn("output.weight", tens) def test_rewrite_preserves_others_and_guards_size(self): d = _mktmp(self) tgt, out = d / "t.safetensors", d / "o.safetensors" write_st(tgt, {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16"), "a.weight": (np.full((2, 2), 3.0, dtype=np.float16), "F16")}) voice.rewrite_safetensors_tensor(str(tgt), str(out), "output.weight", np.ones((4, 4), dtype=np.float16).tobytes(), "F16", (4, 4)) self.assertTrue((read_arr(out, "output.weight") == 1.0).all()) self.assertTrue((read_arr(out, "a.weight") == 3.0).all()) with self.assertRaises(SystemExit): voice.rewrite_safetensors_tensor(str(tgt), str(d / "bad.safetensors"), "output.weight", b"\x00" * 2, "F16", (1, 1)) class TestDetect(unittest.TestCase): def test_exact_alias_wins(self): self.assertEqual(voice.detect_output_tensor(["a", "lm_head.weight"], {}), "lm_head.weight") def test_substring_alias(self): n = "transformer.output_layer.weight" self.assertEqual(voice.detect_output_tensor(["other", n], {}), n) def test_tied_falls_back_to_embed(self): self.assertEqual(voice.detect_output_tensor( ["model.embed_tokens.weight"], {"tie_word_embeddings": True}), "model.embed_tokens.weight") def test_untied_embed_is_last_resort(self): self.assertEqual(voice.detect_output_tensor(["model.embed_tokens.weight"], {}), "model.embed_tokens.weight") self.assertIsNone(voice.detect_output_tensor(["blk.0.weight"], {})) def test_token_embd_detected_as_head(self): self.assertEqual(voice.detect_output_tensor(["blk.0.weight", "token_embd.weight"], None), "token_embd.weight") self.assertEqual(voice.detect_output_tensor(["output.weight", "token_embd.weight"], None), "output.weight") def test_largest_2d(self): self.assertEqual(voice.largest_2d(["a", "b"], {"a": (10, 20), "b": (5, 5)}), "a") def test_gguf_prefers_alias_over_size(self): class FakeGGUF: kind = "gguf" def ref(self, n): shapes = {"some.huge.weight": (64, 64), "transformer.output_layer.weight": (32, 32)} return voice.TensorRef(n, "F16", shapes[n]) names = ["some.huge.weight", "transformer.output_layer.weight"] self.assertEqual(voice._resolve_output_name(FakeGGUF(), None, names), "transformer.output_layer.weight") class TestOrient(unittest.TestCase): def test_same_transpose_miss(self): a = np.ones((2, 3), dtype=np.float32) self.assertIs(voice._orient(a, (2, 3), (2, 3)), a) self.assertEqual(voice._orient(a, (2, 3), (3, 2)).shape, (3, 2)) self.assertIsNone(voice._orient(a, (2, 3), (4, 4))) class TestQuantNets(unittest.TestCase): def test_parse_quant(self): self.assertEqual(voice._parse_quant_override(None), "keep") self.assertEqual(voice._parse_quant_override("Q4_0"), "q4_0") self.assertEqual(voice._parse_quant_override("fp16"), "f16") self.assertIsNone(voice._parse_quant_override("bogus-quant")) def test_retry_after_bounded(self): self.assertEqual(voice._bounded_retry_after({"Retry-After": "3600"}, 1.0), 30) self.assertEqual(voice._bounded_retry_after({"Retry-After": "2"}, 1.0), 2) self.assertEqual(voice._bounded_retry_after({}, 1.5), 1.5) def test_hf_url_table(self): self.assertTrue(voice._is_hf_url("https://huggingface.co/o/m")) self.assertTrue(voice._is_hf_url("https://cdn-lfs.huggingface.co/x")) self.assertFalse(voice._is_hf_url("https://us.aws.cdn.hf.co/xet-bridge/x")) self.assertFalse(voice._is_hf_url("https://evil.com/huggingface.co/x")) def test_auth_never_leaks_off_host(self): h = voice._hf_auth_headers("https://evil.com/x", {"Authorization": "Bearer S"}) self.assertNotIn("Authorization", h) class TestGuards(IsolatedVoices): def test_check_overwrite_refuses_symlink(self): d = _mktmp(self) real = d / "real.gguf" real.write_bytes(b"x") link = d / "link.gguf" try: link.symlink_to(real) except OSError: self.skipTest("symlinks unsupported here") with self.assertRaises(SystemExit): voice._check_overwrite(str(link), ns()) def test_assert_not_symlink(self): d = _mktmp(self) link = d / "l" try: link.symlink_to(d / "t") except OSError: self.skipTest("symlinks unsupported here") with self.assertRaises(SystemExit): voice._assert_not_symlink(str(link)) class TestAddCache(IsolatedVoices): def test_add_tensor_before_metadata(self): src = _mktmp(self) write_st(src / "voice.safetensors", {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")}) (src / "voice.json").write_text(json.dumps({"name": "myadd", "source": "t"})) voice.cmd_add(ns(safetensors=str(src / "voice.safetensors"), json=str(src / "voice.json"), name="myadd")) self.assertTrue((self.vdir / "myadd" / "voice.safetensors").exists()) self.assertTrue((self.vdir / "myadd" / "voice.json").exists()) def test_add_invalid_leaves_no_metadata(self): src = _mktmp(self) (src / "bad.safetensors").write_bytes(b"corrupt-not-safetensors") (src / "voice.json").write_text(json.dumps({"name": "badadd"})) with self.assertRaises(SystemExit): voice.cmd_add(ns(safetensors=str(src / "bad.safetensors"), json=str(src / "voice.json"), name="badadd")) self.assertFalse((self.vdir / "badadd" / "voice.json").exists()) def test_cache_base_survives_tmp_cleanup(self): src = _mktmp(self) write_st(src / "base.safetensors", {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")}) voice._cache_base(str(src / "base.safetensors"), self.vdir / "base" / "m.safetensors", self.vdir / "base" / "m.json") self.assertTrue((self.vdir / "base" / "m.safetensors").exists()) meta = json.loads((self.vdir / "base" / "m.json").read_text()) self.assertEqual(meta.get("bytes"), 4 * 4 * 2) class TestDeltaGates(unittest.TestCase): def _pair(self, d, marker_voice=False, marker_base=False): import json as _j v, b = d / "v.safetensors", d / "b.safetensors" write_st(v, {"output.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")}) write_st(b, {"output.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")}) for p, mk in ((v, marker_voice), (b, marker_base)): if not mk: continue raw = p.read_bytes() hs = struct.unpack(" r("BF16") > r("F16") > r("Q8_0") > r("Q4_K") > r("IQ1_M") > r("NVFP4")) self.assertEqual(r("NOPE"), -1) def test_multi_source_union_prefers_best_fidelity(self): u1 = "https://h/x/a.gguf" u2 = "https://h/x/b.gguf" mapping = { u1: self._parsed({"blk.0.attn.weight": ([4, 4], "Q8_0"), "output.weight": ([8, 4], "Q8_0")}), u2: self._parsed({"blk.1.attn.weight": ([4, 4], "BF16"), "output.weight": ([8, 4], "BF16")}), } with self._patch_parse(mapping): src = voice.GgufSource(urls=[u1, u2]) self.assertEqual(src.names(), ["blk.0.attn.weight", "output.weight", "blk.1.attn.weight"]) self.assertEqual(src.ref("output.weight").dtype, "BF16") self.assertEqual(src.ref("output.weight").shape, (4, 8)) with self.assertRaises(KeyError): src.ref("ghost.weight") def test_select_split_repo_for_head_shard(self): b = "https://huggingface.co/o/m/resolve/main/" files = ["m-BF16-00001-of-00002.gguf", "m-BF16-00002-of-00002.gguf", "m-Q8_0.gguf"] mapping = { b + "m-BF16-00001-of-00002.gguf": self._parsed({"blk.0.ffn_down.weight": ([8, 4], "BF16")}), b + "m-BF16-00002-of-00002.gguf": self._parsed({"output.weight": ([8, 4], "BF16")}), b + "m-Q8_0.gguf": self._parsed({"blk.0.attn.weight": ([4, 4], "Q8_0"), "output.weight": ([8, 4], "Q8_0")}), } with self._patch_parse(mapping): src = voice._gguf_source_for_repo("o/m", "main", files) self.assertEqual(src.urls, [b + "m-BF16-00001-of-00002.gguf", b + "m-BF16-00002-of-00002.gguf"]) self.assertIn("output.weight", src.names()) def test_select_prefers_single_when_split_headless(self): b = "https://huggingface.co/o/m/resolve/main/" files = ["m-00001-of-00002.gguf", "m-00002-of-00002.gguf", "m-Q8_0.gguf"] mapping = { b + "m-00001-of-00002.gguf": self._parsed({"blk.0.attn.weight": ([4, 4], "F16")}), b + "m-00002-of-00002.gguf": self._parsed({"blk.1.attn.weight": ([4, 4], "F16")}), b + "m-Q8_0.gguf": self._parsed({"blk.0.attn.weight": ([4, 4], "Q8_0"), "output.weight": ([8, 4], "Q8_0")}), } with self._patch_parse(mapping): src = voice._gguf_source_for_repo("o/m", "main", files) self.assertEqual(src.url, b + "m-Q8_0.gguf") def test_select_fails_loud_when_nothing_resolves(self): b = "https://huggingface.co/o/m/resolve/main/" with self._patch_parse({b + "mmproj-x.gguf": self._parsed({"proj.weight": ([4, 4], "F16")})}): with self.assertRaises(SystemExit): voice._gguf_source_for_repo("o/m", "main", ["mmproj-x.gguf"]) def test_select_finds_valid_unit_past_old_cap(self): b = "https://huggingface.co/o/m/resolve/main/" files = [f"a{i}-Q8_0.gguf" for i in range(8)] + ["z-model.gguf"] mapping = {b + f: self._parsed({"proj.weight": ([4, 4], "F16")}) for f in files[:8]} mapping[b + "z-model.gguf"] = self._parsed({"blk.0.attn.weight": ([4, 4], "F16"), "output.weight": ([8, 4], "F16")}) with self._patch_parse(mapping): src = voice._gguf_source_for_repo("o/m", "main", files) self.assertEqual(src.url, b + "z-model.gguf") class TestFeedback(unittest.TestCase): def test_fetch_bytes_small_uses_single_read(self): from unittest import mock import vlib.net as net with mock.patch.object(net, "http_range", return_value=(b"xy", 206, None)) as hr, \ mock.patch.object(net, "download_range") as dr: self.assertEqual(net._fetch_bytes_progress("http://x/f", 0, 1, "t"), b"xy") dr.assert_not_called() hr.assert_called_once() def test_fetch_bytes_large_progresses_and_cleans(self): from unittest import mock import vlib.net as net from vlib import ctx d = _mktmp(self) big = net._PROGRESS_BYTES + 8 def fake_dl(url, s, e, part_dir, etag, label=""): part_dir.mkdir(parents=True, exist_ok=True) (part_dir / "combined.part").write_bytes(b"z" * (e - s + 1)) return part_dir / "combined.part" with mock.patch.object(ctx, "VOICES_DIR", d), \ mock.patch.object(net, "download_range", side_effect=fake_dl) as dr, \ mock.patch.object(net, "http_range") as hr: self.assertEqual(net._fetch_bytes_progress("http://x/f.gguf", 0, big - 1, "head"), b"z" * big) hr.assert_not_called() self.assertEqual(dr.call_args[1].get("label"), "head") self.assertFalse(any(p.is_file() for p in d.rglob("*")), "part files cleaned on success") def test_fetch_bytes_failure_keeps_parts(self): from unittest import mock import vlib.net as net from vlib import ctx d = _mktmp(self) def fake_dl(url, s, e, part_dir, etag, label=""): part_dir.mkdir(parents=True, exist_ok=True) (part_dir / "chunk_000.part").write_bytes(b"z") raise RuntimeError("boom") with mock.patch.object(ctx, "VOICES_DIR", d), \ mock.patch.object(net, "download_range", side_effect=fake_dl): with self.assertRaises(RuntimeError): net._fetch_bytes_progress("http://x/f.gguf", 0, net._PROGRESS_BYTES + 1, "head") self.assertTrue(any(p.name == "chunk_000.part" for p in (d / ".parts").rglob("*")), "parts stay on failure so the next run resumes") def test_tied_note_respects_quiet(self): import io from contextlib import redirect_stdout from unittest import mock from vlib import ctx d = _mktmp(self) v, b = d / "v.safetensors", d / "b.safetensors" write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")}) write_st(b, {"model.language_model.embed_tokens.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")}) buf = io.StringIO() with mock.patch.object(ctx, "QUIET", True), redirect_stdout(buf): voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns()) self.assertNotIn("ties its head", buf.getvalue(), "filler must not leak through -q") def test_lookup_opener_and_quiet(self): import io from contextlib import redirect_stdout from unittest import mock from vlib import cmds_voices, ctx with mock.patch.object(cmds_voices, "open_source", side_effect=RuntimeError("net down")): buf = io.StringIO() with redirect_stdout(buf): with self.assertRaises(SystemExit): voice.cmd_get(ns(source="org/model", name="x")) self.assertIn("Looking up org/model", buf.getvalue()) buf2 = io.StringIO() with mock.patch.object(ctx, "QUIET", True), redirect_stdout(buf2): with self.assertRaises(SystemExit): voice.cmd_get(ns(source="org/model", name="x")) self.assertNotIn("Looking up", buf2.getvalue()) def test_using_opener_and_quiet(self): import io from contextlib import redirect_stdout from unittest import mock from vlib import ctx b = "https://huggingface.co/o/m/resolve/main/" mapping = {b + "m-Q8_0.gguf": (("llama", 64, {"blk.0.attn.weight": ([4, 4], 8, 0, 8), "output.weight": ([8, 4], 8, 0, 8)}))} with mock.patch("vlib.sources._parse_gguf_header", side_effect=lambda u: mapping[u]): buf = io.StringIO() with redirect_stdout(buf): voice._gguf_source_for_repo("o/m", "main", ["m-Q8_0.gguf"]) self.assertIn("Using m-Q8_0.gguf", buf.getvalue()) buf2 = io.StringIO() with mock.patch.object(ctx, "QUIET", True), redirect_stdout(buf2): voice._gguf_source_for_repo("o/m", "main", ["m-Q8_0.gguf"]) self.assertNotIn("Using", buf2.getvalue()) def test_saving_opener_and_quiet(self): import io from contextlib import redirect_stdout from unittest import mock from vlib import ctx d = _mktmp(self) arr = np.full((4, 4), 1.0, dtype=np.float16) fetched = ("bytes", None, arr.tobytes(), "F16", (4, 4)) buf = io.StringIO() with redirect_stdout(buf): voice._write_voice(d / "v", "output.weight", fetched, {"name": "x"}) self.assertIn("Saving voice", buf.getvalue()) self.assertTrue((d / "v" / "voice.safetensors").exists()) buf2 = io.StringIO() with mock.patch.object(ctx, "QUIET", True), redirect_stdout(buf2): voice._write_voice(d / "v2", "output.weight", fetched, {"name": "x"}) self.assertNotIn("Saving", buf2.getvalue()) def test_preparing_opener_and_quiet(self): import io from contextlib import redirect_stdout from unittest import mock from vlib import cmds_voices, ctx d = _mktmp(self) v = d / "v.safetensors" write_st(v, {"output.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")}) with mock.patch.object(cmds_voices, "_ensure_base_tensors", side_effect=SystemExit(1)): buf = io.StringIO() with redirect_stdout(buf): with self.assertRaises(SystemExit): voice.cmd_delta(ns(voicename=str(v), base="org/model")) self.assertIn("Preparing base", buf.getvalue()) buf2 = io.StringIO() with mock.patch.object(ctx, "QUIET", True), redirect_stdout(buf2): with self.assertRaises(SystemExit): voice.cmd_delta(ns(voicename=str(v), base="org/model")) self.assertNotIn("Preparing", buf2.getvalue()) def test_source_read_f32_large_uses_progress_path(self): import struct from unittest import mock import vlib.net as net from vlib import ctx from gguf.constants import GGMLQuantizationType as Q d = _mktmp(self) raw64 = struct.pack("<16f", *([1.0] * 16)) table = {"output.weight": ([4, 4], int(Q.F32), 0, 20000000)} parsed = ("llama", 64, table) def fake_dl(url, s, e, part_dir, etag, label=""): part_dir.mkdir(parents=True, exist_ok=True) (part_dir / "combined.part").write_bytes(raw64) return part_dir / "combined.part" with mock.patch("vlib.sources._parse_gguf_header", return_value=parsed), \ mock.patch.object(ctx, "VOICES_DIR", d), \ mock.patch.object(net, "download_range", side_effect=fake_dl) as dr: src = voice.GgufSource(urls=["http://x/m.gguf"]) got = src.read_f32("output.weight") self.assertEqual(tuple(got.shape), (4, 4)) self.assertTrue((got == 1.0).all()) self.assertTrue(dr.called, "large tensor must go through the progress path") class TestQuantShapes(unittest.TestCase): def _q8_voice(self, d, shape=(64, 96)): from gguf import GGUFWriter from gguf.constants import GGMLQuantizationType as Q from gguf.quants import quantize fused = np.arange(int(np.prod(shape)), dtype=np.float32).reshape(shape) q = quantize(fused, Q.Q8_0) vp = d / "v.gguf" w = GGUFWriter(str(vp), "llama", use_temp_file=False) w.add_tensor("output.weight", q, raw_dtype=Q.Q8_0) w.write_header_to_file() w.write_kv_data_to_file() w.write_tensors_to_file() w.close() return vp, fused def test_single_tensor_artifact_keeps_logical_shape(self): from gguf.constants import GGMLQuantizationType as Q from gguf.quants import quantize d = _mktmp(self) vp, fused = self._q8_voice(d) src = voice.open_source(str(vp)) ref = src.ref("output.weight") raw = src.read_raw("output.weight") out = str(d / "voice.gguf") Path(d / "raw.bin").write_bytes(raw) voice._write_single_tensor_gguf("output.weight", d / "raw.bin", len(raw), ref.dtype, ref.shape, out) back = voice.open_source(out) self.assertEqual(tuple(back.ref("output.weight").shape), tuple(ref.shape)) self.assertEqual(back.read_raw("output.weight"), raw) def test_transplant_cast_keeps_shape_and_bytes(self): from gguf import GGUFReader, GGUFWriter from gguf.constants import GGMLQuantizationType as Q d = _mktmp(self) vp, _ = self._q8_voice(d) tp = d / "t.gguf" w = GGUFWriter(str(tp), "llama", use_temp_file=False) w.add_architecture() w.add_tensor("output.weight", np.zeros((64, 96), dtype=np.float16), raw_dtype=Q.F16) w.write_header_to_file() w.write_kv_data_to_file() w.write_tensors_to_file() w.close() out = d / "voiced.gguf" voice.cmd_cast(ns(target=str(tp), voice=str(vp), out=str(out))) got = [t for t in GGUFReader(str(out)).tensors if t.name == "output.weight"][0] self.assertEqual(tuple(reversed(tuple(int(x) for x in got.shape))), (64, 96)) src_raw = voice.open_source(str(vp)).read_raw("output.weight") self.assertEqual(bytes(got.data), src_raw) class TestVoicePacks(IsolatedVoices): def _pack_pair(self, d): write_st(d / "v.safetensors", { "output.weight": (np.full((4, 4), 3.0, np.float16), "F16"), "model.norm.weight": (np.full((8,), 5.0, np.float16), "F16")}) write_st(d / "b.safetensors", { "output.weight": (np.full((4, 4), 2.0, np.float16), "F16"), "model.norm.weight": (np.full((8,), 4.0, np.float16), "F16"), "extra.weight": (np.zeros((2, 2), np.float16), "F16")}) return d / "v.safetensors", d / "b.safetensors" def test_pack_delta_computes_all(self): d = _mktmp(self) v, b = self._pack_pair(d) out = voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns()) for name, want in (("output.weight", 1.0), ("model.norm.weight", 1.0)): got = read_arr(out, name) self.assertTrue((got == want).all(), name) def test_pack_delta_missing_name_fails(self): d = _mktmp(self) write_st(d / "v.safetensors", {"ghost.weight": (np.zeros((2, 2), np.float16), "F16")}) write_st(d / "b.safetensors", {"other.weight": (np.zeros((2, 2), np.float16), "F16")}) with self.assertRaises(SystemExit): voice._compute_delta(str(d / "v.safetensors"), str(d / "b.safetensors"), d / "out", "delta-x", ns()) def test_tensor_cast_delta_fuses_not_replaces(self): from gguf import GGUFReader, GGUFWriter from gguf.constants import GGMLQuantizationType as Q d = _mktmp(self) write_st(d / "v.safetensors", {"output.weight": (np.full((4, 4), 3.0, np.float16), "F16")}) write_st(d / "b.safetensors", {"output.weight": (np.full((4, 4), 2.0, np.float16), "F16")}) dout = voice._compute_delta(str(d / "v.safetensors"), str(d / "b.safetensors"), d / "dout", "delta-x", ns()) tp = d / "t.gguf" w = GGUFWriter(str(tp), "llama", use_temp_file=False) w.add_architecture() w.add_tensor("output.weight", np.full((4, 4), 10.0, np.float16), raw_dtype=Q.F16) w.write_header_to_file() w.write_kv_data_to_file() w.write_tensors_to_file() w.close() out = d / "voiced.gguf" voice.cmd_cast(ns(target=str(tp), voice=str(dout), out=str(out))) got = [t for t in GGUFReader(str(out)).tensors if t.name == "output.weight"][0] # base 10 + delta (3-2) = 11. Raw-delta replace would give 1. self.assertTrue((np.asarray(got.data, dtype=np.float32) == 11.0).all()) def test_pack_cast_gguf_fuses_all(self): from gguf import GGUFReader, GGUFWriter from gguf.constants import GGMLQuantizationType as Q d = _mktmp(self) v, b = self._pack_pair(d) dout = voice._compute_delta(str(v), str(b), d / "dout", "delta-x", ns()) tp = d / "t.gguf" w = GGUFWriter(str(tp), "llama", use_temp_file=False) w.add_architecture() w.add_tensor("output.weight", np.full((4, 4), 10.0, np.float16), raw_dtype=Q.F16) w.add_tensor("model.norm.weight", np.full((8,), 20.0, np.float32), raw_dtype=Q.F32) w.write_header_to_file() w.write_kv_data_to_file() w.write_tensors_to_file() w.close() out = d / "voiced.gguf" voice.cmd_cast(ns(target=str(tp), voice=str(dout), out=str(out))) back = {t.name: t for t in GGUFReader(str(out)).tensors} self.assertTrue((np.asarray(back["output.weight"].data, dtype=np.float32) == 11.0).all()) self.assertTrue((np.asarray(back["model.norm.weight"].data, dtype=np.float32) == 21.0).all()) def test_pack_cast_safetensors_fuses_all(self): d = _mktmp(self) v, b = self._pack_pair(d) dout = voice._compute_delta(str(v), str(b), d / "dout", "delta-x", ns()) write_st(d / "t.safetensors", { "output.weight": (np.full((4, 4), 10.0, np.float16), "F16"), "model.norm.weight": (np.full((8,), 20.0, np.float16), "F16")}) out = d / "o.safetensors" voice.cmd_cast(ns(target=str(d / "t.safetensors"), voice=str(dout), out=str(out))) for name, want in (("output.weight", 11.0), ("model.norm.weight", 21.0)): got = read_arr(out, name) self.assertTrue((got == want).all(), name) def test_pack_cast_safetensors_single_pass(self): # The old chain called rewrite_safetensors_tensor once per tensor # (O(N.file) full copies). The fused path must succeed with it disabled. d = _mktmp(self) v, b = self._pack_pair(d) dout = voice._compute_delta(str(v), str(b), d / "dout", "delta-x", ns()) write_st(d / "t.safetensors", { "output.weight": (np.full((4, 4), 10.0, np.float16), "F16"), "model.norm.weight": (np.full((8,), 20.0, np.float16), "F16")}) out = d / "o.safetensors" orig = voice.rewrite_safetensors_tensor def _boom(*a, **k): raise AssertionError("chained per-tensor rewrite used") voice.rewrite_safetensors_tensor = _boom try: voice.cmd_cast(ns(target=str(d / "t.safetensors"), voice=str(dout), out=str(out))) finally: voice.rewrite_safetensors_tensor = orig for name, want in (("output.weight", 11.0), ("model.norm.weight", 21.0)): got = read_arr(out, name) self.assertTrue((got == want).all(), name) class TestBaseCache(unittest.TestCase): def _cache(self, d, tensors): write_st(d / "base.safetensors", tensors) return d / "base.safetensors" def test_validate_hit(self): d = _mktmp(self) p = self._cache(d, {"a": (np.zeros((4, 4), np.float16), "F16")}) self.assertEqual(voice._cache_validate(str(p), ["a"]), []) def test_validate_missing_and_truncated(self): import struct as _st, json as _j d = _mktmp(self) p = self._cache(d, {"a": (np.zeros((4, 4), np.float16), "F16")}) raw = bytearray(p.read_bytes()) hs = _st.unpack(" 0.40) & (frac < 0.60)).all(), frac.tolist()) # Largest-magnitude entries survive more often than the smallest. mag = np.abs(d) kept_mag = mag[out != 0].mean() dropped_mag = mag[out == 0].mean() self.assertGreater(kept_mag, dropped_mag) def test_seeded_run_bit_identical(self): rng = np.random.default_rng(1) d = rng.standard_normal((6, 64)).astype(np.float32) a = voice_della.magprune(d, density=0.8, epsilon=0.1, rng=np.random.default_rng(42)) b = voice_della.magprune(d, density=0.8, epsilon=0.1, rng=np.random.default_rng(42)) self.assertTrue(np.array_equal(a, b)) base = rng.standard_normal((9, 32)).astype(np.float32) vs = [base + 1, base - 1] m1 = voice_della.merge(base, vs, density=0.8, epsilon=0.1, seed=42) m2 = voice_della.merge(base, vs, density=0.8, epsilon=0.1, seed=42) self.assertTrue(np.array_equal(m1, m2)) m3 = voice_della.merge(base, vs, density=0.8, epsilon=0.1, seed=43) self.assertFalse(np.array_equal(m1, m3)) mb1 = voice_della.merge(base, vs, density=0.8, epsilon=0.1, seed=42, block_rows=4096) mb2 = voice_della.merge(base, vs, density=0.8, epsilon=0.1, seed=42, block_rows=2) self.assertTrue(np.array_equal(mb1, mb2)) def test_density_epsilon_violations_raise(self): d = np.ones((2, 8), dtype=np.float32) for density, epsilon in ((0.9, 0.2), (0.05, 0.1)): with self.assertRaises(ValueError): voice_della.magprune(d, density=density, epsilon=epsilon) with self.assertRaises(ValueError): voice_della.merge(d, [d + 1], density=0.95, epsilon=0.1, seed=0) def test_noop_and_zero_density(self): d = np.ones((2, 8), dtype=np.float32) self.assertTrue(np.array_equal( voice_della.magprune(d, density=1.0, epsilon=0.1), d)) self.assertTrue((voice_della.magprune(d, density=0.0, epsilon=0.1) == 0).all()) def test_empty_voice_list_returns_base(self): base = np.ones((3, 5), dtype=np.float32) out = voice_della.merge(base, []) self.assertTrue(np.array_equal(out, base)) def test_f16_in_base_dtype_out(self): rng = np.random.default_rng(2) base = (rng.standard_normal((4, 16)) * 2).astype(np.float16) donor = (base.astype(np.float32) + 1).astype(np.float16) out = voice_della.merge(base, [donor], density=0.8, epsilon=0.1, seed=1) self.assertEqual(out.dtype, np.float16) self.assertTrue(np.isfinite(out.astype(np.float32)).all()) def test_all_pruned_row_stays_finite(self): tiny = np.full((2, 50), 1e-9, dtype=np.float32) out = voice_della.magprune(tiny, density=0.05, epsilon=0.04, rng=np.random.default_rng(0)) self.assertTrue(np.isfinite(out).all()) def test_elected_combine_matches_upstream_formula(self): rng = np.random.default_rng(3) base = rng.standard_normal((5, 40)).astype(np.float32) v1, v2 = base + 1, base - 1 pruned = [voice_della.magprune(v - base, density=0.8, epsilon=0.1, rng=np.random.default_rng(5)) for v in (v1, v2)] got = voice_della.combine(base, pruned, [1.0, 1.0]) stacked = np.stack([p.astype(np.float32) for p in pruned]) majority = np.where(stacked.sum(0) >= 0, 1.0, -1.0) elected = np.sign(stacked) == majority mixed = np.where(elected, stacked, 0).sum(0) divisor = np.where(elected, 1.0, 0).sum(0) divisor[divisor == 0] = 1 self.assertTrue(np.allclose(got, base + mixed / divisor, atol=1e-6)) def test_per_row_l1_rescale_not_global(self): # Per-row L1 (vlib fork) keeps each row's own sum|x|; a whole-tensor # L1 (upstream) would scale every row by one global factor instead. rng = np.random.default_rng(4) scales = np.array([0.1, 1, 5, 0.5, 2, 10], dtype=np.float32)[:, None] d = (rng.standard_normal((6, 100)).astype(np.float32)) * scales out = voice_della.magprune(d, density=0.7, epsilon=0.1, rng=np.random.default_rng(11)) before = np.abs(d).sum(axis=-1) after = np.abs(out).sum(axis=-1) live = after >= 1e-7 self.assertTrue(live.all()) self.assertTrue(np.allclose(after[live], before[live], rtol=1e-5)) if __name__ == "__main__": unittest.main()