Update voice.py, vlib, tests, bundles
Browse filesFiles changed (11)
- tests/test_units.py+159-1
- vlib/cache.py+6-2
- vlib/cmds_voices.py+4-1
- vlib/delta.py+2-2
- vlib/fetch.py+4-3
- vlib/net.py+23
- vlib/registry.py+2-1
- vlib/sources.py+231-23
- voice-cli.tar.gz+2-2
- voice.py+1-1
- voice.pyz+2-2
306 unmodified lines307308309310311312313161 unmodified lines475476477478479480306 unmodified linesout = voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())self.assertTrue((read_arr(out, "lm_head.weight") == 1.0).all(), "head delta must equal voice head(2.0) - tied base embed(1.0)")self.assertTrue((read_arr(out, "model.language_model.embed_tokens.weight") == 6.0).all(), "embed delta must equal voice embed(7.0) - base embed(1.0)")self.assertIn("tied", buf.getvalue(), "fallback must be loud, not silent")def test_tied_base_shape_mismatch_fails(self):d = Path(tempfile.mkdtemp())161 unmodified linesvoice.cmd_get(ns(source=str(gp), name="tiny-gguf"))self.assertTrue((self.vdir / "tiny-gguf" / "voice.safetensors").exists())class TestQuantShapes(unittest.TestCase):def _q8_voice(self, d, shape=(64, 96)):from gguf import GGUFWriter306 unmodified lines307308309310311312313161 unmodified lines475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638306 unmodified linesout = voice._compute_delta(str(v), str(b), d / "out", "delta-x", ns())self.assertTrue((read_arr(out, "lm_head.weight") == 1.0).all(), "head delta must equal voice head(2.0) - tied base embed(1.0)")self.assertTrue((read_arr(out, "model.language_model.embed_tokens.weight") == 6.0).all(), "embed delta must equal voice embed(7.0) - base embed(1.0)")self.assertIn("ties its head", buf.getvalue(), "fallback must be loud, not silent")def test_tied_base_shape_mismatch_fails(self):d = Path(tempfile.mkdtemp())161 unmodified linesvoice.cmd_get(ns(source=str(gp), name="tiny-gguf"))self.assertTrue((self.vdir / "tiny-gguf" / "voice.safetensors").exists())class TestGgufTensorFirst(unittest.TestCase):def _parsed(self, tensors):from gguf.constants import GGMLQuantizationType as Qoff, table = 0, {}for n, (dims, dt) in tensors.items():table[n] = (list(dims), int(Q[dt]), off, 8)off += 8return ("llama", 64, table)def _patch_parse(self, mapping):from unittest import mockimport vlib.sources as _srcreturn mock.patch.object(_src, "_parse_gguf_header", side_effect=lambda u: mapping[u])def test_triage_groups_splits_drops_polluters(self):files = ["BF16/m-00002-of-00002.gguf", "BF16/m-00001-of-00002.gguf","m-Q8_0.gguf", "mmproj-m.gguf", "x-imatrix.gguf"]g, s, d = voice._triage_gguf_files(files)self.assertEqual(g, [["BF16/m-00001-of-00002.gguf", "BF16/m-00002-of-00002.gguf"]])self.assertEqual(s, ["m-Q8_0.gguf"])self.assertEqual(sorted(d), ["mmproj-m.gguf", "x-imatrix.gguf"])def test_triage_singleton_split_counts_as_single(self):g, s, _d = voice._triage_gguf_files(["m-00001-of-00001.gguf"])self.assertEqual(g, [])self.assertEqual(s, ["m-00001-of-00001.gguf"])def test_census_requires_head_and_body(self):self.assertEqual(voice._gguf_unit_census(["blk.0.attn.weight", "output.weight"]), ("output.weight", True))self.assertEqual(voice._gguf_unit_census(["blk.0.attn.weight", "token_embd.weight"]), ("token_embd.weight", True))self.assertIsNone(voice._gguf_unit_census(["blk.0.attn.weight"])[0])self.assertFalse(voice._gguf_unit_census(["output.weight"])[1])self.assertEqual(voice._gguf_unit_census(["proj.weight"] * 1), (None, False))def test_dtype_rank_orders_fidelity(self):r = voice._gguf_dtype_rankself.assertTrue(r("F32") > r("BF16") > r("F16") > r("Q8_0") > r("Q4_K") > r("IQ1_M") > r("NVFP4"))self.assertEqual(r("NOPE"), -1)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_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 mockimport vlib.net as netwith 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 mockimport vlib.net as netfrom vlib import ctxd = Path(tempfile.mkdtemp())big = net._PROGRESS_BYTES + 8def 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 mockimport vlib.net as netfrom vlib import ctxd = Path(tempfile.mkdtemp())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 iofrom contextlib import redirect_stdoutfrom unittest import mockfrom vlib import ctxd = Path(tempfile.mkdtemp())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")class TestQuantShapes(unittest.TestCase):def _q8_voice(self, d, shape=(64, 96)):from gguf import GGUFWriter
140 unmodified lines14114214314414514614778 unmodified lines226227228229230231232233140 unmodified linesemb = _tied_embed_name(names)if emb is None:return want_say(f" → Base head is tied; caching '{emb}' for the head delta.")return list(dict.fromkeys(emb if n == head else n for n in want))78 unmodified lineselif not verified:_warn(" Base cache lineage unverified (offline?) — proceeding, mixed revisions possible.")rev = _base_rev(base_id, base_file)want = _tied_head_want(base_id, rev, want)missing = _cache_validate(base_file, want)if not missing:return base_file_step(f"Topping up base {base_id} ({len(missing)} tensor(s) missing)…")140 unmodified lines14114214314414514614778 unmodified lines226227228229230231232233234235236237140 unmodified linesemb = _tied_embed_name(names)if emb is None:return want_step("Base model ties its head — fetching its embedding for the match.")return list(dict.fromkeys(emb if n == head else n for n in want))78 unmodified lineselif not verified:_warn(" Base cache lineage unverified (offline?) — proceeding, mixed revisions possible.")rev = _base_rev(base_id, base_file)missing = _cache_validate(base_file, want)if missing:# Reroute before fetching: voice head vs tied base serves the embed# instead. Probed only on a miss, so warm caches never touch network.want = _tied_head_want(base_id, rev, want)missing = _cache_validate(base_file, want)if not missing:return base_file_step(f"Topping up base {base_id} ({len(missing)} tensor(s) missing)…")
27 unmodified lines28293031323376 unmodified lines110111112113114115116299 unmodified lines41641741841942042127 unmodified lines_fail(f' ✗ "{source_id}" couldn\'t be found.')try:source = open_source(source_id)names = source.names()if not names:76 unmodified linesif _registry_name_exists(name) and folder.exists() and ((folder / "voice.safetensors").exists() or (folder / "voice.gguf").exists()):_check_overwrite(str(folder), args)_step(f"{'Reading' if getattr(source, 'path', None) else 'Downloading'} {tname}…")tmp_dir = ctx.VOICES_DIR / ".parts" / _safe_id(source_id, tname)try:fetched = _fetch_tensor(source, tname, tmp_dir)299 unmodified lines_need = []if not _need:_fail(" ✗ No tensors found for delta.")base_file = _ensure_base_tensors(base_id, _need, args)delta_name = f"delta-{voicename.lower()}"27 unmodified lines282930313233343576 unmodified lines112113114115116117118299 unmodified lines41841942042142242342427 unmodified lines_fail(f' ✗ "{source_id}" couldn\'t be found.')try:if not _lp.exists():_step(f"Looking up {source_id}…")source = open_source(source_id)names = source.names()if not names:76 unmodified linesif _registry_name_exists(name) and folder.exists() and ((folder / "voice.safetensors").exists() or (folder / "voice.gguf").exists()):_check_overwrite(str(folder), args)_step(f"{'Reading' if getattr(source, 'path', None) else 'Downloading'} voice ({tname}, {ref.dtype})…")tmp_dir = ctx.VOICES_DIR / ".parts" / _safe_id(source_id, tname)try:fetched = _fetch_tensor(source, tname, tmp_dir)299 unmodified lines_need = []if not _need:_fail(" ✗ No tensors found for delta.")_step("Preparing base…")base_file = _ensure_base_tensors(base_id, _need, args)delta_name = f"delta-{voicename.lower()}"
5 unmodified lines678910111243 unmodified lines565758596061625 unmodified linesimport structimport sysimport timefrom vlib.ui import _fail, _noninteractive, _progress_pref, _say, _transform, _warnfrom vlib.net import _fmt_etafrom vlib.tensors import _is_delta_safetensors, _is_ggml_quant, decode_to_f32, dtype_bytes, read_safetensorsfrom vlib.sources import _detect_base, _normalize_hf_repo, _public_source, open_source, OUTPUT_ALIASES, EMBEDDING_ALIASES43 unmodified linesbshape = tuple(bshape_of(b_emb))if tuple(vshape) != bshape:_fail(f" ✗ Voice head '{head}' {list(vshape)} doesn't fit tied base '{b_emb}' {list(bshape)} — layouts differ.")_say(f" → Base head is tied; '{head}' deltas against '{b_emb}'.")return b_emb5 unmodified lines678910111243 unmodified lines565758596061625 unmodified linesimport structimport sysimport timefrom vlib.ui import _fail, _noninteractive, _progress_pref, _say, _step, _transform, _warnfrom vlib.net import _fmt_etafrom vlib.tensors import _is_delta_safetensors, _is_ggml_quant, decode_to_f32, dtype_bytes, read_safetensorsfrom vlib.sources import _detect_base, _normalize_hf_repo, _public_source, open_source, OUTPUT_ALIASES, EMBEDDING_ALIASES43 unmodified linesbshape = tuple(bshape_of(b_emb))if tuple(vshape) != bshape:_fail(f" ✗ Voice head '{head}' {list(vshape)} doesn't fit tied base '{b_emb}' {list(bshape)} — layouts differ.")_step("Base model ties its head — using its embedding as the match.")return b_emb
109 unmodified lines110111112113114115116117118109 unmodified linesout.write(raw)return t.n_bytesraise KeyError(name)dims, gtype, data_offset, n_bytes = source._remote[2][name]start = source._remote[1] + data_offsetcombined = download_range(source.url, start, start + n_bytes - 1, dest_path.parent, None, label=name)shutil.move(str(combined), str(dest_path))return n_bytes109 unmodified lines110111112113114115116117118119109 unmodified linesout.write(raw)return t.n_bytesraise KeyError(name)url, parsed = source._owner(name)dims, gtype, data_offset, n_bytes = parsed[2][name]start = parsed[1] + data_offsetcombined = download_range(url, start, start + n_bytes - 1, dest_path.parent, None, label=name)shutil.move(str(combined), str(dest_path))return n_bytes
434 unmodified lines435436437438439440434 unmodified linesreturn combineddef _fmt_eta(remaining, mbps):if mbps < 1e-6:return "--:--"434 unmodified lines435436437438439440441442443444445446447448449450451452453454455456457458459460461462463434 unmodified linesreturn combined_PROGRESS_BYTES = 16 * 1024 * 1024def _fetch_bytes_progress(url, start, end, label):"""Bytes for one HTTP range, with progress + resume when large.Small ranges keep the single http_range read (no flicker). Large rangesgo through the multipart downloader into a stable part dir (resume acrossruns), are read back, and cleaned up on success ONLY — parts stay onfailure so the next run resumes. Returns bytes; callers unchanged, andpeak RAM matches the single-read path (file is transient on disk)."""total = end - start + 1if total < _PROGRESS_BYTES:data, _st, _e = http_range(url, start, end, timeout=300)return datapart_dir = ctx.VOICES_DIR / ".parts" / _safe_id(url, f"{start}-{end}")combined = download_range(url, start, end, part_dir, None, label=label)try:with open(combined, "rb") as f:return f.read()finally:_cleanup_tmp(part_dir)def _fmt_eta(remaining, mbps):if mbps < 1e-6:return "--:--"
5 unmodified lines6789101112207 unmodified lines2202212222232242255 unmodified linesimport sysimport timefrom vlib import ctxfrom vlib.ui import _confirm, _fail, _noninteractive, _note, _say, _warnfrom vlib.tensors import _is_gguf_file, _is_quant_fetched, _write_safetensors_streaming, _write_single_tensor_gguf, write_safetensorsfrom vlib.sources import _NAME_RULES, _sanitize_voice_name, _slugify_voice_name207 unmodified linesdef _write_voice(folder, tensor_name, fetched, meta):_assert_not_symlink(folder)folder.mkdir(parents=True, exist_ok=True)try:os.chmod(folder, 0o700)5 unmodified lines6789101112207 unmodified lines2202212222232242252265 unmodified linesimport sysimport timefrom vlib import ctxfrom vlib.ui import _confirm, _fail, _noninteractive, _note, _say, _step, _warnfrom vlib.tensors import _is_gguf_file, _is_quant_fetched, _write_safetensors_streaming, _write_single_tensor_gguf, write_safetensorsfrom vlib.sources import _NAME_RULES, _sanitize_voice_name, _slugify_voice_name207 unmodified linesdef _write_voice(folder, tensor_name, fetched, meta):_assert_not_symlink(folder)_step("Saving voice…")folder.mkdir(parents=True, exist_ok=True)try:os.chmod(folder, 0o700)
7 unmodified lines8910111213141516171819202192 unmodified lines114115116117118119181 unmodified lines30130230330430530630730818 unmodified lines3273283293303313323333343353363373383393403413423433443453463473483493503513523 unmodified lines3563573583593603613624 unmodified lines3673683693703713723733743755 unmodified lines3813823833843853863873883893909 unmodified lines40040140240340440540640740816 unmodified lines4254264274284294301 unmodified line4324334344354364374384394404416 unmodified lines4484494504514524537 unmodified linesimport urllib.requestfrom urllib.parse import urlparsefrom vlib import ctxfrom vlib.ui import _fail, _notefrom vlib.net import _hf_auth_headers, http_get_json, http_rangefrom vlib.tensors import _gguf_raw_to_f32, _gguf_tensor_f32, _is_gguf_file, _parse_gguf_header, decode_to_f32OUTPUT_ALIASES = ("lm_head.weight", "output.weight", "transformer.output_layer.weight","output_layer.weight", "embed_out.weight",)92 unmodified linesreturn Nonedef _normalize_hf_repo(s):if not s or not s.strip():return None181 unmodified linesurl, hs, tensors = self._shard_info(name)info = tensors[name]begin, end = info["data_offsets"]data, _st, _e = http_range(url, 8 + hs + begin, 8 + hs + end - 1, timeout=300)return datadef read_raw_slice(self, name, byte_off, byte_len):"""Minimal slice read: byte_off/byte_len relative to the tensor's data."""18 unmodified linesclass GgufSource:kind = "gguf"def __init__(self, path=None, url=None, rev=None):self.path = str(path) if path else Noneself.url = urlself.rev = rev or "main"self._reader = Noneself._remote = Nonedef _load(self):if self.path:if self._reader is None:from gguf import GGUFReaderself._reader = GGUFReader(self.path)elif self._remote is None:self._remote = _parse_gguf_header(self.url)def names(self):self._load()if self._reader is not None:return [t.name for t in self._reader.tensors]return list(self._remote[2].keys())def ref(self, name):from gguf.constants import GGMLQuantizationType as Q3 unmodified linesif t.name == name:return TensorRef(name, t.tensor_type.name, tuple(reversed(t.shape)))raise KeyError(name)dims, gtype, _off, _nbytes = self._remote[2][name]return TensorRef(name, Q(gtype).name, tuple(reversed(dims)))def read_f32(self, name):4 unmodified linesif t.name == name:return _gguf_tensor_f32(t)raise KeyError(name)dims, gtype, data_offset, n_bytes = self._remote[2][name]start = self._remote[1] + data_offsetraw, _st, _e = http_range(self.url, start, start + n_bytes - 1, timeout=300)return _gguf_raw_to_f32(raw, Q(gtype), dims)def read_raw(self, name):5 unmodified linesif t.name == name:return t.data.tobytes() if t.data.dtype == np.uint8 else memoryview(t.data).cast("B").tobytes()raise KeyError(name)dims, gtype, data_offset, n_bytes = self._remote[2][name]start = self._remote[1] + data_offsetraw, _st, _e = http_range(self.url, start, start + n_bytes - 1, timeout=300)return rawdef read_raw_slice(self, name, byte_off, byte_len):"""Minimal slice read: byte_off/byte_len relative to the tensor's raw bytes."""9 unmodified linesexcept Exception:return self.read_raw(name)[byte_off:byte_off + byte_len]raise KeyError(name)dims, gtype, data_offset, n_bytes = self._remote[2][name]start = self._remote[1] + data_offset + byte_offraw, _st, _e = http_range(self.url, start, start + byte_len - 1, timeout=300)return raw16 unmodified linesreturn _source_from_repo(arg.strip().rstrip("/"), rev=rev)def _source_from_repo(repo, rev=None):rev = rev or "main"try:1 unmodified linefiles = [f.get("path", "") for f in tree if f.get("path")]ggufs = [f for f in files if f.endswith(".gguf")]if ggufs:chosen = _pick_gguf(ggufs)if ctx.VERBOSE:_note(f"GGUF repo — using {chosen}")return GgufSource(url=f"https://huggingface.co/{repo}/resolve/{rev}/{chosen}", rev=rev)if any(f.endswith(".safetensors") for f in files):return SafetensorsSource(repo=repo, rev=rev)if files:6 unmodified linesdef _pick_gguf(files):files = sorted(files)for key in ("fp16", "f16", "q8_0"):for f in files:7 unmodified lines891011121314151617181920212223242592 unmodified lines118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223181 unmodified lines40540640740840941041118 unmodified lines4304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854863 unmodified lines4904914924934944954964974 unmodified lines5025035045055065075085095105115 unmodified lines5175185195205215225235245255269 unmodified lines53653753853954054154254354454516 unmodified lines5625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376381 unmodified line6406416426436446456466 unmodified lines6536546556566576586596606617 unmodified linesimport urllib.requestfrom urllib.parse import urlparsefrom vlib import ctxfrom vlib.ui import _fail, _note, _stepfrom vlib.net import _fetch_bytes_progress, _hf_auth_headers, http_get_json, http_rangefrom vlib.tensors import _gguf_raw_to_f32, _gguf_tensor_f32, _is_gguf_file, _parse_gguf_header, decode_to_f32OUTPUT_ALIASES = ("lm_head.weight", "output.weight", "transformer.output_layer.weight","output_layer.weight", "embed_out.weight",# GGUF-only: tied checkpoints store the shared head under the embed# name (e.g. Gemma quants ship only token_embd.weight). No safetensors# file uses this name, so the shared detector is unaffected there."token_embd.weight",)92 unmodified linesreturn None_GGUF_SPLIT_RE = re.compile(r"^(?P<stem>.+)-(?P<idx>\d+)-of-(?P<total>\d+)\.gguf$", re.IGNORECASE)def _gguf_split_key(basename):"""Split-shard grouping key, or None for single files.'model-00001-of-00002.gguf' -> ('model', 2). Total==1 counts as single."""m = _GGUF_SPLIT_RE.match(basename)if not m or int(m.group("total")) <= 1:return Nonereturn (m.group("stem").lower(), int(m.group("total")))def _gguf_dropped(basename):"""Certain non-models, by name alone. Everything else faces the tensor census."""n = basename.lower()return n.startswith("mmproj") or n.endswith("-imatrix.gguf")def _gguf_name_rank(path):"""Fidelity-hint rank for probe ordering (cost only, never correctness).Higher wins. Suspicious-but-possible names demote slightly; the tensorcensus still gets the final vote."""n = path.lower()score = 0for i, key in enumerate(("fp32", "f32", "bf16", "fp16", "f16", "q8_0", "q6_k","q5_k", "q5_0", "q5_1", "q4_k", "q4_0", "q4_1", "q3_k")):if key in n:score = 100 - ibreakelse:if "iq" in n:score = 84for bad in ("mtp", "vision", "encoder", "lora", "draft", "instruct-"):if bad in n:score -= 3return scoredef _triage_gguf_files(files):"""Split a repo .gguf listing into (groups, singles, dropped). Pure function.groups: shard path-lists of one model each (shard order). singles: rankedbest-first. Incomplete shard groups are kept; the census/fetch stages failloud on truly missing tensors."""dropped = sorted(f for f in files if _gguf_dropped(f.split("/")[-1]))dropped_set = set(dropped)buckets, singles = {}, []for f in sorted(set(files) - dropped_set):parts = f.split("/")key = _gguf_split_key(parts[-1])if key is None:singles.append(f)else:buckets.setdefault((tuple(parts[:-1]),) + key, []).append(f)groups = [sorted(g) for g in buckets.values()]groups.sort(key=lambda g: _gguf_name_rank(g[0]), reverse=True)singles.sort(key=_gguf_name_rank, reverse=True)return groups, singles, dropped_GGUF_DTYPE_RANK = {"F32": 7, "FP32": 7, "BF16": 6, "BF16E8M": 6, "F16": 5, "FP16": 5,"Q8_0": 4, "Q6_K": 3, "Q5_0": 2, "Q5_1": 2, "Q5_K": 2,"Q4_0": 1, "Q4_1": 1, "Q4_K": 1,}def _gguf_dtype_rank(dtype_name):"""Fidelity rank for a tensor dtype name. Unknown/exotic quants rank last."""if not dtype_name:return -1n = str(dtype_name).upper()if n in _GGUF_DTYPE_RANK:return _GGUF_DTYPE_RANK[n]if n.startswith(("Q3", "Q2", "IQ")):return 0return -1_GGUF_EMBED_SUFFIXES = ("embed_tokens.weight", "word_embeddings.weight", "wte.weight", "token_embd.weight")def _gguf_unit_census(names):"""Tensor census for one candidate unit (single file or shard union).Returns (head_name_or_None, has_body). A unit is a base model only whenit has BOTH a head-like tensor and transformer block markers — projector,imatrix, draft-head and adapter files fail one side or the other."""head = Nonefor a in OUTPUT_ALIASES:if a in names:head = abreakif head is None:for n in names:if n.endswith("weight") and ("lm_head" in n or "output_layer" in n or "embed_out" in n):head = nbreakbody = any(n.startswith("blk.") for n in names)return head, bodydef _normalize_hf_repo(s):if not s or not s.strip():return None181 unmodified linesurl, hs, tensors = self._shard_info(name)info = tensors[name]begin, end = info["data_offsets"]return _fetch_bytes_progress(url, 8 + hs + begin, 8 + hs + end - 1, name)def read_raw_slice(self, name, byte_off, byte_len):"""Minimal slice read: byte_off/byte_len relative to the tensor's data."""18 unmodified linesclass GgufSource:kind = "gguf"def __init__(self, path=None, url=None, rev=None, urls=None):self.path = str(path) if path else Noneself.url = url# Split/multi layouts: ordered candidate file URLs (first = primary).# None/singleton behaves byte-for-byte like the legacy single url.self.urls = list(urls) if urls else ([url] if url else [])self.rev = rev or "main"self._reader = Noneself._remote = Noneself._parsed = []self._owners = Nonedef _load(self):if self.path:if self._reader is None:from gguf import GGUFReaderself._reader = GGUFReader(self.path)elif self._owners is None:from gguf.constants import GGMLQuantizationType as Qself._parsed = [_parse_gguf_header(u) for u in self.urls]self._remote = self._parsed[0] if self._parsed else Noneowners = {}for i, p in enumerate(self._parsed):for name, info in p[2].items():try:rank = _gguf_dtype_rank(Q(info[1]).name)except Exception:rank = -1owners.setdefault(name, []).append((rank, i))for name in owners:owners[name].sort(key=lambda t: t[0], reverse=True)owners[name] = [i for _, i in owners[name]]self._owners = ownersdef _owner(self, name):"""(url, parsed) holding the best-fidelity instance of `name`."""self._load()i = self._owners[name]return self.urls[i[0]], self._parsed[i[0]]def names(self):self._load()if self._reader is not None:return [t.name for t in self._reader.tensors]seen, known = [], set()for p in self._parsed:for k in p[2].keys():if k not in known:known.add(k)seen.append(k)return seendef ref(self, name):from gguf.constants import GGMLQuantizationType as Q3 unmodified linesif t.name == name:return TensorRef(name, t.tensor_type.name, tuple(reversed(t.shape)))raise KeyError(name)_u, parsed = self._owner(name)dims, gtype, _off, _nbytes = parsed[2][name]return TensorRef(name, Q(gtype).name, tuple(reversed(dims)))def read_f32(self, name):4 unmodified linesif t.name == name:return _gguf_tensor_f32(t)raise KeyError(name)url, parsed = self._owner(name)dims, gtype, data_offset, n_bytes = parsed[2][name]start = parsed[1] + data_offsetraw = _fetch_bytes_progress(url, start, start + n_bytes - 1, name)return _gguf_raw_to_f32(raw, Q(gtype), dims)def read_raw(self, name):5 unmodified linesif t.name == name:return t.data.tobytes() if t.data.dtype == np.uint8 else memoryview(t.data).cast("B").tobytes()raise KeyError(name)url, parsed = self._owner(name)dims, gtype, data_offset, n_bytes = parsed[2][name]start = parsed[1] + data_offsetreturn _fetch_bytes_progress(url, start, start + n_bytes - 1, name)def read_raw_slice(self, name, byte_off, byte_len):"""Minimal slice read: byte_off/byte_len relative to the tensor's raw bytes."""9 unmodified linesexcept Exception:return self.read_raw(name)[byte_off:byte_off + byte_len]raise KeyError(name)url, parsed = self._owner(name)dims, gtype, data_offset, n_bytes = parsed[2][name]start = parsed[1] + data_offset + byte_offraw, _st, _e = http_range(url, start, start + byte_len - 1, timeout=300)return raw16 unmodified linesreturn _source_from_repo(arg.strip().rstrip("/"), rev=rev)_GGUF_HIGH_TIER = 5 # F16 and above stops the searchdef _gguf_source_for_repo(repo, rev, files):"""Tensor-first GGUF selection. Triage files into candidate units (shardgroups + singles), probe headers in fidelity-hint order, census each unit(head + transformer body required), and return a source over the winningunit. First F16-tier-or-better head stops the search; every unit isprobed otherwise, so a valid model past any cutoff is still found.Nothing resolvable anywhere → the legacy pick is census-checked too, andfails loud instead of returning a blind (possibly headless) file."""groups, singles, dropped = _triage_gguf_files(files)if ctx.VERBOSE and dropped:_note(f"Skipping non-model GGUF files: {', '.join(dropped)}.")units = [("split", g) for g in groups] + [("single", [f]) for f in singles]units.sort(key=lambda u: _gguf_name_rank(u[1][0]), reverse=True)base = f"https://huggingface.co/{repo}/resolve/{rev}/"probed, checked = [], 0for _kind, paths in units:urls = [base + p for p in paths]try:parsed = [_parse_gguf_header(u) for u in urls]except SystemExit:raiseexcept Exception as e:if ctx.VERBOSE:_note(f"Skipping {paths[0]} (unreadable header: {type(e).__name__}).")continuechecked += 1union = {}for p in parsed:for k, v in p[2].items():union.setdefault(k, v)head, body = _gguf_unit_census(list(union.keys()))if not (head and body):if ctx.VERBOSE:_note(f"Skipping {paths[0]} (not a base model: "+ ("no head" if not head else "no transformer blocks") + ").")continuetry:from gguf.constants import GGMLQuantizationType as Qdrank = _gguf_dtype_rank(Q(union[head][1]).name)except Exception:drank = -1probed.append((drank, _gguf_name_rank(paths[0]), urls))if drank >= _GGUF_HIGH_TIER:breakif not probed:chosen = _pick_gguf(files)url = f"https://huggingface.co/{repo}/resolve/{rev}/{chosen}"try:parsed = _parse_gguf_header(url)head, body = _gguf_unit_census(list(parsed[2].keys()))except SystemExit:raiseexcept Exception:head, body = None, Falseif head and body:return GgufSource(url=url, rev=rev)_fail(f" ✗ No base model found in '{repo}' ({checked} file(s) checked, none with an output head).")probed.sort(key=lambda t: (t[0], t[1]), reverse=True)best = probed[0][2]if len(best) == 1:_step(f"Using {best[0].rsplit('/', 1)[-1]}")else:_step(f"Using {len(best)} files ({best[0].rsplit('/', 1)[-1]}…)")if len(best) == 1:return GgufSource(url=best[0], rev=rev)return GgufSource(urls=best, rev=rev)def _source_from_repo(repo, rev=None):rev = rev or "main"try:1 unmodified linefiles = [f.get("path", "") for f in tree if f.get("path")]ggufs = [f for f in files if f.endswith(".gguf")]if ggufs:return _gguf_source_for_repo(repo, rev, ggufs)if any(f.endswith(".safetensors") for f in files):return SafetensorsSource(repo=repo, rev=rev)if files:6 unmodified linesdef _pick_gguf(files):"""Legacy single-file fallback (pre-tensor-first behavior). Kept for thenothing-resolvable path and external imports; new code goes through_gguf_source_for_repo."""files = sorted(files)for key in ("fp16", "f16", "q8_0"):for f in files:
123version https://git-lfs.github.com/spec/v1oid sha256:8ebae7075d10181b2d6a5a640d8b064358dc3cbdac34a46f91444c00f01c2abfsize 70556123version https://git-lfs.github.com/spec/v1oid sha256:5ca5bc2a43c946a288c15ebdcb2daa96611936369035acafcf49ba194ffe0240size 74056
45 unmodified lines4647484950515245 unmodified linesfrom 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_targetsfrom 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_tmpfrom 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_gguffrom 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_namefrom vlib.fetch import _source_arch, _resolve_output_name, _stream_safetensors_tensor, _fetch_tensor, _stream_gguf_tensor, _fetch_pack, _write_fetched, _write_voicepack_jsonfrom 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_overwritefrom 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_want45 unmodified lines4647484950515245 unmodified linesfrom 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_targetsfrom 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_tmpfrom 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_gguffrom 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_repofrom vlib.fetch import _source_arch, _resolve_output_name, _stream_safetensors_tensor, _fetch_tensor, _stream_gguf_tensor, _fetch_pack, _write_fetched, _write_voicepack_jsonfrom 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_overwritefrom 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
123version https://git-lfs.github.com/spec/v1oid sha256:7568525f51fe2bbebeec82b6dd709bb3fb62f798e52485c0cf63290a7f5e4cecsize 260239123version https://git-lfs.github.com/spec/v1oid sha256:1ce6f50700978bd60d88a4dcca8519a99b18e9f1650cebe9e9a73b5d7859a928size 269992
tests/test_units.py+159-1
vlib/cache.py+6-2
vlib/cmds_voices.py+4-1
vlib/delta.py+2-2
vlib/fetch.py+4-3
vlib/net.py+23
vlib/registry.py+2-1
vlib/sources.py+231-23
voice-cli.tar.gz+2-2
voice.py+1-1
voice.pyz+2-2