Wiself commited on
Commit
4a1430c
·
1 Parent(s): fcff745

Update voice.py, vlib, tests, bundles

Browse files
Files changed (8) hide show
  1. tests/_helpers.py +2 -0
  2. tests/test_units.py +242 -68
  3. vlib/cache.py +30 -20
  4. vlib/delta.py +13 -57
  5. vlib/sources.py +91 -21
  6. voice-cli.tar.gz +2 -2
  7. voice.py +2 -2
  8. voice.pyz +2 -2
tests/_helpers.py CHANGED
@@ -7,6 +7,7 @@ E2E: also needs a llama-cli binary (LLAMA_CLI or PATH); skips otherwise.
7
  import argparse
8
  import importlib.util
9
  import os
 
10
  import sys
11
  import tempfile
12
  import unittest
@@ -117,6 +118,7 @@ class IsolatedVoices(unittest.TestCase):
117
  voice_ctx.VOICES_DIR = self._old
118
  (voice_ctx.REPORTS_JSONL, voice_ctx.REPORTS_OUTBOX, voice_ctx.OPERATIONS_LOG,
119
  voice_ctx.HF_TOKEN_PATH) = self._old_reports
 
120
 
121
 
122
  def ns(**kw):
 
7
  import argparse
8
  import importlib.util
9
  import os
10
+ import shutil
11
  import sys
12
  import tempfile
13
  import unittest
 
118
  voice_ctx.VOICES_DIR = self._old
119
  (voice_ctx.REPORTS_JSONL, voice_ctx.REPORTS_OUTBOX, voice_ctx.OPERATIONS_LOG,
120
  voice_ctx.HF_TOKEN_PATH) = self._old_reports
121
+ shutil.rmtree(self.vdir, ignore_errors=True)
122
 
123
 
124
  def ns(**kw):
tests/test_units.py CHANGED
@@ -1,6 +1,7 @@
1
  """Offline unit tests: pure logic, no network. Must stay fast (<60s total)."""
2
  import json
3
  import os
 
4
  import struct
5
  import sys
6
  import tempfile
@@ -34,6 +35,11 @@ def read_arr(path, name, dtype=np.float16):
34
  b = raw[8 + hs + info["data_offsets"][0]:8 + hs + info["data_offsets"][1]]
35
  return np.frombuffer(b, dtype=dtype).reshape(info["shape"])
36
 
 
 
 
 
 
37
 
38
  class TestNames(unittest.TestCase):
39
  def test_sanitize_accepts_sane(self):
@@ -124,13 +130,13 @@ class TestHeaders(unittest.TestCase):
124
  {"a": {"dtype": "F32", "shape": [2], "data_offsets": [0, 999]}}, 100, 50)
125
 
126
  def test_write_read_roundtrip(self):
127
- p = Path(tempfile.mkdtemp()) / "t.safetensors"
128
  write_st(p, {"output.weight": (np.ones((4, 4), dtype=np.float16), "F16")})
129
  hdr, tens = voice.read_safetensors(str(p))
130
  self.assertIn("output.weight", tens)
131
 
132
  def test_rewrite_preserves_others_and_guards_size(self):
133
- d = Path(tempfile.mkdtemp())
134
  tgt, out = d / "t.safetensors", d / "o.safetensors"
135
  write_st(tgt, {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16"),
136
  "a.weight": (np.full((2, 2), 3.0, dtype=np.float16), "F16")})
@@ -162,6 +168,10 @@ class TestDetect(unittest.TestCase):
162
  "model.embed_tokens.weight")
163
  self.assertIsNone(voice.detect_output_tensor(["blk.0.weight"], {}))
164
 
 
 
 
 
165
  def test_largest_2d(self):
166
  self.assertEqual(voice.largest_2d(["a", "b"], {"a": (10, 20), "b": (5, 5)}), "a")
167
 
@@ -212,7 +222,7 @@ class TestQuantNets(unittest.TestCase):
212
 
213
  class TestGuards(IsolatedVoices):
214
  def test_check_overwrite_refuses_symlink(self):
215
- d = Path(tempfile.mkdtemp())
216
  real = d / "real.gguf"
217
  real.write_bytes(b"x")
218
  link = d / "link.gguf"
@@ -224,7 +234,7 @@ class TestGuards(IsolatedVoices):
224
  voice._check_overwrite(str(link), ns())
225
 
226
  def test_assert_not_symlink(self):
227
- d = Path(tempfile.mkdtemp())
228
  link = d / "l"
229
  try:
230
  link.symlink_to(d / "t")
@@ -236,7 +246,7 @@ class TestGuards(IsolatedVoices):
236
 
237
  class TestAddCache(IsolatedVoices):
238
  def test_add_tensor_before_metadata(self):
239
- src = Path(tempfile.mkdtemp())
240
  write_st(src / "voice.safetensors",
241
  {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")})
242
  (src / "voice.json").write_text(json.dumps({"name": "myadd", "source": "t"}))
@@ -246,7 +256,7 @@ class TestAddCache(IsolatedVoices):
246
  self.assertTrue((self.vdir / "myadd" / "voice.json").exists())
247
 
248
  def test_add_invalid_leaves_no_metadata(self):
249
- src = Path(tempfile.mkdtemp())
250
  (src / "bad.safetensors").write_bytes(b"corrupt-not-safetensors")
251
  (src / "voice.json").write_text(json.dumps({"name": "badadd"}))
252
  with self.assertRaises(SystemExit):
@@ -255,7 +265,7 @@ class TestAddCache(IsolatedVoices):
255
  self.assertFalse((self.vdir / "badadd" / "voice.json").exists())
256
 
257
  def test_cache_base_survives_tmp_cleanup(self):
258
- src = Path(tempfile.mkdtemp())
259
  write_st(src / "base.safetensors",
260
  {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")})
261
  voice._cache_base(str(src / "base.safetensors"),
@@ -288,7 +298,7 @@ class TestDeltaGates(unittest.TestCase):
288
  return v, b
289
 
290
  def test_normal_delta_computes(self):
291
- d = Path(tempfile.mkdtemp())
292
  v, b = self._pair(d)
293
  out = voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
294
  got = read_arr(out, "output.weight")
@@ -297,7 +307,7 @@ class TestDeltaGates(unittest.TestCase):
297
  def test_tied_base_head_falls_back_to_embed(self):
298
  import io
299
  from contextlib import redirect_stdout
300
- d = Path(tempfile.mkdtemp())
301
  v, b = d / "v.safetensors", d / "b.safetensors"
302
  write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16"),
303
  "model.language_model.embed_tokens.weight": (np.full((4, 4), 7.0, dtype=np.float16), "F16")})
@@ -310,7 +320,7 @@ class TestDeltaGates(unittest.TestCase):
310
  self.assertIn("ties its head", buf.getvalue(), "fallback must be loud, not silent")
311
 
312
  def test_tied_base_shape_mismatch_fails(self):
313
- d = Path(tempfile.mkdtemp())
314
  v, b = d / "v.safetensors", d / "b.safetensors"
315
  write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
316
  write_st(b, {"model.language_model.embed_tokens.weight": (np.full((4, 8), 1.0, dtype=np.float16), "F16")})
@@ -318,40 +328,93 @@ class TestDeltaGates(unittest.TestCase):
318
  voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
319
 
320
  def test_headless_baseless_still_fails(self):
321
- d = Path(tempfile.mkdtemp())
322
  v, b = d / "v.safetensors", d / "b.safetensors"
323
  write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
324
  write_st(b, {"blk.0.attn.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")})
325
  with self.assertRaises(SystemExit):
326
  voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
327
 
328
- def test_tied_head_want_reroutes_to_embed(self):
329
- d = Path(tempfile.mkdtemp())
330
- b = d / "tied.safetensors"
331
- write_st(b, {"model.language_model.embed_tokens.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")})
332
- self.assertEqual(voice._tied_head_want(str(b), None, ["lm_head.weight"]),
333
- ["model.language_model.embed_tokens.weight"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
 
335
- def test_tied_head_want_dedupes_embed(self):
336
- d = Path(tempfile.mkdtemp())
337
- b = d / "tied.safetensors"
338
- write_st(b, {"model.language_model.embed_tokens.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")})
339
- self.assertEqual(voice._tied_head_want(str(b), None,
340
- ["lm_head.weight", "model.language_model.embed_tokens.weight"]),
341
- ["model.language_model.embed_tokens.weight"])
342
 
343
- def test_tied_head_want_untied_unchanged(self):
344
- d = Path(tempfile.mkdtemp())
345
- b = d / "untied.safetensors"
 
346
  write_st(b, {"lm_head.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16"),
347
- "model.language_model.embed_tokens.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")})
348
- self.assertEqual(voice._tied_head_want(str(b), None, ["lm_head.weight"]), ["lm_head.weight"])
 
349
 
350
- def test_tied_head_want_headless_unchanged(self):
351
- d = Path(tempfile.mkdtemp())
352
- b = d / "bare.safetensors"
353
- write_st(b, {"blk.0.attn.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")})
354
- self.assertEqual(voice._tied_head_want(str(b), None, ["lm_head.weight"]), ["lm_head.weight"])
 
 
 
 
 
 
 
 
 
 
 
355
 
356
  def test_gguf_delta_chunked_matches_full(self):
357
  # Slow path (either side GGUF) must stream dequant in bounded chunks:
@@ -360,7 +423,7 @@ class TestDeltaGates(unittest.TestCase):
360
  from gguf import GGUFWriter
361
  from gguf.constants import GGMLQuantizationType as Q
362
  from gguf.quants import quantize
363
- d = Path(tempfile.mkdtemp())
364
  shape = (64, 128)
365
  rng = np.random.default_rng(7)
366
  vf = (rng.normal(size=shape) * 2).astype(np.float32)
@@ -395,7 +458,7 @@ class TestDeltaGates(unittest.TestCase):
395
  self.assertTrue((got == want).all())
396
  def test_share_safe_delta_header(self):
397
  import json as _j
398
- d = Path(tempfile.mkdtemp())
399
  home = d / "Users" / "someone" / "Desktop"
400
  home.mkdir(parents=True)
401
  self._pair(home)
@@ -414,7 +477,7 @@ class TestDeltaGates(unittest.TestCase):
414
  self.assertEqual(meta.get("voice"), "v.safetensors")
415
 
416
  def test_verify_agrees(self):
417
- d = Path(tempfile.mkdtemp())
418
  write_st(d / "v.safetensors",
419
  {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")})
420
  meta = {"tensor_name": "output.weight", "shape": [4, 4],
@@ -422,7 +485,7 @@ class TestDeltaGates(unittest.TestCase):
422
  self.assertEqual(voice._verify_voice_file(str(d / "v.safetensors"), meta), [])
423
 
424
  def test_verify_flags_mismatch(self):
425
- d = Path(tempfile.mkdtemp())
426
  write_st(d / "v.safetensors",
427
  {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")})
428
  meta = {"tensor_name": "output.weight", "shape": [262144, 2048],
@@ -452,7 +515,7 @@ class TestDeltaGates(unittest.TestCase):
452
 
453
  def test_niche_gates_fail_fast_non_interactive(self):
454
  for mv, mb in ((False, True), (True, False), (True, True)):
455
- d = Path(tempfile.mkdtemp())
456
  v, b = self._pair(d, marker_voice=mv, marker_base=mb)
457
  with self.assertRaises(SystemExit, msg=f"mv={mv} mb={mb}"):
458
  voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
@@ -462,7 +525,7 @@ class TestGetGguf(IsolatedVoices):
462
  def test_get_from_local_gguf(self):
463
  from gguf import GGUFWriter
464
  from gguf.constants import GGMLQuantizationType as Q
465
- d = Path(tempfile.mkdtemp())
466
  gp = d / "tiny.gguf"
467
  w = GGUFWriter(str(gp), "llama", use_temp_file=False)
468
  w.add_architecture()
@@ -475,6 +538,24 @@ class TestGetGguf(IsolatedVoices):
475
  voice.cmd_get(ns(source=str(gp), name="tiny-gguf"))
476
  self.assertTrue((self.vdir / "tiny-gguf" / "voice.safetensors").exists())
477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
  class TestGgufTensorFirst(unittest.TestCase):
479
  def _parsed(self, tensors):
480
  from gguf.constants import GGMLQuantizationType as Q
@@ -514,10 +595,6 @@ class TestGgufTensorFirst(unittest.TestCase):
514
  self.assertTrue(r("F32") > r("BF16") > r("F16") > r("Q8_0") > r("Q4_K") > r("IQ1_M") > r("NVFP4"))
515
  self.assertEqual(r("NOPE"), -1)
516
 
517
- def test_token_embd_detected_as_head(self):
518
- self.assertEqual(voice.detect_output_tensor(["blk.0.weight", "token_embd.weight"], None), "token_embd.weight")
519
- self.assertEqual(voice.detect_output_tensor(["output.weight", "token_embd.weight"], None), "output.weight")
520
-
521
  def test_multi_source_union_prefers_best_fidelity(self):
522
  u1 = "https://h/x/a.gguf"
523
  u2 = "https://h/x/b.gguf"
@@ -588,7 +665,7 @@ class TestFeedback(unittest.TestCase):
588
  from unittest import mock
589
  import vlib.net as net
590
  from vlib import ctx
591
- d = Path(tempfile.mkdtemp())
592
  big = net._PROGRESS_BYTES + 8
593
  def fake_dl(url, s, e, part_dir, etag, label=""):
594
  part_dir.mkdir(parents=True, exist_ok=True)
@@ -606,7 +683,7 @@ class TestFeedback(unittest.TestCase):
606
  from unittest import mock
607
  import vlib.net as net
608
  from vlib import ctx
609
- d = Path(tempfile.mkdtemp())
610
  def fake_dl(url, s, e, part_dir, etag, label=""):
611
  part_dir.mkdir(parents=True, exist_ok=True)
612
  (part_dir / "chunk_000.part").write_bytes(b"z")
@@ -623,7 +700,7 @@ class TestFeedback(unittest.TestCase):
623
  from contextlib import redirect_stdout
624
  from unittest import mock
625
  from vlib import ctx
626
- d = Path(tempfile.mkdtemp())
627
  v, b = d / "v.safetensors", d / "b.safetensors"
628
  write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
629
  write_st(b, {"model.language_model.embed_tokens.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")})
@@ -632,6 +709,102 @@ class TestFeedback(unittest.TestCase):
632
  voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
633
  self.assertNotIn("ties its head", buf.getvalue(), "filler must not leak through -q")
634
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
 
636
  class TestQuantShapes(unittest.TestCase):
637
  def _q8_voice(self, d, shape=(64, 96)):
@@ -652,7 +825,7 @@ class TestQuantShapes(unittest.TestCase):
652
  def test_single_tensor_artifact_keeps_logical_shape(self):
653
  from gguf.constants import GGMLQuantizationType as Q
654
  from gguf.quants import quantize
655
- d = Path(tempfile.mkdtemp())
656
  vp, fused = self._q8_voice(d)
657
  src = voice.open_source(str(vp))
658
  ref = src.ref("output.weight")
@@ -668,7 +841,7 @@ class TestQuantShapes(unittest.TestCase):
668
  def test_transplant_cast_keeps_shape_and_bytes(self):
669
  from gguf import GGUFReader, GGUFWriter
670
  from gguf.constants import GGMLQuantizationType as Q
671
- d = Path(tempfile.mkdtemp())
672
  vp, _ = self._q8_voice(d)
673
  tp = d / "t.gguf"
674
  w = GGUFWriter(str(tp), "llama", use_temp_file=False)
@@ -700,7 +873,7 @@ class TestVoicePacks(IsolatedVoices):
700
  return d / "v.safetensors", d / "b.safetensors"
701
 
702
  def test_pack_delta_computes_all(self):
703
- d = Path(tempfile.mkdtemp())
704
  v, b = self._pack_pair(d)
705
  out = voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
706
  for name, want in (("output.weight", 1.0), ("model.norm.weight", 1.0)):
@@ -708,7 +881,7 @@ class TestVoicePacks(IsolatedVoices):
708
  self.assertTrue((got == want).all(), name)
709
 
710
  def test_pack_delta_missing_name_fails(self):
711
- d = Path(tempfile.mkdtemp())
712
  write_st(d / "v.safetensors",
713
  {"ghost.weight": (np.zeros((2, 2), np.float16), "F16")})
714
  write_st(d / "b.safetensors",
@@ -720,7 +893,7 @@ class TestVoicePacks(IsolatedVoices):
720
  def test_tensor_cast_delta_fuses_not_replaces(self):
721
  from gguf import GGUFReader, GGUFWriter
722
  from gguf.constants import GGMLQuantizationType as Q
723
- d = Path(tempfile.mkdtemp())
724
  write_st(d / "v.safetensors",
725
  {"output.weight": (np.full((4, 4), 3.0, np.float16), "F16")})
726
  write_st(d / "b.safetensors",
@@ -744,7 +917,7 @@ class TestVoicePacks(IsolatedVoices):
744
  def test_pack_cast_gguf_fuses_all(self):
745
  from gguf import GGUFReader, GGUFWriter
746
  from gguf.constants import GGMLQuantizationType as Q
747
- d = Path(tempfile.mkdtemp())
748
  v, b = self._pack_pair(d)
749
  dout = voice._compute_delta(str(v), str(b), d / "dout", "delta-x", ns())
750
  tp = d / "t.gguf"
@@ -764,7 +937,7 @@ class TestVoicePacks(IsolatedVoices):
764
 
765
  def test_pack_cast_safetensors_fuses_all(self):
766
 
767
- d = Path(tempfile.mkdtemp())
768
  v, b = self._pack_pair(d)
769
  dout = voice._compute_delta(str(v), str(b), d / "dout", "delta-x", ns())
770
  write_st(d / "t.safetensors", {
@@ -780,7 +953,7 @@ class TestVoicePacks(IsolatedVoices):
780
  def test_pack_cast_safetensors_single_pass(self):
781
  # The old chain called rewrite_safetensors_tensor once per tensor
782
  # (O(N.file) full copies). The fused path must succeed with it disabled.
783
- d = Path(tempfile.mkdtemp())
784
  v, b = self._pack_pair(d)
785
  dout = voice._compute_delta(str(v), str(b), d / "dout", "delta-x", ns())
786
  write_st(d / "t.safetensors", {
@@ -807,13 +980,13 @@ class TestBaseCache(unittest.TestCase):
807
  return d / "base.safetensors"
808
 
809
  def test_validate_hit(self):
810
- d = Path(tempfile.mkdtemp())
811
  p = self._cache(d, {"a": (np.zeros((4, 4), np.float16), "F16")})
812
  self.assertEqual(voice._cache_validate(str(p), ["a"]), [])
813
 
814
  def test_validate_missing_and_truncated(self):
815
  import struct as _st, json as _j
816
- d = Path(tempfile.mkdtemp())
817
  p = self._cache(d, {"a": (np.zeros((4, 4), np.float16), "F16")})
818
  raw = bytearray(p.read_bytes())
819
  hs = _st.unpack("<Q", bytes(raw[:8]))[0]
@@ -824,13 +997,13 @@ class TestBaseCache(unittest.TestCase):
824
  self.assertEqual(sorted(voice._cache_validate(str(p), ["a", "b", "c"])), ["b", "c"])
825
 
826
  def test_validate_garbage(self):
827
- d = Path(tempfile.mkdtemp())
828
  p = d / "base.safetensors"
829
  p.write_bytes(b"not-a-safetensors-file")
830
  self.assertEqual(voice._cache_validate(str(p), ["a"]), ["a"])
831
 
832
  def test_topup_write_roundtrip(self):
833
- d = Path(tempfile.mkdtemp())
834
  p = self._cache(d, {"a": (np.full((4, 4), 7.0, np.float16), "F16")})
835
  rawf = d / "raw.bin"
836
  rawf.write_bytes(np.full((8,), 9.0, np.float16).tobytes())
@@ -920,7 +1093,7 @@ class TestAliases(unittest.TestCase):
920
  def test_pack_preset_head_only(self):
921
  # Preset is the output head, nothing else. Tied repos resolve the embed
922
  # (it doubles as head); untied resolve lm_head.
923
- d = Path(tempfile.mkdtemp())
924
  write_st(d / "tied.safetensors", {
925
  "model.language_model.embed_tokens.weight": (np.zeros((8, 4), np.float16), "F16"),
926
  "model.language_model.norm.weight": (np.zeros((4,), np.float16), "F16")})
@@ -949,7 +1122,7 @@ class TestAliases(unittest.TestCase):
949
  # ST pack names onto a GGUF target speaking llama.cpp names (replace mode).
950
  from gguf import GGUFReader, GGUFWriter
951
  from gguf.constants import GGMLQuantizationType as Q
952
- d = Path(tempfile.mkdtemp())
953
  write_st(d / "pack.safetensors", {
954
  "model.language_model.embed_tokens.weight": (np.full((4, 4), 3.0, np.float16), "F16"),
955
  "lm_head.weight": (np.full((4, 4), 7.0, np.float16), "F16")})
@@ -980,7 +1153,7 @@ class TestAliases(unittest.TestCase):
980
  from gguf import GGUFReader, GGUFWriter
981
  from gguf.constants import GGMLQuantizationType as Q
982
  from gguf.quants import quant_shape_to_byte_shape
983
- d = Path(tempfile.mkdtemp())
984
  logical = (256, 256)
985
  raw = np.zeros(quant_shape_to_byte_shape(logical, Q.Q4_K), dtype=np.uint8)
986
  tp = d / "t.gguf"
@@ -1082,7 +1255,7 @@ class TestEntry(IsolatedVoices):
1082
  def test_venv_reexec_targets_entry(self):
1083
  # Re-exec must run voice.py (absolute) with argv intact — never the module.
1084
  import types
1085
- d = Path(tempfile.mkdtemp())
1086
  vp = d / ".venv" / "bin"
1087
  vp.mkdir(parents=True)
1088
  (vp / "python").symlink_to(sys.executable)
@@ -1142,7 +1315,7 @@ class TestEntry(IsolatedVoices):
1142
  # offsets: fail up front with guidance, not warn-then-dump (B1).
1143
  import io
1144
  from contextlib import redirect_stdout
1145
- d = Path(tempfile.mkdtemp())
1146
  write_st(d / "t.safetensors",
1147
  {"output.weight": (np.zeros((4, 4), np.float32), "F32")})
1148
  write_st(d / "v.safetensors",
@@ -1173,7 +1346,7 @@ class TestEntry(IsolatedVoices):
1173
  def test_requested_subset_routes_by_role(self):
1174
  # An explicitly named tensor must land in its own slot, never the
1175
  # output-first fallback (D2: embed request fitted onto lm_head).
1176
- d = Path(tempfile.mkdtemp())
1177
  write_st(d / "v.safetensors", {
1178
  "model.embed_tokens.weight": (np.full((4, 3), 7.0, np.float16), "F16"),
1179
  "model.lm_head.weight": (np.full((8, 4), 8.0, np.float16), "F16")})
@@ -1199,7 +1372,7 @@ class TestSymlinkHardening(IsolatedVoices):
1199
  # Old code compared raw strings, so a cwd-relative in-registry path
1200
  # never matched the absolute VOICES_DIR scope and skipped the walk.
1201
  import os as _os
1202
- t = Path(tempfile.mkdtemp())
1203
  (t / "real" / ".voices").mkdir(parents=True)
1204
  (t / "elsewhere").mkdir()
1205
  try:
@@ -1228,12 +1401,13 @@ class TestSymlinkHardening(IsolatedVoices):
1228
  voice._assert_not_symlink(self.vdir / "myadd" / "voice.json")
1229
  sib = self.vdir.parent / (self.vdir.name + "2")
1230
  sib.mkdir(exist_ok=True)
 
1231
  with self.assertRaises(SystemExit):
1232
  voice._assert_not_symlink(sib / "voice.json")
1233
- voice._assert_not_symlink(Path(tempfile.mkdtemp()) / "voice.json")
1234
 
1235
  def test_topup_write_refuses_symlink(self):
1236
- d = Path(tempfile.mkdtemp())
1237
  hdr = {"a": {"dtype": "F16", "shape": [4], "data_offsets": [0, 8]}}
1238
  hj = json.dumps(hdr).encode()
1239
  real = d / "base.safetensors"
 
1
  """Offline unit tests: pure logic, no network. Must stay fast (<60s total)."""
2
  import json
3
  import os
4
+ import shutil
5
  import struct
6
  import sys
7
  import tempfile
 
35
  b = raw[8 + hs + info["data_offsets"][0]:8 + hs + info["data_offsets"][1]]
36
  return np.frombuffer(b, dtype=dtype).reshape(info["shape"])
37
 
38
+ def _mktmp(self):
39
+ d = Path(tempfile.mkdtemp())
40
+ self.addCleanup(shutil.rmtree, d, True)
41
+ return d
42
+
43
 
44
  class TestNames(unittest.TestCase):
45
  def test_sanitize_accepts_sane(self):
 
130
  {"a": {"dtype": "F32", "shape": [2], "data_offsets": [0, 999]}}, 100, 50)
131
 
132
  def test_write_read_roundtrip(self):
133
+ p = _mktmp(self) / "t.safetensors"
134
  write_st(p, {"output.weight": (np.ones((4, 4), dtype=np.float16), "F16")})
135
  hdr, tens = voice.read_safetensors(str(p))
136
  self.assertIn("output.weight", tens)
137
 
138
  def test_rewrite_preserves_others_and_guards_size(self):
139
+ d = _mktmp(self)
140
  tgt, out = d / "t.safetensors", d / "o.safetensors"
141
  write_st(tgt, {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16"),
142
  "a.weight": (np.full((2, 2), 3.0, dtype=np.float16), "F16")})
 
168
  "model.embed_tokens.weight")
169
  self.assertIsNone(voice.detect_output_tensor(["blk.0.weight"], {}))
170
 
171
+ def test_token_embd_detected_as_head(self):
172
+ self.assertEqual(voice.detect_output_tensor(["blk.0.weight", "token_embd.weight"], None), "token_embd.weight")
173
+ self.assertEqual(voice.detect_output_tensor(["output.weight", "token_embd.weight"], None), "output.weight")
174
+
175
  def test_largest_2d(self):
176
  self.assertEqual(voice.largest_2d(["a", "b"], {"a": (10, 20), "b": (5, 5)}), "a")
177
 
 
222
 
223
  class TestGuards(IsolatedVoices):
224
  def test_check_overwrite_refuses_symlink(self):
225
+ d = _mktmp(self)
226
  real = d / "real.gguf"
227
  real.write_bytes(b"x")
228
  link = d / "link.gguf"
 
234
  voice._check_overwrite(str(link), ns())
235
 
236
  def test_assert_not_symlink(self):
237
+ d = _mktmp(self)
238
  link = d / "l"
239
  try:
240
  link.symlink_to(d / "t")
 
246
 
247
  class TestAddCache(IsolatedVoices):
248
  def test_add_tensor_before_metadata(self):
249
+ src = _mktmp(self)
250
  write_st(src / "voice.safetensors",
251
  {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")})
252
  (src / "voice.json").write_text(json.dumps({"name": "myadd", "source": "t"}))
 
256
  self.assertTrue((self.vdir / "myadd" / "voice.json").exists())
257
 
258
  def test_add_invalid_leaves_no_metadata(self):
259
+ src = _mktmp(self)
260
  (src / "bad.safetensors").write_bytes(b"corrupt-not-safetensors")
261
  (src / "voice.json").write_text(json.dumps({"name": "badadd"}))
262
  with self.assertRaises(SystemExit):
 
265
  self.assertFalse((self.vdir / "badadd" / "voice.json").exists())
266
 
267
  def test_cache_base_survives_tmp_cleanup(self):
268
+ src = _mktmp(self)
269
  write_st(src / "base.safetensors",
270
  {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")})
271
  voice._cache_base(str(src / "base.safetensors"),
 
298
  return v, b
299
 
300
  def test_normal_delta_computes(self):
301
+ d = _mktmp(self)
302
  v, b = self._pair(d)
303
  out = voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
304
  got = read_arr(out, "output.weight")
 
307
  def test_tied_base_head_falls_back_to_embed(self):
308
  import io
309
  from contextlib import redirect_stdout
310
+ d = _mktmp(self)
311
  v, b = d / "v.safetensors", d / "b.safetensors"
312
  write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16"),
313
  "model.language_model.embed_tokens.weight": (np.full((4, 4), 7.0, dtype=np.float16), "F16")})
 
320
  self.assertIn("ties its head", buf.getvalue(), "fallback must be loud, not silent")
321
 
322
  def test_tied_base_shape_mismatch_fails(self):
323
+ d = _mktmp(self)
324
  v, b = d / "v.safetensors", d / "b.safetensors"
325
  write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
326
  write_st(b, {"model.language_model.embed_tokens.weight": (np.full((4, 8), 1.0, dtype=np.float16), "F16")})
 
328
  voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
329
 
330
  def test_headless_baseless_still_fails(self):
331
+ d = _mktmp(self)
332
  v, b = d / "v.safetensors", d / "b.safetensors"
333
  write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
334
  write_st(b, {"blk.0.attn.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")})
335
  with self.assertRaises(SystemExit):
336
  voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
337
 
338
+ def test_resolve_head_want_table(self):
339
+ E = "model.language_model.embed_tokens.weight"
340
+ F = lambda: (np.full((4, 4), 1.0, dtype=np.float16), "F16")
341
+ cases = [
342
+ ("reroutes tied head to embed",
343
+ {E: F()}, ["lm_head.weight"], [E]),
344
+ ("dedupes embed",
345
+ {E: F()}, ["lm_head.weight", E], [E]),
346
+ ("untied unchanged",
347
+ {"lm_head.weight": F(), E: F()}, ["lm_head.weight"], ["lm_head.weight"]),
348
+ ("headless unchanged",
349
+ {"blk.0.attn.weight": F()}, ["lm_head.weight"], ["lm_head.weight"]),
350
+ ("cross-format alias",
351
+ {"lm_head.weight": F()}, ["output.weight"], ["lm_head.weight"]),
352
+ ]
353
+ for label, tensors, want, expected in cases:
354
+ with self.subTest(label):
355
+ d = _mktmp(self)
356
+ b = d / "b.safetensors"
357
+ write_st(b, tensors)
358
+ self.assertEqual(voice._resolve_head_want(str(b), None, want), expected)
359
+
360
+ def test_role_table(self):
361
+ self.assertEqual(voice.role_of("lm_head.weight"), "head")
362
+ self.assertEqual(voice.role_of("model.output.weight"), "head")
363
+ self.assertEqual(voice.role_of("token_embd.weight"), "embed")
364
+ self.assertEqual(voice.role_of("model.language_model.embed_tokens.weight"), "embed")
365
+ self.assertEqual(voice.role_of("blk.0.ffn_down.weight"), "body")
366
+ self.assertEqual(voice.role_of(""), "body")
367
+ self.assertTrue(voice.is_tied(["model.language_model.embed_tokens.weight", "blk.0.weight"]))
368
+ self.assertTrue(voice.is_tied(["token_embd.weight"]))
369
+ self.assertFalse(voice.is_tied(["lm_head.weight", "model.language_model.embed_tokens.weight"]))
370
+ self.assertFalse(voice.is_tied(["output.weight", "token_embd.weight"]))
371
+ self.assertFalse(voice.is_tied([]))
372
+ self.assertEqual(voice.find_head(["blk.0.weight", "output.weight"]), "output.weight")
373
+ self.assertIsNone(voice.find_head(["blk.0.weight", "token_embd.weight"]))
374
+ self.assertEqual(voice.find_embed(["blk.0.weight", "token_embd.weight"]), "token_embd.weight")
375
+
376
+ def test_cross_format_head_delta_computes(self):
377
+ d = _mktmp(self)
378
+ v, b = d / "v.safetensors", d / "b.safetensors"
379
+ write_st(v, {"output.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
380
+ write_st(b, {"lm_head.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16"),
381
+ "model.language_model.embed_tokens.weight": (np.full((4, 4), 9.0, dtype=np.float16), "F16")})
382
+ out = voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
383
+ self.assertTrue((read_arr(out, "output.weight") == 1.0).all(), "cross-format head delta must equal voice(2.0) - base(1.0)")
384
 
385
+ def test_gguf_tied_base_delta_computes(self):
386
+ d = _mktmp(self)
387
+ v, b = d / "v.safetensors", d / "b.safetensors"
388
+ write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
389
+ write_st(b, {"token_embd.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16"),
390
+ "blk.0.attn.weight": (np.full((4, 4), 5.0, dtype=np.float16), "F16")})
391
+ out = voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
392
 
393
+ def test_ambiguous_head_fails_loud(self):
394
+ d = _mktmp(self)
395
+ v, b = d / "v.safetensors", d / "b.safetensors"
396
+ write_st(v, {"model.lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
397
  write_st(b, {"lm_head.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16"),
398
+ "output.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")})
399
+ with self.assertRaises(SystemExit):
400
+ voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
401
 
402
+ def test_gguf_voice_to_st_base_cross_format(self):
403
+ from gguf import GGUFWriter
404
+ from gguf.constants import GGMLQuantizationType as Q
405
+ d = _mktmp(self)
406
+ vp = d / "v.gguf"
407
+ w = GGUFWriter(str(vp), "llama", use_temp_file=False)
408
+ w.add_tensor("output.weight", np.full((4, 4), 2.0, dtype=np.float16), raw_dtype=Q.F16)
409
+ w.write_header_to_file()
410
+ w.write_kv_data_to_file()
411
+ w.write_tensors_to_file()
412
+ w.close()
413
+ b = d / "b.safetensors"
414
+ write_st(b, {"lm_head.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16"),
415
+ "model.language_model.embed_tokens.weight": (np.full((4, 4), 9.0, dtype=np.float16), "F16")})
416
+ out = voice._compute_delta(str(vp), str(b), d / "out", "delta-x", ns())
417
+ self.assertTrue((read_arr(out, "output.weight") == 1.0).all(), "GGUF voice head must delta against ST base head")
418
 
419
  def test_gguf_delta_chunked_matches_full(self):
420
  # Slow path (either side GGUF) must stream dequant in bounded chunks:
 
423
  from gguf import GGUFWriter
424
  from gguf.constants import GGMLQuantizationType as Q
425
  from gguf.quants import quantize
426
+ d = _mktmp(self)
427
  shape = (64, 128)
428
  rng = np.random.default_rng(7)
429
  vf = (rng.normal(size=shape) * 2).astype(np.float32)
 
458
  self.assertTrue((got == want).all())
459
  def test_share_safe_delta_header(self):
460
  import json as _j
461
+ d = _mktmp(self)
462
  home = d / "Users" / "someone" / "Desktop"
463
  home.mkdir(parents=True)
464
  self._pair(home)
 
477
  self.assertEqual(meta.get("voice"), "v.safetensors")
478
 
479
  def test_verify_agrees(self):
480
+ d = _mktmp(self)
481
  write_st(d / "v.safetensors",
482
  {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")})
483
  meta = {"tensor_name": "output.weight", "shape": [4, 4],
 
485
  self.assertEqual(voice._verify_voice_file(str(d / "v.safetensors"), meta), [])
486
 
487
  def test_verify_flags_mismatch(self):
488
+ d = _mktmp(self)
489
  write_st(d / "v.safetensors",
490
  {"output.weight": (np.zeros((4, 4), dtype=np.float16), "F16")})
491
  meta = {"tensor_name": "output.weight", "shape": [262144, 2048],
 
515
 
516
  def test_niche_gates_fail_fast_non_interactive(self):
517
  for mv, mb in ((False, True), (True, False), (True, True)):
518
+ d = _mktmp(self)
519
  v, b = self._pair(d, marker_voice=mv, marker_base=mb)
520
  with self.assertRaises(SystemExit, msg=f"mv={mv} mb={mb}"):
521
  voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
 
525
  def test_get_from_local_gguf(self):
526
  from gguf import GGUFWriter
527
  from gguf.constants import GGMLQuantizationType as Q
528
+ d = _mktmp(self)
529
  gp = d / "tiny.gguf"
530
  w = GGUFWriter(str(gp), "llama", use_temp_file=False)
531
  w.add_architecture()
 
538
  voice.cmd_get(ns(source=str(gp), name="tiny-gguf"))
539
  self.assertTrue((self.vdir / "tiny-gguf" / "voice.safetensors").exists())
540
 
541
+ def test_get_from_split_repo_picks_head(self):
542
+ import types
543
+ from unittest import mock
544
+ from vlib import cmds_voices
545
+ names = ["blk.0.ffn_down.weight", "output.weight"]
546
+ stub = types.SimpleNamespace(
547
+ kind="gguf", path=None, repo=None, _reader=None, _remote=None,
548
+ names=lambda: names,
549
+ ref=lambda n: voice.TensorRef(n, "BF16", (8, 4)),
550
+ _load=lambda: None)
551
+ arr = np.zeros((8, 4), dtype=np.float16)
552
+ with mock.patch.object(cmds_voices, "open_source", return_value=stub), \
553
+ mock.patch.object(cmds_voices, "_fetch_tensor",
554
+ return_value=("bytes", None, arr.tobytes(), "BF16", (8, 4))) as ft:
555
+ voice.cmd_get(ns(source="org/m", name="x"))
556
+ self.assertEqual(ft.call_args[0][1], "output.weight")
557
+ self.assertTrue((self.vdir / "x" / "voice.safetensors").exists())
558
+
559
  class TestGgufTensorFirst(unittest.TestCase):
560
  def _parsed(self, tensors):
561
  from gguf.constants import GGMLQuantizationType as Q
 
595
  self.assertTrue(r("F32") > r("BF16") > r("F16") > r("Q8_0") > r("Q4_K") > r("IQ1_M") > r("NVFP4"))
596
  self.assertEqual(r("NOPE"), -1)
597
 
 
 
 
 
598
  def test_multi_source_union_prefers_best_fidelity(self):
599
  u1 = "https://h/x/a.gguf"
600
  u2 = "https://h/x/b.gguf"
 
665
  from unittest import mock
666
  import vlib.net as net
667
  from vlib import ctx
668
+ d = _mktmp(self)
669
  big = net._PROGRESS_BYTES + 8
670
  def fake_dl(url, s, e, part_dir, etag, label=""):
671
  part_dir.mkdir(parents=True, exist_ok=True)
 
683
  from unittest import mock
684
  import vlib.net as net
685
  from vlib import ctx
686
+ d = _mktmp(self)
687
  def fake_dl(url, s, e, part_dir, etag, label=""):
688
  part_dir.mkdir(parents=True, exist_ok=True)
689
  (part_dir / "chunk_000.part").write_bytes(b"z")
 
700
  from contextlib import redirect_stdout
701
  from unittest import mock
702
  from vlib import ctx
703
+ d = _mktmp(self)
704
  v, b = d / "v.safetensors", d / "b.safetensors"
705
  write_st(v, {"lm_head.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
706
  write_st(b, {"model.language_model.embed_tokens.weight": (np.full((4, 4), 1.0, dtype=np.float16), "F16")})
 
709
  voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
710
  self.assertNotIn("ties its head", buf.getvalue(), "filler must not leak through -q")
711
 
712
+ def test_lookup_opener_and_quiet(self):
713
+ import io
714
+ from contextlib import redirect_stdout
715
+ from unittest import mock
716
+ from vlib import cmds_voices, ctx
717
+ with mock.patch.object(cmds_voices, "open_source", side_effect=RuntimeError("net down")):
718
+ buf = io.StringIO()
719
+ with redirect_stdout(buf):
720
+ with self.assertRaises(SystemExit):
721
+ voice.cmd_get(ns(source="org/model", name="x"))
722
+ self.assertIn("Looking up org/model", buf.getvalue())
723
+ buf2 = io.StringIO()
724
+ with mock.patch.object(ctx, "QUIET", True), redirect_stdout(buf2):
725
+ with self.assertRaises(SystemExit):
726
+ voice.cmd_get(ns(source="org/model", name="x"))
727
+ self.assertNotIn("Looking up", buf2.getvalue())
728
+
729
+ def test_using_opener_and_quiet(self):
730
+ import io
731
+ from contextlib import redirect_stdout
732
+ from unittest import mock
733
+ from vlib import ctx
734
+ b = "https://huggingface.co/o/m/resolve/main/"
735
+ mapping = {b + "m-Q8_0.gguf": (("llama", 64, {"blk.0.attn.weight": ([4, 4], 8, 0, 8),
736
+ "output.weight": ([8, 4], 8, 0, 8)}))}
737
+ with mock.patch("vlib.sources._parse_gguf_header", side_effect=lambda u: mapping[u]):
738
+ buf = io.StringIO()
739
+ with redirect_stdout(buf):
740
+ voice._gguf_source_for_repo("o/m", "main", ["m-Q8_0.gguf"])
741
+ self.assertIn("Using m-Q8_0.gguf", buf.getvalue())
742
+ buf2 = io.StringIO()
743
+ with mock.patch.object(ctx, "QUIET", True), redirect_stdout(buf2):
744
+ voice._gguf_source_for_repo("o/m", "main", ["m-Q8_0.gguf"])
745
+ self.assertNotIn("Using", buf2.getvalue())
746
+
747
+ def test_saving_opener_and_quiet(self):
748
+ import io
749
+ from contextlib import redirect_stdout
750
+ from unittest import mock
751
+ from vlib import ctx
752
+ d = _mktmp(self)
753
+ arr = np.full((4, 4), 1.0, dtype=np.float16)
754
+ fetched = ("bytes", None, arr.tobytes(), "F16", (4, 4))
755
+ buf = io.StringIO()
756
+ with redirect_stdout(buf):
757
+ voice._write_voice(d / "v", "output.weight", fetched, {"name": "x"})
758
+ self.assertIn("Saving voice", buf.getvalue())
759
+ self.assertTrue((d / "v" / "voice.safetensors").exists())
760
+ buf2 = io.StringIO()
761
+ with mock.patch.object(ctx, "QUIET", True), redirect_stdout(buf2):
762
+ voice._write_voice(d / "v2", "output.weight", fetched, {"name": "x"})
763
+ self.assertNotIn("Saving", buf2.getvalue())
764
+
765
+ def test_preparing_opener_and_quiet(self):
766
+ import io
767
+ from contextlib import redirect_stdout
768
+ from unittest import mock
769
+ from vlib import cmds_voices, ctx
770
+ d = _mktmp(self)
771
+ v = d / "v.safetensors"
772
+ write_st(v, {"output.weight": (np.full((4, 4), 2.0, dtype=np.float16), "F16")})
773
+ with mock.patch.object(cmds_voices, "_ensure_base_tensors", side_effect=SystemExit(1)):
774
+ buf = io.StringIO()
775
+ with redirect_stdout(buf):
776
+ with self.assertRaises(SystemExit):
777
+ voice.cmd_delta(ns(voicename=str(v), base="org/model"))
778
+ self.assertIn("Preparing base", buf.getvalue())
779
+ buf2 = io.StringIO()
780
+ with mock.patch.object(ctx, "QUIET", True), redirect_stdout(buf2):
781
+ with self.assertRaises(SystemExit):
782
+ voice.cmd_delta(ns(voicename=str(v), base="org/model"))
783
+ self.assertNotIn("Preparing", buf2.getvalue())
784
+
785
+ def test_source_read_f32_large_uses_progress_path(self):
786
+ import struct
787
+ from unittest import mock
788
+ import vlib.net as net
789
+ from vlib import ctx
790
+ from gguf.constants import GGMLQuantizationType as Q
791
+ d = _mktmp(self)
792
+ raw64 = struct.pack("<16f", *([1.0] * 16))
793
+ table = {"output.weight": ([4, 4], int(Q.F32), 0, 20000000)}
794
+ parsed = ("llama", 64, table)
795
+ def fake_dl(url, s, e, part_dir, etag, label=""):
796
+ part_dir.mkdir(parents=True, exist_ok=True)
797
+ (part_dir / "combined.part").write_bytes(raw64)
798
+ return part_dir / "combined.part"
799
+ with mock.patch("vlib.sources._parse_gguf_header", return_value=parsed), \
800
+ mock.patch.object(ctx, "VOICES_DIR", d), \
801
+ mock.patch.object(net, "download_range", side_effect=fake_dl) as dr:
802
+ src = voice.GgufSource(urls=["http://x/m.gguf"])
803
+ got = src.read_f32("output.weight")
804
+ self.assertEqual(tuple(got.shape), (4, 4))
805
+ self.assertTrue((got == 1.0).all())
806
+ self.assertTrue(dr.called, "large tensor must go through the progress path")
807
+
808
 
809
  class TestQuantShapes(unittest.TestCase):
810
  def _q8_voice(self, d, shape=(64, 96)):
 
825
  def test_single_tensor_artifact_keeps_logical_shape(self):
826
  from gguf.constants import GGMLQuantizationType as Q
827
  from gguf.quants import quantize
828
+ d = _mktmp(self)
829
  vp, fused = self._q8_voice(d)
830
  src = voice.open_source(str(vp))
831
  ref = src.ref("output.weight")
 
841
  def test_transplant_cast_keeps_shape_and_bytes(self):
842
  from gguf import GGUFReader, GGUFWriter
843
  from gguf.constants import GGMLQuantizationType as Q
844
+ d = _mktmp(self)
845
  vp, _ = self._q8_voice(d)
846
  tp = d / "t.gguf"
847
  w = GGUFWriter(str(tp), "llama", use_temp_file=False)
 
873
  return d / "v.safetensors", d / "b.safetensors"
874
 
875
  def test_pack_delta_computes_all(self):
876
+ d = _mktmp(self)
877
  v, b = self._pack_pair(d)
878
  out = voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())
879
  for name, want in (("output.weight", 1.0), ("model.norm.weight", 1.0)):
 
881
  self.assertTrue((got == want).all(), name)
882
 
883
  def test_pack_delta_missing_name_fails(self):
884
+ d = _mktmp(self)
885
  write_st(d / "v.safetensors",
886
  {"ghost.weight": (np.zeros((2, 2), np.float16), "F16")})
887
  write_st(d / "b.safetensors",
 
893
  def test_tensor_cast_delta_fuses_not_replaces(self):
894
  from gguf import GGUFReader, GGUFWriter
895
  from gguf.constants import GGMLQuantizationType as Q
896
+ d = _mktmp(self)
897
  write_st(d / "v.safetensors",
898
  {"output.weight": (np.full((4, 4), 3.0, np.float16), "F16")})
899
  write_st(d / "b.safetensors",
 
917
  def test_pack_cast_gguf_fuses_all(self):
918
  from gguf import GGUFReader, GGUFWriter
919
  from gguf.constants import GGMLQuantizationType as Q
920
+ d = _mktmp(self)
921
  v, b = self._pack_pair(d)
922
  dout = voice._compute_delta(str(v), str(b), d / "dout", "delta-x", ns())
923
  tp = d / "t.gguf"
 
937
 
938
  def test_pack_cast_safetensors_fuses_all(self):
939
 
940
+ d = _mktmp(self)
941
  v, b = self._pack_pair(d)
942
  dout = voice._compute_delta(str(v), str(b), d / "dout", "delta-x", ns())
943
  write_st(d / "t.safetensors", {
 
953
  def test_pack_cast_safetensors_single_pass(self):
954
  # The old chain called rewrite_safetensors_tensor once per tensor
955
  # (O(N.file) full copies). The fused path must succeed with it disabled.
956
+ d = _mktmp(self)
957
  v, b = self._pack_pair(d)
958
  dout = voice._compute_delta(str(v), str(b), d / "dout", "delta-x", ns())
959
  write_st(d / "t.safetensors", {
 
980
  return d / "base.safetensors"
981
 
982
  def test_validate_hit(self):
983
+ d = _mktmp(self)
984
  p = self._cache(d, {"a": (np.zeros((4, 4), np.float16), "F16")})
985
  self.assertEqual(voice._cache_validate(str(p), ["a"]), [])
986
 
987
  def test_validate_missing_and_truncated(self):
988
  import struct as _st, json as _j
989
+ d = _mktmp(self)
990
  p = self._cache(d, {"a": (np.zeros((4, 4), np.float16), "F16")})
991
  raw = bytearray(p.read_bytes())
992
  hs = _st.unpack("<Q", bytes(raw[:8]))[0]
 
997
  self.assertEqual(sorted(voice._cache_validate(str(p), ["a", "b", "c"])), ["b", "c"])
998
 
999
  def test_validate_garbage(self):
1000
+ d = _mktmp(self)
1001
  p = d / "base.safetensors"
1002
  p.write_bytes(b"not-a-safetensors-file")
1003
  self.assertEqual(voice._cache_validate(str(p), ["a"]), ["a"])
1004
 
1005
  def test_topup_write_roundtrip(self):
1006
+ d = _mktmp(self)
1007
  p = self._cache(d, {"a": (np.full((4, 4), 7.0, np.float16), "F16")})
1008
  rawf = d / "raw.bin"
1009
  rawf.write_bytes(np.full((8,), 9.0, np.float16).tobytes())
 
1093
  def test_pack_preset_head_only(self):
1094
  # Preset is the output head, nothing else. Tied repos resolve the embed
1095
  # (it doubles as head); untied resolve lm_head.
1096
+ d = _mktmp(self)
1097
  write_st(d / "tied.safetensors", {
1098
  "model.language_model.embed_tokens.weight": (np.zeros((8, 4), np.float16), "F16"),
1099
  "model.language_model.norm.weight": (np.zeros((4,), np.float16), "F16")})
 
1122
  # ST pack names onto a GGUF target speaking llama.cpp names (replace mode).
1123
  from gguf import GGUFReader, GGUFWriter
1124
  from gguf.constants import GGMLQuantizationType as Q
1125
+ d = _mktmp(self)
1126
  write_st(d / "pack.safetensors", {
1127
  "model.language_model.embed_tokens.weight": (np.full((4, 4), 3.0, np.float16), "F16"),
1128
  "lm_head.weight": (np.full((4, 4), 7.0, np.float16), "F16")})
 
1153
  from gguf import GGUFReader, GGUFWriter
1154
  from gguf.constants import GGMLQuantizationType as Q
1155
  from gguf.quants import quant_shape_to_byte_shape
1156
+ d = _mktmp(self)
1157
  logical = (256, 256)
1158
  raw = np.zeros(quant_shape_to_byte_shape(logical, Q.Q4_K), dtype=np.uint8)
1159
  tp = d / "t.gguf"
 
1255
  def test_venv_reexec_targets_entry(self):
1256
  # Re-exec must run voice.py (absolute) with argv intact — never the module.
1257
  import types
1258
+ d = _mktmp(self)
1259
  vp = d / ".venv" / "bin"
1260
  vp.mkdir(parents=True)
1261
  (vp / "python").symlink_to(sys.executable)
 
1315
  # offsets: fail up front with guidance, not warn-then-dump (B1).
1316
  import io
1317
  from contextlib import redirect_stdout
1318
+ d = _mktmp(self)
1319
  write_st(d / "t.safetensors",
1320
  {"output.weight": (np.zeros((4, 4), np.float32), "F32")})
1321
  write_st(d / "v.safetensors",
 
1346
  def test_requested_subset_routes_by_role(self):
1347
  # An explicitly named tensor must land in its own slot, never the
1348
  # output-first fallback (D2: embed request fitted onto lm_head).
1349
+ d = _mktmp(self)
1350
  write_st(d / "v.safetensors", {
1351
  "model.embed_tokens.weight": (np.full((4, 3), 7.0, np.float16), "F16"),
1352
  "model.lm_head.weight": (np.full((8, 4), 8.0, np.float16), "F16")})
 
1372
  # Old code compared raw strings, so a cwd-relative in-registry path
1373
  # never matched the absolute VOICES_DIR scope and skipped the walk.
1374
  import os as _os
1375
+ t = _mktmp(self)
1376
  (t / "real" / ".voices").mkdir(parents=True)
1377
  (t / "elsewhere").mkdir()
1378
  try:
 
1401
  voice._assert_not_symlink(self.vdir / "myadd" / "voice.json")
1402
  sib = self.vdir.parent / (self.vdir.name + "2")
1403
  sib.mkdir(exist_ok=True)
1404
+ self.addCleanup(shutil.rmtree, sib, True)
1405
  with self.assertRaises(SystemExit):
1406
  voice._assert_not_symlink(sib / "voice.json")
1407
+ voice._assert_not_symlink(_mktmp(self) / "voice.json")
1408
 
1409
  def test_topup_write_refuses_symlink(self):
1410
+ d = _mktmp(self)
1411
  hdr = {"a": {"dtype": "F16", "shape": [4], "data_offsets": [0, 8]}}
1412
  hj = json.dumps(hdr).encode()
1413
  real = d / "base.safetensors"
vlib/cache.py CHANGED
@@ -8,9 +8,8 @@ from vlib import ctx
8
  from vlib.ui import _fail, _now_iso, _say, _step, _warn
9
  from vlib.net import _cleanup_tmp, _safe_id, http_get_json
10
  from vlib.tensors import _is_ggml_quant, _write_safetensors_streaming, read_safetensors, write_safetensors
11
- from vlib.sources import _base_paths, open_source
12
  from vlib.fetch import _fetch_tensor, _resolve_output_name, _source_arch
13
- from vlib.delta import _tied_embed_name, _voice_head_name
14
  from vlib.registry import _assert_not_symlink
15
 
16
 
@@ -119,15 +118,15 @@ def _cache_topup_write(base_file, staged):
119
  return new_hdr
120
 
121
 
122
- def _tied_head_want(base_id, rev, want):
123
- """Reroute a wanted voice head onto the base's tied embed tensor.
124
- Voice untied + base tied: the base can never serve the head name, so
125
- want the embed instead (the delta pairs them later). Returns the
126
- want list, order-preserved and deduplicated. Anything unresolvable
127
- (offline, base has the head, base not tied) returns want unchanged
128
- and downstream fails exactly as before."""
129
- head = _voice_head_name(want)
130
- if head is None or head not in want:
131
  return want
132
  try:
133
  src = open_source(base_id, rev=rev)
@@ -136,13 +135,23 @@ def _tied_head_want(base_id, rev, want):
136
  raise
137
  except Exception:
138
  return want
139
- if head in names:
140
- return want
141
- emb = _tied_embed_name(names)
142
- if emb is None:
 
 
 
 
 
 
 
 
 
 
 
143
  return want
144
- _step("Base model ties its head — fetching its embedding for the match.")
145
- return list(dict.fromkeys(emb if n == head else n for n in want))
146
 
147
 
148
  def _ensure_base_tensors(base_id, names, args=None):
@@ -228,9 +237,10 @@ def _ensure_base_tensors_locked(base_id, base_file, base_json, want):
228
  rev = _base_rev(base_id, base_file)
229
  missing = _cache_validate(base_file, want)
230
  if missing:
231
- # Reroute before fetching: voice head vs tied base serves the embed
232
- # instead. Probed only on a miss, so warm caches never touch network.
233
- want = _tied_head_want(base_id, rev, want)
 
234
  missing = _cache_validate(base_file, want)
235
  if not missing:
236
  return base_file
 
8
  from vlib.ui import _fail, _now_iso, _say, _step, _warn
9
  from vlib.net import _cleanup_tmp, _safe_id, http_get_json
10
  from vlib.tensors import _is_ggml_quant, _write_safetensors_streaming, read_safetensors, write_safetensors
11
+ from vlib.sources import _base_paths, open_source, role_of, is_tied
12
  from vlib.fetch import _fetch_tensor, _resolve_output_name, _source_arch
 
13
  from vlib.registry import _assert_not_symlink
14
 
15
 
 
118
  return new_hdr
119
 
120
 
121
+ def _resolve_head_want(base_id, rev, want):
122
+ """Reroute wanted head/embed tensors onto the base's same-role names.
123
+ Covers cross-format aliases (voice `output.weight` vs base `lm_head`)
124
+ and tied bases (voice head vs base embed — the delta pairs them later).
125
+ Returns the want list, order-preserved and deduplicated. Anything
126
+ unresolvable (offline, exact names present, no same-role counterpart)
127
+ returns want unchanged and downstream fails exactly as before."""
128
+ heads = [n for n in want if role_of(n) in ("head", "embed")]
129
+ if not heads:
130
  return want
131
  try:
132
  src = open_source(base_id, rev=rev)
 
135
  raise
136
  except Exception:
137
  return want
138
+ remap = {}
139
+ for h in heads:
140
+ if h in names:
141
+ continue
142
+ cands = [n for n in names if role_of(n) == role_of(h)]
143
+ tied = False
144
+ if not cands and role_of(h) == "head" and is_tied(names):
145
+ cands = [n for n in names if role_of(n) == "embed"]
146
+ tied = bool(cands)
147
+ if len(cands) != 1:
148
+ return want
149
+ remap[h] = cands[0]
150
+ if tied:
151
+ _step("Base model ties its head — fetching its embedding for the match.")
152
+ if not remap:
153
  return want
154
+ return list(dict.fromkeys(remap.get(n, n) for n in want))
 
155
 
156
 
157
  def _ensure_base_tensors(base_id, names, args=None):
 
237
  rev = _base_rev(base_id, base_file)
238
  missing = _cache_validate(base_file, want)
239
  if missing:
240
+ # Reroute before fetching: same-role base names serve cross-format
241
+ # heads/embeds (voice head vs tied base serves the embed instead).
242
+ # Probed only on a miss, so warm caches never touch network.
243
+ want = _resolve_head_want(base_id, rev, want)
244
  missing = _cache_validate(base_file, want)
245
  if not missing:
246
  return base_file
vlib/delta.py CHANGED
@@ -9,57 +9,11 @@ import time
9
  from vlib.ui import _fail, _noninteractive, _progress_pref, _say, _step, _transform, _warn
10
  from vlib.net import _fmt_eta
11
  from vlib.tensors import _is_delta_safetensors, _is_ggml_quant, decode_to_f32, dtype_bytes, read_safetensors
12
- from vlib.sources import _detect_base, _normalize_hf_repo, _public_source, open_source, OUTPUT_ALIASES, EMBEDDING_ALIASES
13
  from vlib.fetch import _resolve_output_name, _source_arch
14
  from vlib.registry import _assert_not_symlink, _iter_voices, _read_meta
15
 
16
 
17
- _EMBED_SUFFIXES = ("embed_tokens.weight", "word_embeddings.weight", "wte.weight", "token_embd.weight")
18
-
19
-
20
- def _tied_embed_name(b_names):
21
- """Base-side tied counterpart: the embed tensor doubling as output head.
22
- Returns the embed name only when the base is truly headless (no head
23
- tensor at all); otherwise None."""
24
- for n in b_names:
25
- if n in OUTPUT_ALIASES:
26
- return None
27
- if n.endswith("weight") and ("lm_head" in n or "output_layer" in n or "embed_out" in n):
28
- return None
29
- for n in b_names:
30
- if n in EMBEDDING_ALIASES or n.endswith(_EMBED_SUFFIXES):
31
- return n
32
- return None
33
-
34
-
35
- def _voice_head_name(v_names):
36
- """Voice-side output head: exact alias first, head-like pattern after."""
37
- for n in v_names:
38
- if n in OUTPUT_ALIASES:
39
- return n
40
- for n in v_names:
41
- if n.endswith("weight") and ("lm_head" in n or "output_layer" in n or "embed_out" in n):
42
- return n
43
- return None
44
-
45
-
46
- def _tied_head_pair(head, b_names, vshape, bshape_of):
47
- """Voice untied + base tied: pair the voice head with the base's tied
48
- embed tensor (it serves as both input and output projection, so it is
49
- the only valid counterpart). Returns the base name, or None when the
50
- base is not tied. Shapes must match exactly."""
51
- if head is None:
52
- return None
53
- b_emb = _tied_embed_name(b_names)
54
- if b_emb is None:
55
- return None
56
- bshape = tuple(bshape_of(b_emb))
57
- if tuple(vshape) != bshape:
58
- _fail(f" ✗ Voice head '{head}' {list(vshape)} doesn't fit tied base '{b_emb}' {list(bshape)} — layouts differ.")
59
- _step("Base model ties its head — using its embedding as the match.")
60
- return b_emb
61
-
62
-
63
  def _choose_voice(args):
64
  voices = []
65
  for d in _iter_voices():
@@ -209,12 +163,13 @@ def _compute_delta(voice_path, base_path, delta_folder, delta_name, args=None):
209
  ordered = ([_cand] if _cand in v_names else []) + [n for n in v_names if n != _cand]
210
  missing = [n for n in ordered if n not in b_names]
211
  fallback = {}
212
- v_head = _voice_head_name(v_names)
213
- if v_head in missing:
214
- b = _tied_head_pair(v_head, b_names, tuple(v_src.ref(v_head).shape),
215
- lambda n: tuple(b_src.ref(n).shape))
 
216
  if b is not None:
217
- fallback[v_head] = b
218
  missing = [n for n in missing if n not in fallback]
219
  if missing:
220
  shown = ", ".join(missing[:5]) + ("…" if len(missing) > 5 else "")
@@ -302,12 +257,13 @@ def _compute_delta(voice_path, base_path, delta_folder, delta_name, args=None):
302
  _fail(" ✗ No tensors found for delta.")
303
  missing = [k for k in v_keys if k not in b_tensors]
304
  fallback = {}
305
- v_head = _voice_head_name(v_keys)
306
- if v_head in missing:
307
- b = _tied_head_pair(v_head, list(b_tensors.keys()), tuple(v_tensors[v_head]["shape"]),
308
- lambda n: tuple(b_tensors[n]["shape"]))
 
309
  if b is not None:
310
- fallback[v_head] = b
311
  missing = [k for k in missing if k not in fallback]
312
  if missing:
313
  shown = ", ".join(missing[:5]) + ("…" if len(missing) > 5 else "")
 
9
  from vlib.ui import _fail, _noninteractive, _progress_pref, _say, _step, _transform, _warn
10
  from vlib.net import _fmt_eta
11
  from vlib.tensors import _is_delta_safetensors, _is_ggml_quant, decode_to_f32, dtype_bytes, read_safetensors
12
+ from vlib.sources import _detect_base, _normalize_hf_repo, _public_source, open_source, pair_role, role_of
13
  from vlib.fetch import _resolve_output_name, _source_arch
14
  from vlib.registry import _assert_not_symlink, _iter_voices, _read_meta
15
 
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def _choose_voice(args):
18
  voices = []
19
  for d in _iter_voices():
 
163
  ordered = ([_cand] if _cand in v_names else []) + [n for n in v_names if n != _cand]
164
  missing = [n for n in ordered if n not in b_names]
165
  fallback = {}
166
+ for m in missing:
167
+ if role_of(m) not in ("head", "embed"):
168
+ continue
169
+ b = pair_role(m, tuple(v_src.ref(m).shape), b_names,
170
+ lambda n: tuple(b_src.ref(n).shape))
171
  if b is not None:
172
+ fallback[m] = b
173
  missing = [n for n in missing if n not in fallback]
174
  if missing:
175
  shown = ", ".join(missing[:5]) + ("…" if len(missing) > 5 else "")
 
257
  _fail(" ✗ No tensors found for delta.")
258
  missing = [k for k in v_keys if k not in b_tensors]
259
  fallback = {}
260
+ for m in missing:
261
+ if role_of(m) not in ("head", "embed"):
262
+ continue
263
+ b = pair_role(m, tuple(v_tensors[m]["shape"]), list(b_tensors.keys()),
264
+ lambda n: tuple(b_tensors[n]["shape"]))
265
  if b is not None:
266
+ fallback[m] = b
267
  missing = [k for k in missing if k not in fallback]
268
  if missing:
269
  shown = ", ".join(missing[:5]) + ("…" if len(missing) > 5 else "")
vlib/sources.py CHANGED
@@ -16,19 +16,97 @@ from vlib.tensors import _gguf_raw_to_f32, _gguf_tensor_f32, _is_gguf_file, _par
16
  OUTPUT_ALIASES = (
17
  "lm_head.weight", "output.weight", "transformer.output_layer.weight",
18
  "output_layer.weight", "embed_out.weight",
19
- # GGUF-only: tied checkpoints store the shared head under the embed
20
- # name (e.g. Gemma quants ship only token_embd.weight). No safetensors
21
- # file uses this name, so the shared detector is unaffected there.
22
- "token_embd.weight",
23
  )
24
 
25
 
26
  EMBEDDING_ALIASES = (
27
  "model.embed_tokens.weight", "embed_tokens.weight",
28
  "transformer.embedding.word_embeddings.weight", "wte.weight", "word_embeddings.weight",
 
 
 
 
29
  )
30
 
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  def _family(arch):
33
  a = (arch or "").lower()
34
  if "glm" in a or "chatglm" in a:
@@ -73,9 +151,10 @@ def detect_output_tensor(names, config):
73
  for alias in EMBEDDING_ALIASES:
74
  if alias in names:
75
  return alias
76
- # any embedding-like tensor (tied layouts, incl. transformer.wte.weight)
 
77
  for n in names:
78
- if n.endswith(("embed_tokens.weight", "word_embeddings.weight", "wte.weight")):
79
  return n
80
  return None
81
 
@@ -196,24 +275,15 @@ def _gguf_dtype_rank(dtype_name):
196
  return -1
197
 
198
 
199
- _GGUF_EMBED_SUFFIXES = ("embed_tokens.weight", "word_embeddings.weight", "wte.weight", "token_embd.weight")
200
-
201
-
202
  def _gguf_unit_census(names):
203
  """Tensor census for one candidate unit (single file or shard union).
204
  Returns (head_name_or_None, has_body). A unit is a base model only when
205
- it has BOTH a head-like tensor and transformer block markers — projector,
206
- imatrix, draft-head and adapter files fail one side or the other."""
207
- head = None
208
- for a in OUTPUT_ALIASES:
209
- if a in names:
210
- head = a
211
- break
212
- if head is None:
213
- for n in names:
214
- if n.endswith("weight") and ("lm_head" in n or "output_layer" in n or "embed_out" in n):
215
- head = n
216
- break
217
  body = any(n.startswith("blk.") for n in names)
218
  return head, body
219
 
 
16
  OUTPUT_ALIASES = (
17
  "lm_head.weight", "output.weight", "transformer.output_layer.weight",
18
  "output_layer.weight", "embed_out.weight",
 
 
 
 
19
  )
20
 
21
 
22
  EMBEDDING_ALIASES = (
23
  "model.embed_tokens.weight", "embed_tokens.weight",
24
  "transformer.embedding.word_embeddings.weight", "wte.weight", "word_embeddings.weight",
25
+ # GGUF tied checkpoints store the shared head under this name (e.g. Gemma
26
+ # quants ship only token_embd.weight). Kept here (embed role), not in
27
+ # OUTPUT_ALIASES, so tie detection reads structure, not aliases.
28
+ "token_embd.weight",
29
  )
30
 
31
 
32
+ _EMBED_SUFFIXES = ("embed_tokens.weight", "word_embeddings.weight", "wte.weight", "token_embd.weight")
33
+ _HEAD_PATTERNS = ("lm_head", "output_layer", "embed_out")
34
+
35
+
36
+ def role_of(name):
37
+ """Canonical role of one tensor name: 'head', 'embed', or 'body'.
38
+ Single home for the head/embed duality; cast's BODY machinery
39
+ (_ROLE_ALIASES, _same_role) is untouched and out of scope."""
40
+ if not name:
41
+ return "body"
42
+ if name in OUTPUT_ALIASES or name.endswith(tuple(OUTPUT_ALIASES)):
43
+ return "head"
44
+ if name in EMBEDDING_ALIASES or name.endswith(_EMBED_SUFFIXES):
45
+ return "embed"
46
+ if name.endswith("weight") and any(a in name for a in _HEAD_PATTERNS):
47
+ return "head"
48
+ return "body"
49
+
50
+
51
+ def is_tied(names):
52
+ """Structural tie check (no config, no downloads): an embed tensor is
53
+ present and no head tensor exists. The embed then serves as both input
54
+ and output projection."""
55
+ if not names:
56
+ return False
57
+ names = list(names)
58
+ return any(role_of(n) == "embed" for n in names) and not any(role_of(n) == "head" for n in names)
59
+
60
+
61
+ def find_head(names):
62
+ """Head-role tensor in `names`: exact alias first, pattern second."""
63
+ for a in OUTPUT_ALIASES:
64
+ if a in names:
65
+ return a
66
+ for n in names:
67
+ if role_of(n) == "head":
68
+ return n
69
+ return None
70
+
71
+
72
+ def find_embed(names):
73
+ """Embed-role tensor in `names`: exact alias first, suffix second."""
74
+ for a in EMBEDDING_ALIASES:
75
+ if a in names:
76
+ return a
77
+ for n in names:
78
+ if role_of(n) == "embed":
79
+ return n
80
+ return None
81
+
82
+
83
+ def pair_role(vname, vshape, b_names, bshape_of):
84
+ """Pair one voice tensor by (role, shape). Returns the base name or None.
85
+ Same-role alias wins; a head with no base head falls back to the tied
86
+ base embed. Shapes must match exactly; cross-name pairings announce
87
+ themselves, exact matches stay silent. None means: fail loud upstream."""
88
+ from vlib.ui import _fail, _step
89
+ if role_of(vname) not in ("head", "embed"):
90
+ return None
91
+ cands = [n for n in b_names if role_of(n) == role_of(vname)]
92
+ tied = False
93
+ if not cands and role_of(vname) == "head" and is_tied(b_names):
94
+ cands = [n for n in b_names if role_of(n) == "embed"]
95
+ tied = bool(cands)
96
+ if len(cands) != 1:
97
+ return None
98
+ b = cands[0]
99
+ if tuple(vshape) != tuple(bshape_of(b)):
100
+ _fail(f" ✗ Voice tensor '{vname}' {list(vshape)} doesn't fit base '{b}' {list(tuple(bshape_of(b)))}.")
101
+ if b == vname:
102
+ return b
103
+ if tied:
104
+ _step("Base model ties its head — using its embedding as the match.")
105
+ else:
106
+ _step(f"Using base '{b}' for voice '{vname}'.")
107
+ return b
108
+
109
+
110
  def _family(arch):
111
  a = (arch or "").lower()
112
  if "glm" in a or "chatglm" in a:
 
151
  for alias in EMBEDDING_ALIASES:
152
  if alias in names:
153
  return alias
154
+ # any embedding-like tensor (tied layouts, incl. transformer.wte.weight
155
+ # and GGUF token_embd.weight)
156
  for n in names:
157
+ if n.endswith(("embed_tokens.weight", "word_embeddings.weight", "wte.weight", "token_embd.weight")):
158
  return n
159
  return None
160
 
 
275
  return -1
276
 
277
 
 
 
 
278
  def _gguf_unit_census(names):
279
  """Tensor census for one candidate unit (single file or shard union).
280
  Returns (head_name_or_None, has_body). A unit is a base model only when
281
+ it has BOTH a fetchable head (true head, or tied embed carrier) and
282
+ transformer block markers — projector, imatrix, draft-head and adapter
283
+ files fail one side or the other."""
284
+ head = find_head(names)
285
+ if head is None and is_tied(names):
286
+ head = find_embed(names)
 
 
 
 
 
 
287
  body = any(n.startswith("blk.") for n in names)
288
  return head, body
289
 
voice-cli.tar.gz CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5ca5bc2a43c946a288c15ebdcb2daa96611936369035acafcf49ba194ffe0240
3
- size 74056
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97b2dd9b18db01e696031518efd35c4551fe5df981ad143b73e97363fbb3bbfd
3
+ size 73376
voice.py CHANGED
@@ -46,10 +46,10 @@ from vlib import ctx
46
  from vlib.compute import _load_voice, _orient, _cast_st_prepare, _cast_core, _is_head_name, _parse_quant_override, _quant_from_key, _quantize_to_Q, _qerr, _nearest_encodable, _fuse_delta, _gguf_fuse_one, _gguf_write_repl, _read_gguf_arch, _confirm_arch_mismatch, _cast_gguf, _cast_gguf_pack, _cast_pack, _parse_tensor_list, _parse_exclude_list, _resolve_one_tensor, _tensor_src_meta, _load_tensor, _pack_aliases, _resolve_pack_targets
47
  from vlib.net import _HF_TOKEN_CACHE, _get_hf_token, _HF_TRUSTED_HOSTS, _is_hf_url, _hf_auth_headers, _PreserveAuthRedirectHandler, _parse_retry_after, _bounded_retry_after, _timeout, http_range, http_get_json, _safe_id, _acquire_parts_lock, download_range, _fmt_eta, _cleanup_tmp
48
  from vlib.tensors import _validate_safetensors_header, read_safetensors, write_safetensors, _write_safetensors_streaming, rewrite_safetensors_tensor, _safetensors_write_repl, _DTYPE_BYTES_MAP, dtype_bytes, bf16_to_f32, decode_to_f32, encode_from_f32, _gguf_tensor_f32, _gguf_raw_to_f32, _gguf_raw_slice_to_f32, _DELTA_CHUNK_ELEMS, _gguf_nbytes, _parse_gguf_header, _is_gguf_file, _QUANT_DTYPES, _is_ggml_quant, _is_quant_fetched, _is_delta_safetensors, _write_single_tensor_gguf
49
- from vlib.sources import OUTPUT_ALIASES, EMBEDDING_ALIASES, _family, _nested, detect_output_tensor, largest_2d, _hf_config, _hf_license, _hf_model_index, _normalize_hf_repo, _base_paths, _hf_api_base_model, _hf_mergekit_base, _detect_base, TensorRef, SafetensorsSource, GgufSource, open_source, _source_from_repo, _pick_gguf, _sanitize_voice_name, _NAME_RULES, _public_source, _slugify_voice_name, _triage_gguf_files, _gguf_unit_census, _gguf_dtype_rank, _gguf_source_for_repo
50
  from vlib.fetch import _source_arch, _resolve_output_name, _stream_safetensors_tensor, _fetch_tensor, _stream_gguf_tensor, _fetch_pack, _write_fetched, _write_voicepack_json
51
  from vlib.registry import log_operation, _atomic_jsonl_append, _write_outbox, _append_report, _iter_voices, _registry_resolve, _read_meta, _registry_name_exists, _registry_folder, _assert_not_symlink, _write_voice, _resolve_name, _out_path, _stem, _check_overwrite
52
- from vlib.cache import _base_rev, _cache_validate, _cache_topup_write, _ensure_base_tensors, _ensure_base_tensors_locked, _cache_base, _load_safetensors_or_gguf_f32, _tied_head_want
53
  from vlib.delta import _choose_voice, _resolve_base, _delta_gate, _check_delta_gate, _compute_delta
54
  from vlib.reports import _hash_file, _sanitize_note, _sanitize_reporter, _prompt_share, _push_reports_batch, _push_report, _last_operation, cmd_report
55
  from vlib.cmds_voices import cmd_get, cmd_cast, cmd_delta, cmd_add
 
46
  from vlib.compute import _load_voice, _orient, _cast_st_prepare, _cast_core, _is_head_name, _parse_quant_override, _quant_from_key, _quantize_to_Q, _qerr, _nearest_encodable, _fuse_delta, _gguf_fuse_one, _gguf_write_repl, _read_gguf_arch, _confirm_arch_mismatch, _cast_gguf, _cast_gguf_pack, _cast_pack, _parse_tensor_list, _parse_exclude_list, _resolve_one_tensor, _tensor_src_meta, _load_tensor, _pack_aliases, _resolve_pack_targets
47
  from vlib.net import _HF_TOKEN_CACHE, _get_hf_token, _HF_TRUSTED_HOSTS, _is_hf_url, _hf_auth_headers, _PreserveAuthRedirectHandler, _parse_retry_after, _bounded_retry_after, _timeout, http_range, http_get_json, _safe_id, _acquire_parts_lock, download_range, _fmt_eta, _cleanup_tmp
48
  from vlib.tensors import _validate_safetensors_header, read_safetensors, write_safetensors, _write_safetensors_streaming, rewrite_safetensors_tensor, _safetensors_write_repl, _DTYPE_BYTES_MAP, dtype_bytes, bf16_to_f32, decode_to_f32, encode_from_f32, _gguf_tensor_f32, _gguf_raw_to_f32, _gguf_raw_slice_to_f32, _DELTA_CHUNK_ELEMS, _gguf_nbytes, _parse_gguf_header, _is_gguf_file, _QUANT_DTYPES, _is_ggml_quant, _is_quant_fetched, _is_delta_safetensors, _write_single_tensor_gguf
49
+ from vlib.sources import OUTPUT_ALIASES, EMBEDDING_ALIASES, _family, _nested, detect_output_tensor, largest_2d, _hf_config, _hf_license, _hf_model_index, _normalize_hf_repo, _base_paths, _hf_api_base_model, _hf_mergekit_base, _detect_base, TensorRef, SafetensorsSource, GgufSource, open_source, _source_from_repo, _pick_gguf, _sanitize_voice_name, _NAME_RULES, _public_source, _slugify_voice_name, _triage_gguf_files, _gguf_unit_census, _gguf_dtype_rank, _gguf_source_for_repo, role_of, is_tied, find_head, find_embed, pair_role
50
  from vlib.fetch import _source_arch, _resolve_output_name, _stream_safetensors_tensor, _fetch_tensor, _stream_gguf_tensor, _fetch_pack, _write_fetched, _write_voicepack_json
51
  from vlib.registry import log_operation, _atomic_jsonl_append, _write_outbox, _append_report, _iter_voices, _registry_resolve, _read_meta, _registry_name_exists, _registry_folder, _assert_not_symlink, _write_voice, _resolve_name, _out_path, _stem, _check_overwrite
52
+ from vlib.cache import _base_rev, _cache_validate, _cache_topup_write, _ensure_base_tensors, _ensure_base_tensors_locked, _cache_base, _load_safetensors_or_gguf_f32, _resolve_head_want
53
  from vlib.delta import _choose_voice, _resolve_base, _delta_gate, _check_delta_gate, _compute_delta
54
  from vlib.reports import _hash_file, _sanitize_note, _sanitize_reporter, _prompt_share, _push_reports_batch, _push_report, _last_operation, cmd_report
55
  from vlib.cmds_voices import cmd_get, cmd_cast, cmd_delta, cmd_add
voice.pyz CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1ce6f50700978bd60d88a4dcca8519a99b18e9f1650cebe9e9a73b5d7859a928
3
- size 269992
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb4c92845ded61a45b875fd60e3a6ad1361dcfce07d312f0ef1d3e5eb346fcb6
3
+ size 271251