Skip to content

Open-source State-of-the-art TTS model which runs on a CPU 😻

Python

Load emb4 weights without expanding the whole model in host memory

haaziq-sl4168e23b777d
diff --git a/kittenml/kittentts2/tl2_emb4.py b/kittenml/kittentts2/tl2_emb4.py
index 9c31aea..bdc29a1 100644
--- a/kittenml/kittentts2/tl2_emb4.py
+++ b/kittenml/kittentts2/tl2_emb4.py
@@ -46,6 +46,9 @@ def unpack_tl2(buf, out_features, in_features):
if buf.shape != (rows, groups, TL2_GROUP_BYTES):
raise ValueError(f"expected {(rows, groups, TL2_GROUP_BYTES)}, got {buf.shape}")
+ # The result is allocated before the temporaries, so the memory they free can
+ # be reused by the next tensor rather than left as gaps between results.
+ weight = torch.empty(out_features, groups, GROUP, dtype=torch.bfloat16)
gamma = buf[:, :, :TL2_ROWS * 2].copy().view(np.float16).transpose(0, 2, 1)
trits = np.empty((rows, TL2_ROWS, groups, GROUP), dtype=np.int8)
cursor = TL2_ROWS * 2
@@ -83,7 +86,8 @@ def unpack_tl2(buf, out_features, in_features):
values = torch.from_numpy(trits.reshape(out_features, groups, GROUP)).to(torch.bfloat16)
scales = torch.from_numpy(
np.ascontiguousarray(gamma.reshape(out_features, groups))).to(torch.bfloat16)
- return (values * scales.unsqueeze(-1)).reshape(out_features, in_features)
+ torch.mul(values, scales.unsqueeze(-1), out=weight)
+ return weight.reshape(out_features, in_features)
def _hadamard(n):
@@ -105,7 +109,7 @@ def _unpack_codes(buf, codebook_size, count):
return out[:count].astype(np.int64)
-def dequant_embedding(get_tensor, metadata, chunk=1 << 15):
+def dequant_embedding(get_tensor, metadata, chunk=1 << 15, lookup_chunk=1 << 12):
"""4-bit codes -> a bf16 embedding matrix.
Rows are split into frequency tiers with their own codebook sizes — audio
@@ -118,43 +122,63 @@ def dequant_embedding(get_tensor, metadata, chunk=1 << 15):
tier_map = get_tensor("emb4/tier_map").numpy()
hadamard = _hadamard(dim)
- weights = torch.empty(vocab, dim, dtype=torch.float32)
+ # Decoding the whole table at once would hold every code as int64 and the
+ # matrix in float32, several GB for 158k x 2048. So codes are looked up
+ # `lookup_chunk` rows at a time and the result goes straight into bf16; the
+ # rotation is still one matrix multiply per `chunk` rows, because a CPU
+ # library can round the last bit differently for a different matrix size.
+ weights = torch.empty(vocab, dim, dtype=torch.bfloat16)
for tier, codebook_size in enumerate(codebook_sizes):
rows = np.flatnonzero(tier_map == tier) # ascending == packing order
- codes = _unpack_codes(get_tensor(f"emb4/t{tier}_codes").numpy(),
- codebook_size, rows.size * dim).reshape(rows.size, dim)
+ packed = get_tensor(f"emb4/t{tier}_codes").numpy()
+ per_byte = 8 // int(math.ceil(math.log2(codebook_size)))
centres = get_tensor(f"emb4/t{tier}_centers").to(torch.float32).numpy()
- row_scale = get_tensor(f"emb4/t{tier}_s").to(torch.float32).numpy()
+ row_scale = torch.from_numpy(get_tensor(f"emb4/t{tier}_s").to(torch.float32).numpy())
col_scale = torch.from_numpy(
get_tensor(f"emb4/t{tier}_t").to(torch.float32).numpy())
- centres_t = np.ascontiguousarray(centres.T)
- # Chunked: the full rotation would otherwise materialise 158k x 2048 floats.
+ rotated = np.empty((min(chunk, rows.size), dim), dtype=np.float32)
for start in range(0, rows.size, chunk):
stop = min(start + chunk, rows.size)
- rotated = np.take_along_axis(centres_t, codes[start:stop].T, axis=1).T
- restored = torch.from_numpy(np.ascontiguousarray(rotated)) @ hadamard.T
- weights[rows[start:stop]] = (restored * col_scale[None, :]
- * torch.from_numpy(row_scale[start:stop])[:, None])
- return weights.to(torch.bfloat16)
-
-
-def load_state_dict(path):
- """Rebuild the full bf16 state dict from a TL2 + emb4 checkpoint."""
+ for low in range(start, stop, lookup_chunk):
+ high = min(low + lookup_chunk, stop)
+ # A byte can hold codes from more than one row: start at this row's first.
+ first, skip = divmod(low * dim, per_byte)
+ codes = _unpack_codes(packed[first:-(-high * dim // per_byte)], codebook_size,
+ skip + (high - low) * dim)[skip:].reshape(-1, dim)
+ rotated[low - start:high - start] = np.take_along_axis(centres, codes, axis=0)
+ restored = torch.from_numpy(rotated[:stop - start]) @ hadamard.T
+ restored.mul_(col_scale[None, :]).mul_(row_scale[start:stop, None])
+ weights[rows[start:stop]] = restored.to(torch.bfloat16)
+ return weights
+
+
+def iter_state_dict(path, include=None):
+ """Yield the bf16 (name, tensor) pairs of a TL2 + emb4 checkpoint, one at a time.
+
+ `include`, if given, is a predicate on tensor names: the others are skipped
+ without being unpacked, so a caller that needs a few tensors, or loads them
+ one by one, never holds the expanded model in host memory.
+ """
from safetensors import safe_open
- state = {}
+ wanted = include or (lambda name: True)
with safe_open(str(path), framework="pt") as handle:
metadata = dict(handle.metadata() or {})
if metadata.get("schema") != "kitten_ternary_tl2_emb4_v1":
raise ValueError(f"unexpected schema {metadata.get('schema')!r} in {path}")
embedding_metadata = json.loads(metadata.get("embedding_metadata", "{}"))
for key in handle.keys():
- if key.startswith("tl2/"):
+ if key.startswith("tl2/") and wanted(key[4:]):
buf = handle.get_tensor(key).numpy()
rows, groups, _ = buf.shape
- state[key[4:]] = unpack_tl2(buf, rows * TL2_ROWS, groups * GROUP)
- elif key.startswith("fp/"):
- state[key[3:]] = handle.get_tensor(key)
- state["model.embed_tokens.weight"] = dequant_embedding(
- handle.get_tensor, embedding_metadata)
- return state
+ yield key[4:], unpack_tl2(buf, rows * TL2_ROWS, groups * GROUP)
+ elif key.startswith("fp/") and wanted(key[3:]):
+ yield key[3:], handle.get_tensor(key)
+ if wanted("model.embed_tokens.weight"):
+ yield "model.embed_tokens.weight", dequant_embedding(
+ handle.get_tensor, embedding_metadata)
+
+
+def load_state_dict(path, include=None):
+ """The bf16 state dict, or the tensors `include` selects, of a TL2 + emb4 checkpoint."""
+ return dict(iter_state_dict(path, include))
diff --git a/kittenml/kittentts2/vllm/loader.py b/kittenml/kittentts2/vllm/loader.py
index 3e8ecba..dac411f 100644
--- a/kittenml/kittentts2/vllm/loader.py
+++ b/kittenml/kittentts2/vllm/loader.py
@@ -2,7 +2,7 @@
from vllm.model_executor.model_loader.base_loader import BaseModelLoader
-from ..weights import load_lm_weights
+from ..weights import iter_lm_weights
class KittenModelLoader(BaseModelLoader):
@@ -24,8 +24,8 @@ class KittenModelLoader(BaseModelLoader):
from .w4a16 import iter_w4a16
weights = iter_w4a16(options["repo_dir"], options["config"], options["weights"])
elif quantization is None:
- state = load_lm_weights(options["repo_dir"], options["config"], options["weights"])
- weights = ((name, tensor) for name, tensor in state.items()
+ state = iter_lm_weights(options["repo_dir"], options["config"], options["weights"])
+ weights = ((name, tensor) for name, tensor in state
if not name.startswith("spk_proj."))
else:
raise ValueError(f"unknown KittenTTS quantization {quantization!r}")
diff --git a/kittenml/kittentts2/vllm/w4a16.py b/kittenml/kittentts2/vllm/w4a16.py
index fe81ad2..984e76f 100644
--- a/kittenml/kittentts2/vllm/w4a16.py
+++ b/kittenml/kittentts2/vllm/w4a16.py
@@ -13,8 +13,9 @@ another kernel or 8-bit activations). Everything that is not ternary stays at
its stored precision: the token embedding and the tied output head, all norms,
and the KV cache. ``spk_proj`` runs outside vLLM and is dropped here.
-The lossy ``emb4`` packing is refused: W4A16 is offered as an exact
-representation of the published weights and is never combined with it.
+With the lossy ``emb4`` packing the projections are still exact (its TL2 body
+holds the same trits); only its 4-bit embedding, and so the tied output head,
+differs from the published bf16 model.
In the opt-in float16 mode (fp16.py) the same codes are used; the group scales
of v/o/up/down are multiplied by that mode's powers of two and stored in
@@ -174,10 +175,9 @@ def _iter_packed(path):
def _iter_emb4(repo_dir, config):
- from ..weights import load_lm_weights
+ from ..weights import iter_lm_weights
- state = load_lm_weights(repo_dir, config, "emb4")
- for name, tensor in state.items():
+ for name, tensor in iter_lm_weights(repo_dir, config, "emb4"):
if name.startswith("spk_proj."):
continue
if is_projection(name):
diff --git a/kittenml/kittentts2/weights.py b/kittenml/kittentts2/weights.py
index 77f2242..0ba20db 100644
--- a/kittenml/kittentts2/weights.py
+++ b/kittenml/kittentts2/weights.py
@@ -32,8 +32,7 @@ def load_lm_weights(repo_dir, config, variant, lm_dir=None, include=None):
`include`, if given, is a predicate on tensor names: only those tensors are
read (and, for packed files, unpacked), so callers that need a few tensors
- do not expand the whole model in host memory. The emb4 reader always
- decodes the full file and filters afterwards.
+ do not expand the whole model in host memory.
"""
from safetensors import safe_open
from safetensors.torch import load_file
@@ -44,8 +43,7 @@ def load_lm_weights(repo_dir, config, variant, lm_dir=None, include=None):
raise FileNotFoundError(f"{variant!r} weights not found: {path}")
if variant == "emb4":
from .tl2_emb4 import load_state_dict
- state = load_state_dict(path)
- return state if include is None else {k: v for k, v in state.items() if include(k)}
+ return load_state_dict(path, include)
with safe_open(str(path), framework="pt") as handle:
metadata = handle.metadata() or {}
if include is None:
@@ -71,3 +69,14 @@ def load_lm_weights(repo_dir, config, variant, lm_dir=None, include=None):
if not shards or (include is None and not state):
raise FileNotFoundError(f"no plain model weights in {lm_dir}")
return state
+
+
+def iter_lm_weights(repo_dir, config, variant):
+ """load_lm_weights as (name, tensor) pairs; the emb4 reader yields them one at a time."""
+ if variant == "emb4":
+ path = weights_path(repo_dir, config, variant)
+ if not path.is_file():
+ raise FileNotFoundError(f"{variant!r} weights not found: {path}")
+ from .tl2_emb4 import iter_state_dict
+ return iter_state_dict(path)
+ return iter(load_lm_weights(repo_dir, config, variant).items())
diff --git a/tests/test_vllm.py b/tests/test_vllm.py
index f116f6e..cb50d55 100644
--- a/tests/test_vllm.py
+++ b/tests/test_vllm.py
@@ -1,5 +1,6 @@
"""Small checkpoints and sampler parity; no GPU or model download required."""
+import json
from dataclasses import asdict
from types import SimpleNamespace
from unittest import mock
@@ -114,6 +115,97 @@ def test_emb4_unpacking_is_independent_of_vllm_default_dtype():
assert actual.dtype == torch.bfloat16 and torch.equal(actual, expected)
+def _emb4_tensors(vocab=37, dim=16, seed=0):
+ """A three-tier emb4 table (8-bit and two 4-bit books) and its full-matrix decode.
+
+ Small integer centres, power-of-two scales and dim=16 (Hadamard entries ±1/4)
+ keep every product and sum exact, so the expected matrix does not depend on
+ how a matrix multiply orders its additions.
+ """
+ import math
+ generator = torch.Generator().manual_seed(seed)
+ sizes = [256, 16, 16]
+ tier_map = torch.randint(0, len(sizes), (vocab,), generator=generator).to(torch.uint8)
+ tensors = {"emb4/tier_map": tier_map}
+ hadamard = torch.tensor([[1.0]])
+ for _ in range(int(math.log2(dim))):
+ hadamard = torch.cat([torch.cat([hadamard, hadamard], 1),
+ torch.cat([hadamard, -hadamard], 1)], 0)
+ hadamard /= math.sqrt(dim)
+ expected = torch.empty(vocab, dim)
+ for tier, size in enumerate(sizes):
+ rows = torch.nonzero(tier_map == tier).flatten()
+ codes = torch.randint(0, size, (rows.numel(), dim), generator=generator)
+ flat = codes.flatten().to(torch.uint8)
+ if size == 16:
+ flat = flat[0::2] | (flat[1::2] << 4)
+ centres = torch.randint(-8, 9, (size, dim), generator=generator).to(torch.float16)
+ row_scale = 2.0 ** torch.randint(-3, 3, (rows.numel(),), generator=generator)
+ col_scale = 2.0 ** torch.randint(-3, 3, (dim,), generator=generator)
+ tensors.update({f"emb4/t{tier}_codes": flat, f"emb4/t{tier}_centers": centres,
+ f"emb4/t{tier}_s": row_scale.to(torch.float16),
+ f"emb4/t{tier}_t": col_scale.to(torch.float16)})
+ rotated = torch.gather(centres.float().T, 1, codes.T).T
+ expected[rows] = (rotated @ hadamard.T) * col_scale[None, :] * row_scale[:, None]
+ metadata = {"V": str(vocab), "D": str(dim), "Ks": json.dumps(sizes)}
+ return tensors, metadata, expected.to(torch.bfloat16)
+
+
[email protected]("chunk, lookup_chunk", [(1, 1), (5, 2), (8, 3), (1 << 15, 1 << 12)])
+def test_emb4_embedding_is_the_same_decoded_in_chunks(chunk, lookup_chunk):
+ from kittenml.kittentts2.tl2_emb4 import dequant_embedding
+ tensors, metadata, expected = _emb4_tensors()
+ actual = dequant_embedding(tensors.__getitem__, metadata, chunk=chunk,
+ lookup_chunk=lookup_chunk)
+ assert actual.dtype == torch.bfloat16 and torch.equal(actual, expected)
+
+
+def _write_emb4_checkpoint(path):
+ tensors, metadata, embedding = _emb4_tensors()
+ # One TL2 block (32 output rows x 128 inputs): random trits, finite group scales.
+ tl2 = torch.randint(0, 256, (1, 1, 928), dtype=torch.uint8)
+ tl2[..., :64] = (torch.rand(32) + 0.5).to(torch.float16).view(torch.uint8)
+ tensors = {**tensors,
+ "tl2/model.layers.0.self_attn.o_proj.weight": tl2,
+ "fp/model.norm.weight": torch.rand(16, dtype=torch.bfloat16),
+ "fp/spk_proj.0.weight": torch.rand(16, 4, dtype=torch.bfloat16)}
+ path.parent.mkdir(parents=True, exist_ok=True)
+ save_file(tensors, path, metadata={"schema": "kitten_ternary_tl2_emb4_v1",
+ "embedding_metadata": json.dumps(metadata)})
+ return embedding
+
+
+def test_emb4_reader_unpacks_only_the_tensors_asked_for(tmp_path):
+ from kittenml.kittentts2 import tl2_emb4
+ from kittenml.kittentts2.weights import iter_lm_weights
+
+ config = {"lm_emb4": "lm/model-tl2-emb4.safetensors"}
+ embedding = _write_emb4_checkpoint(tmp_path / config["lm_emb4"])
+ full = load_lm_weights(tmp_path, config, "emb4")
+ assert set(full) == {"model.layers.0.self_attn.o_proj.weight", "model.norm.weight",
+ "spk_proj.0.weight", "model.embed_tokens.weight"}
+ assert full["model.layers.0.self_attn.o_proj.weight"].shape == (32, 128)
+ assert torch.equal(full["model.embed_tokens.weight"], embedding)
+
+ # The main process asks for the speaker head only (and the embedding): nothing
+ # else may be unpacked.
+ with mock.patch.object(tl2_emb4, "unpack_tl2", side_effect=AssertionError), \
+ mock.patch.object(tl2_emb4, "dequant_embedding", side_effect=AssertionError):
+ head = load_lm_weights(tmp_path, config, "emb4",
+ include=lambda name: name.startswith("spk_proj."))
+ assert list(head) == ["spk_proj.0.weight"]
+ assert torch.equal(head["spk_proj.0.weight"], full["spk_proj.0.weight"])
+
+ # The engine side gets the same tensors one at a time, not a dict.
+ streamed = iter_lm_weights(tmp_path, config, "emb4")
+ assert not isinstance(streamed, dict)
+ streamed = dict(streamed)
+ assert set(streamed) == set(full)
+ assert all(torch.equal(streamed[name], full[name]) for name in full)
+ with pytest.raises(FileNotFoundError):
+ iter_lm_weights(tmp_path, {"lm_emb4": "lm/missing.safetensors"}, "emb4")
+
+
def test_optional_backend_errors_before_model_download():
resolved = (None, "example/repo", {"type": "KITTEN2"})
with mock.patch("kittenml.get_model.resolve_repo", return_value=resolved), \
@@ -230,10 +322,10 @@ def test_vllm_loader_filters_speaker_weights_and_rejects_missing_parameters():
model = TinyModel()
state = {"model.weight": torch.ones(2), "spk_proj.0.bias": torch.zeros(2)}
- with mock.patch("kittenml.kittentts2.vllm.loader.load_lm_weights", return_value=state):
+ with mock.patch("kittenml.kittentts2.vllm.loader.iter_lm_weights", return_value=state.items()):
loader.load_weights(model, None)
assert set(model.loaded) == {"model.weight"}
- with mock.patch("kittenml.kittentts2.vllm.loader.load_lm_weights", return_value={}):
+ with mock.patch("kittenml.kittentts2.vllm.loader.iter_lm_weights", return_value={}.items()):
with pytest.raises(ValueError, match="missing from the checkpoint"):
loader.load_weights(model, None)
@@ -450,7 +542,8 @@ def test_w4a16_accepts_emb4_and_packs_its_ternary_body_exactly(tmp_path):
state = {"model.layers.0.self_attn.o_proj.weight": weight,
"model.embed_tokens.weight": embedding,
"spk_proj.weight": torch.zeros(2, 2, dtype=torch.bfloat16)}
- with mock.patch("kittenml.kittentts2.weights.load_lm_weights", return_value=state) as load:
+ with mock.patch("kittenml.kittentts2.weights.iter_lm_weights",
+ return_value=iter(state.items())) as load:
out = dict(w4a16.iter_w4a16(tmp_path, {"lm_emb4": "x"}, "emb4"))
load.assert_called_once_with(tmp_path, {"lm_emb4": "x"}, "emb4")
assert "spk_proj.weight" not in out
@@ -1099,7 +1192,7 @@ def test_vllm_loader_float16_rescales_weights_and_residual_norm_epsilon_only():
state = {"model.embed_tokens.weight": embedding, "spk_proj.0.bias": torch.zeros(2),
"model.layers.0.mlp.up_proj.weight": torch.full((2, 2), 0.5, dtype=torch.bfloat16)}
model = _float16_engine_model()
- with mock.patch("kittenml.kittentts2.vllm.loader.load_lm_weights", return_value=state):
+ with mock.patch("kittenml.kittentts2.vllm.loader.iter_lm_weights", return_value=state.items()):
loader.load_weights(model, fp16_config)
assert set(model.loaded) == {"model.embed_tokens.weight", "lm_head.weight",
"model.layers.0.mlp.up_proj.weight"}
@@ -1140,7 +1233,8 @@ def test_vllm_loader_bfloat16_paths_hand_over_the_checkpoint_tensors_untouched()
model.proj = _linear_with_kernel(MarlinLinearKernel)
tensors = {"model.embed_tokens.weight": torch.full((4, 2), 0.03, dtype=torch.bfloat16),
"model.layers.0.mlp.up_proj.weight": torch.ones(2, 2, dtype=torch.bfloat16)}
- with mock.patch("kittenml.kittentts2.vllm.loader.load_lm_weights", return_value=tensors), \
+ with mock.patch("kittenml.kittentts2.vllm.loader.iter_lm_weights",
+ return_value=tensors.items()), \
mock.patch("kittenml.kittentts2.vllm.w4a16.iter_w4a16",
return_value=iter(tensors.items())):
loader.load_weights(model, bf16)