Skip to content

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

Python

Add an MLX backend for KittenTTS 2 on Apple silicon

Test4cf61e4f388f
diff --git a/README.md b/README.md
index 0667e9a..62fa529 100644
--- a/README.md
+++ b/README.md
@@ -37,6 +37,7 @@ The library also ships the original [**lightweight legacy models**](docs/onnx-mo
- [Voice cloning](#voice-cloning)
- [Expression controls](#expression-controls)
- [Running on CPU](#running-on-cpu)
+- [Running on a Mac](#running-on-a-mac)
- [Running with vLLM](#running-with-vllm)
- [Long text and streaming](#long-text-and-streaming)
- [Documentation](#documentation)
@@ -58,6 +59,7 @@ The library also ships the original [**lightweight legacy models**](docs/onnx-mo
- **Runs without a GPU**
- **Runs real time on a CPU** -- Check [Running on CPU](#running-on-cpu)
- **Optimized C++ inference for CPU** -- Our fork of [llama.cpp](https://github.com/KittenML/kitten-tts-2-cpp)
+- **Several times realtime on Apple silicon** -- Check [Running on a Mac](#running-on-a-mac)
@@ -211,6 +213,37 @@ print(model.last_report) # Generation timings and token IDs.
> Kitten-TTS 2 C++ is in beta. Please report any issues you encounter.
+## Running on a Mac
+
+On an Apple-silicon Mac, install the optional MLX backend and select it:
+
+```bash
+pip install "kittenml[mlx]"
+```
+
+```python
+from kittenml import KittenTTS
+
+m = KittenTTS("KittenML/kitten-tts-2", backend="mlx")
+m.generate_to_file("One day, a little girl named Lily found a needle in her room.",
+ "hello.wav", voice="Bruno")
+```
+
+This runs the language model on the Mac's GPU through
+[MLX](https://github.com/ml-explore/mlx), and audio decoding on MPS. On an M4 Max
+it synthesizes at roughly **4.7-5.2x realtime**, where the default PyTorch backend
+on the same machine manages 0.4-0.6x β€” about a **9-13x speedup**, measured in
+[docs/mlx.md](docs/mlx.md).
+
+The speedup is not only the GPU. KittenTTS 2's linear weights are ternary, and
+MLX's 4-bit format can hold the three values a ternary weight takes *exactly*, so
+this backend reads them at 4 bits each instead of expanding them to bf16 first β€”
+a quarter of the bytes per token, and bit-for-bit the published weights. Voices,
+cloning, expression tags and streaming are unchanged. `backend="auto"` picks MLX
+here and PyTorch elsewhere.
+
+See the [MLX guide](docs/mlx.md) for benchmarks and the full details.
+
## Running with vLLM
For GPU inference with vLLM on Linux and an NVIDIA CUDA GPU, install the optional backend:
@@ -279,6 +312,7 @@ Two consequences worth knowing:
| [Text normalization](docs/text-normalization.md) | How written text becomes spoken text |
| [Architecture](docs/architecture.md) | What the model is, package layout, vendored components |
| [Lightweight ONNX models](docs/onnx-models.md) | The CPU models, 15M-80M parameters, and their API |
+| [MLX on Apple silicon](docs/mlx.md) | The optional Mac GPU backend, and why it is faster |
## System Requirements
diff --git a/docs/README.md b/docs/README.md
index 33d92ff..ae54417 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -7,6 +7,7 @@ Fuller detail than the [project README](../README.md), which covers getting star
| [api.md](api.md) | The KittenTTS 2 API: every argument to `generate`, streaming, and the advanced knobs |
| [voices-and-expression.md](voices-and-expression.md) | The 47 built-in voices, the emotion and vocal-event tags, the ten languages |
| [decoders.md](decoders.md) | How audio is decoded, and the smaller quantised decoders |
+| [mlx.md](mlx.md) | Optional Apple-silicon GPU inference with MLX |
| [vllm.md](vllm.md) | Optional NVIDIA GPU inference with vLLM |
| [text-normalization.md](text-normalization.md) | How written text becomes spoken text |
| [architecture.md](architecture.md) | What the model is, package layout, vendored components |
diff --git a/docs/api.md b/docs/api.md
index f0f6009..c2c8aee 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -10,12 +10,13 @@ Loads whichever model family the repository's `config.json` declares.
|---|---|---|---|
| `model_name` | `str` | -- | Hugging Face repo ID, or a path to a local repository directory |
| `cache_dir` | `str` | `None` | Local directory for caching downloaded files |
-| `device` | `str` | `None` | `"cuda"` or `"cpu"`; auto-detected when omitted. Note: this Python package is for demo only, and not optimized for speed. For real-time performance on CPU, please refer to our [optimized cpu inference repo](https://github.com/KittenML/kitten-tts-2-cpp). And for GPU, please refer to the vllm instructions below. |
+| `device` | `str` | `None` | `"cuda"`, `"mps"` or `"cpu"`; auto-detected when omitted. With `backend="mlx"` the language model always runs on the Mac GPU and this selects only where audio decoding runs, defaulting to `"mps"`. Note: this Python package is for demo only, and not optimized for speed. For real-time performance on CPU, please refer to our [optimized cpu inference repo](https://github.com/KittenML/kitten-tts-2-cpp). And for GPU, please refer to the vllm instructions below. |
| `hf_token` | `str` | `None` | Token, only for downloading a private model repository |
| `decoder` | `str` | repo default | Which decoder to load; see [decoders.md](decoders.md) |
| `weights` | `str` | `"packed"` | Which weight packing to load: `"packed"` (lossless), `"emb4"` (smaller, quantised embedding), `"full"` (bf16) |
-| `backend` | `str` | `None` | Default PyTorch inference, or `"vllm"` for optional NVIDIA GPU inference on Linux |
+| `backend` | `str` | `None` | Default PyTorch inference, `"mlx"` for the Apple-silicon GPU, `"vllm"` for optional NVIDIA GPU inference on Linux, or `"auto"` to pick MLX on a Mac and PyTorch elsewhere |
| `vllm_options` | `dict` | `None` | Engine memory and context settings; see [vLLM](vllm.md) |
+| `mlx_options` | `dict` | `None` | Reserved; the MLX backend currently takes no options. See [MLX](mlx.md) |
# `model.generate(text, voice=None, reference=None, ...)`
diff --git a/docs/architecture.md b/docs/architecture.md
index ca39c0d..0ee9844 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -21,13 +21,19 @@ kittenml/
tokens.py the shared text/audio token layout
vocoder.py reference encoding and token -> waveform
s3gen.py vendored S3 tokenizer + s3gen vocoder
+ mlx/ the optional Apple-silicon backend
+ loader.py ternary weights -> MLX's 4-bit kernels, exactly
+ model.py Qwen3 and the speaker head as MLX modules
+ sample.py the same decode pipeline, in MLX
kittentts_legacy/ the ONNX models
model.py KittenTTSOnnx: generate, speed control
onnx_model.py the ONNX session and phonemizer
```
Neither backend is imported until it is the one selected, so a KittenTTS 2 install never needs
-espeak and an ONNX install never needs torch.
+espeak and an ONNX install never needs torch. The same is true of the optional language-model
+backends under `kittentts2/`: `mlx/` is imported only for `backend="mlx"`, `vllm/` only for
+`backend="vllm"`.
# The model repository
diff --git a/docs/mlx.md b/docs/mlx.md
new file mode 100644
index 0000000..871515d
--- /dev/null
+++ b/docs/mlx.md
@@ -0,0 +1,108 @@
+# Running with MLX (Apple silicon)
+
+The optional `mlx` backend runs KittenTTS 2's language model on a Mac's GPU
+through [MLX](https://github.com/ml-explore/mlx). It is the fast way to run
+KittenTTS 2 on an Apple-silicon Mac: the default PyTorch backend runs the model
+on the CPU there, below realtime.
+
+```bash
+pip install "kittenml[mlx]"
+```
+
+```python
+from kittenml import KittenTTS
+
+m = KittenTTS("KittenML/kitten-tts-2", backend="mlx")
+m.generate_to_file("One day, a little girl named Lily found a needle in her room.",
+ "output.wav", voice="Bruno")
+```
+
+`backend="auto"` is the portable spelling: MLX on an Apple-silicon Mac with
+`mlx` installed, the PyTorch backend everywhere else. It never selects vLLM,
+which has memory settings of its own to choose.
+
+Voices, cloning, expression tags, decode presets, chunking and streaming are the
+existing implementations and behave identically. Only the language model moves.
+
+## Why it is faster
+
+Generating audio is one forward pass per 1/25 s of speech, each pass reading
+every weight once, so the model is bound by memory bandwidth rather than
+arithmetic. Two things change:
+
+- **The weights stay packed.** The published checkpoint's linear weights are
+ ternary β€” inside every 128-wide group each value is exactly one of
+ `{-scale, 0, +scale}` β€” and the repository ships them at 1.6 bits each. Both
+ other backends expand them to bf16 before the first token, spending 16 bits to
+ say one of three things. MLX's 4-bit quantised format can represent those three
+ values *exactly*, by taking its scale from the group and its zero point at
+ `-scale`, which puts `-scale`, `0` and `+scale` at codes 0, 1 and 2. So the
+ 1.4B ternary parameters are read as 4 bits each, and the weights being
+ multiplied are bit-for-bit the published ones. Nothing is rounded, and there is
+ no quantisation step at load time β€” the trits on disk already *are* the codes,
+ so loading is bit shuffling and takes about a second.
+- **It runs on the GPU.** Unified memory means the weights are not copied
+ anywhere to get there, and audio decoding runs on the same GPU through MPS.
+
+The result is roughly 1.4 GB read per token instead of 3.5 GB, at GPU bandwidth
+instead of CPU bandwidth.
+
+## What is and is not identical
+
+The weights are exact, and the decode pipeline β€” the run and repetition
+penalties, temperature, top-k, top-p, min-p, in that order β€” is a port of the
+same one, checked against it in `tests/test_mlx.py`.
+
+Generated audio is still not sample-identical to the PyTorch backend's, for the
+same reason two PyTorch runs with different attention kernels are not: the model
+computes in bfloat16, whose rounding depends on the order of operations. The
+logit differences are of the size bfloat16 rounding produces β€” the same size as
+between MLX in bfloat16 and MLX in float32 β€” and a seed therefore reproduces a
+generation within a backend, not across backends. Speaker similarity against the
+reference is unchanged.
+
+## Requirements and limits
+
+- An Apple-silicon Mac. `backend="mlx"` raises on Intel Macs and elsewhere.
+- `weights="packed"`, which is the default. `weights="emb4"` is a different
+ packing with a quantised embedding and is refused rather than silently
+ expanded; `weights="full"` is not the packed file this backend reads.
+- The first generation of a process also compiles the Metal kernels, which costs
+ about a second on top; the numbers below are steady state.
+- `device=` selects only where audio decoding, speaker embedding and
+ transcription run, since the language model is always on the GPU. It defaults
+ to `"mps"`, which decodes several times faster than the CPU. Pass
+ `device="cpu"` if a PyTorch build's MPS backend is missing an op s3gen needs.
+- One request at a time, like the PyTorch backend. Long text still uses
+ KittenTTS's sentence chunking, and `generate_stream` yields completed chunks.
+- Voice cloning without a supplied `reference_text` still loads Whisper through
+ transformers, which runs on the CPU.
+
+## Benchmarks
+
+Measured on an Apple M4 Max with 12 GB of memory, macOS 15.6, Python 3.13, PyTorch
+2.14.1 and MLX 0.32.4, using `weights="packed"`, the default decoder and the stable
+preset. These are median end-to-end synthesis times from five runs after one warmup
+per voice (three runs for PyTorch, which is slow enough that the medians were already
+stable). Short, medium and long inputs contain 61, 205 and 522 characters; the long
+input is split into two chunks. Model initialization and file writes are excluded.
+
+The two backends sample differently, so each produces a slightly different length of
+audio from the same text β€” hence the realtime factors rather than a bare time ratio.
+
+| Input / voice | PyTorch CPU | MLX | PyTorch | MLX | Speedup |
+|---|---:|---:|---:|---:|---:|
+| Short / Bruno | 9.23 s | 0.86 s | 0.41x realtime | 4.76x realtime | 11.6x |
+| Short / Bella | 13.06 s | 1.12 s | 0.39x realtime | 5.07x realtime | 13.0x |
+| Medium / Bruno | 23.45 s | 2.55 s | 0.53x realtime | 4.77x realtime | 9.0x |
+| Medium / Bella | 30.25 s | 3.31 s | 0.57x realtime | 5.21x realtime | 9.1x |
+| Long / Bruno | 54.98 s | 6.14 s | 0.54x realtime | 4.68x realtime | 8.7x |
+| Long / Bella | 71.21 s | 8.42 s | 0.55x realtime | 4.91x realtime | 8.9x |
+
+Of the 0.86 s short run, the language model takes about 0.68 s β€” roughly 150 tokens
+per second, against the codec's 25 tokens per second of speech β€” and audio decoding
+about 0.16 s. Decoding on the CPU instead (`device="cpu"`) costs about 1.0 s, which
+is why MPS is the default for it.
+
+This machine is a virtual machine, which costs some memory bandwidth; a Mac running
+the same model natively should be at least as fast.
diff --git a/example_mlx.py b/example_mlx.py
new file mode 100644
index 0000000..afd369c
--- /dev/null
+++ b/example_mlx.py
@@ -0,0 +1,32 @@
+"""KittenTTS 2 on an Apple-silicon Mac β€” the same API, on the GPU.
+
+ pip install "kittenml[mlx]"
+
+The language model runs through MLX with its ternary weights left packed, and
+audio decoding runs on MPS. Everything else β€” voices, cloning, expression tags,
+streaming β€” is unchanged; see the other examples.
+"""
+import time
+
+import soundfile as sf
+
+from kittenml import KittenTTS
+
+# backend="auto" is the portable spelling: MLX on an Apple-silicon Mac with mlx
+# installed, and the default PyTorch backend anywhere else.
+m = KittenTTS("KittenML/kitten-tts-2", backend="auto")
+print(f"backend: {m.backend}, audio decoding on: {m.device}")
+
+text = "One day, a little girl named Lily found a needle in her room."
+
+# The first generation also compiles the Metal kernels both backends need; time
+# the second to see the steady-state rate.
+m.generate(text, voice="Bruno")
+
+start = time.time()
+audio = m.generate(text, voice="Bruno")
+elapsed = time.time() - start
+seconds = len(audio) / m.sample_rate
+print(f"{seconds:.2f}s of audio in {elapsed:.2f}s -> {seconds / elapsed:.1f}x realtime")
+
+sf.write("output.wav", audio, m.sample_rate)
diff --git a/kittenml/get_model.py b/kittenml/get_model.py
index b76afa1..7f251dd 100644
--- a/kittenml/get_model.py
+++ b/kittenml/get_model.py
@@ -58,13 +58,14 @@ class KittenTTS(KittenTTSOnnx):
m = KittenTTS("KittenML/kitten-tts-mini-0.8") # ONNX, runs on CPU
m = KittenTTS("KittenML/kitten-tts-2") # KittenTTS 2, GPU optional
+ m = KittenTTS("KittenML/kitten-tts-2", backend="mlx") # on an Apple-silicon Mac
Both also accept a path to a local repository directory.
"""
def __new__(cls, model_name="KittenML/kitten-tts-nano-0.8", cache_dir=None,
backend=None, device=None, hf_token=None, decoder=None, weights=None,
- vllm_options=None):
+ vllm_options=None, mlx_options=None):
local_dir, repo_id, config = resolve_repo(model_name, cache_dir)
model_type = config.get("type")
@@ -75,6 +76,11 @@ class KittenTTS(KittenTTSOnnx):
validate_environment(device)
elif vllm_options is not None:
raise ValueError("vllm_options requires backend='vllm'")
+ if backend == "mlx":
+ from .kittentts2.mlx.backend import validate_environment
+ validate_environment(device)
+ elif mlx_options is not None:
+ raise ValueError("mlx_options requires backend='mlx'")
if local_dir is None:
local_dir = snapshot_download(
repo_id=repo_id, cache_dir=cache_dir, token=hf_token,
@@ -82,7 +88,8 @@ class KittenTTS(KittenTTSOnnx):
# Returning a different class means __init__ below is never called.
return KittenTTS2(local_dir, config, device=device, cache_dir=cache_dir,
hf_token=hf_token, decoder=decoder, weights=weights,
- backend=backend, vllm_options=vllm_options)
+ backend=backend, vllm_options=vllm_options,
+ mlx_options=mlx_options)
if model_type not in ONNX_TYPES:
raise ValueError(
@@ -92,6 +99,9 @@ class KittenTTS(KittenTTSOnnx):
if backend == "vllm" or vllm_options is not None:
raise ValueError("the vLLM backend requires a KittenTTS 2 model")
+ if backend == "mlx" or mlx_options is not None:
+ raise ValueError("the MLX backend requires a KittenTTS 2 model")
+
instance = super().__new__(cls)
# Hand the already-resolved repository to KittenTTSOnnx.__init__ rather
# than making it hit the Hub a second time.
diff --git a/kittenml/kittentts2/mlx/__init__.py b/kittenml/kittentts2/mlx/__init__.py
new file mode 100644
index 0000000..4630e48
--- /dev/null
+++ b/kittenml/kittentts2/mlx/__init__.py
@@ -0,0 +1,9 @@
+"""The optional MLX backend: KittenTTS 2's language model on Apple-silicon GPU.
+
+Selected with `KittenTTS("KittenML/kitten-tts-2", backend="mlx")`. Nothing here
+is imported unless that backend is chosen, so `mlx` stays an optional dependency.
+"""
+
+from .backend import MLXBackend, validate_environment
+
+__all__ = ["MLXBackend", "validate_environment"]
diff --git a/kittenml/kittentts2/mlx/backend.py b/kittenml/kittentts2/mlx/backend.py
new file mode 100644
index 0000000..19a0ed8
--- /dev/null
+++ b/kittenml/kittentts2/mlx/backend.py
@@ -0,0 +1,121 @@
+"""Optional Apple-silicon language-model backend; waveform decoding stays in KittenTTS.
+
+KittenTTS 2 spends nearly all of its time in the language model, one token at a
+time, which makes it bound by how fast the weights can be read. On a Mac the
+default backend reads them as bf16 on the CPU. This one keeps them in the 4-bit
+form the published checkpoint already implies (see `loader.py`) and runs the
+model on the GPU through MLX, so each step reads a quarter of the bytes and reads
+them at GPU bandwidth. The weights are bit-for-bit the published ones and the
+sampling pipeline is the same, so this is the same model, not a smaller one.
+
+Audio decoding, voice cloning, text normalization and chunking are unchanged.
+"""
+
+import importlib.util
+import json
+import platform
+
+import numpy as np
+
+from .sample import build_logits_processors, sample
+
+
+def validate_environment(device=None):
+ """Fail early, and say what to install, rather than at the first generation."""
+ if platform.system() != "Darwin" or platform.machine() != "arm64":
+ raise RuntimeError("the MLX backend requires an Apple-silicon Mac")
+ if importlib.util.find_spec("mlx") is None:
+ raise ImportError('install the optional backend with pip install "kittenml[mlx]"')
+ if device is not None and str(device) not in ("mps", "cpu"):
+ raise ValueError(f"the MLX backend runs the language model on the Mac GPU; "
+ f"device={device!r} would only move audio decoding. Pass "
+ f"device='mps' or device='cpu' (or leave it unset).")
+
+
+class MLXBackend:
+ """The language model on Apple-silicon GPU, with its weights left packed."""
+
+ def __init__(self, owner, options=None):
+ validate_environment(owner.device)
+ import mlx.core as mx
+ from transformers import AutoTokenizer
+
+ from .loader import load_lm_weights
+ from .model import KittenLM
+
+ if options:
+ raise ValueError(f"unknown mlx_options: {sorted(options)}")
+ self.mx = mx
+ self.token_map = owner.token_map
+ self.stop_ids = {owner.token_map.speech_end_id, owner.token_map.stop_id}
+
+ lm_dir = owner.repo_dir / owner.config.get("lm_dir", "lm")
+ if owner.weights != "packed":
+ raise ValueError(
+ f"the MLX backend reads the packed ternary weights, not "
+ f"weights={owner.weights!r}: the packing is what lets it keep the "
+ f"ternary weights at 4 bits exactly. Use weights='packed'.")
+ path = owner._weights_path("packed")
+ if not path.is_file():
+ raise FileNotFoundError(f"packed weights not found: {path}")
+
+ self.dtype = mx.bfloat16 if owner.config.get("dtype", "bf16") == "bf16" else mx.float32
+ owner.tokenizer = AutoTokenizer.from_pretrained(str(lm_dir))
+ dense, quantised, group_size = load_lm_weights(path, dtype=self.dtype)
+ with open(lm_dir / "config.json") as handle:
+ config = json.load(handle)
+ self.model = KittenLM.from_config(
+ config, quantised, group_size,
+ spk_dim=owner.config.get("speaker_embedding_dim", 512)).load_dense(dense)
+ self.model.eval()
+ mx.eval(self.model)
+
+ def seed(self, seed):
+ """Seed MLX's global sampler state; KittenTTS 2 calls this per generation."""
+ self.mx.random.seed(int(seed))
+
+ def speaker_embedding(self, embedding):
+ """Project a speaker embedding once, instead of once per chunk.
+
+ Returns the hidden state that replaces the first position's token
+ embedding at prefill β€” the MLX counterpart of the Torch backend's
+ `spk_proj` forward hook.
+ """
+ projected = self.model.speaker_embedding(
+ self.mx.array(np.asarray(embedding, np.float32)))
+ self.mx.eval(projected)
+ return projected.reshape(1, 1, -1)
+
+ def generate_tokens(self, prompt, speaker_embedding, settings, max_new_tokens, advanced):
+ """Run the LM for one chunk and return its audio codec ids (0-based)."""
+ mx = self.mx
+ processors = build_logits_processors(
+ self.token_map,
+ temperature=settings["temperature"], top_k=settings["top_k"],
+ top_p=settings["top_p"], min_p=settings.get("min_p", 0.0),
+ repetition_penalty=advanced["repetition_penalty"],
+ repetition_window=advanced["repetition_window"],
+ token_run_penalty=advanced["token_run_penalty"],
+ token_run_grace=advanced["token_run_grace"],
+ prompt_length=len(prompt))
+
+ cache = self.model.new_cache()
+ embeddings = self.model.embed(prompt)
+ # Position 0 carries the speaker, exactly as in `speaker.attach_speaker_head`.
+ embeddings = mx.concatenate(
+ [speaker_embedding.astype(embeddings.dtype), embeddings[:, 1:]], axis=1)
+ history = mx.array(prompt, mx.int32)[None]
+ logits = self.model(embeddings, cache)
+
+ generated = []
+ for _ in range(int(max_new_tokens)):
+ token = sample(history, logits, processors)
+ value = int(token.item())
+ if value in self.stop_ids:
+ break
+ generated.append(value)
+ history = mx.concatenate([history, token[None].astype(mx.int32)], axis=1)
+ logits = self.model(self.model.embed([value]), cache)
+
+ low, high = self.token_map.audio_id_base, self.token_map.audio_id_end
+ return [t - low for t in generated if low <= t < high]
diff --git a/kittenml/kittentts2/mlx/loader.py b/kittenml/kittentts2/mlx/loader.py
new file mode 100644
index 0000000..08a1d42
--- /dev/null
+++ b/kittenml/kittentts2/mlx/loader.py
@@ -0,0 +1,85 @@
+"""The published ternary weights, loaded straight into MLX's 4-bit kernels.
+
+The checkpoint's linear weights are ternary: inside every 128-wide group each
+value is exactly one of {-scale, 0, +scale}, stored as five base-3 trits per byte
+(see `ternary.py`). MLX multiplies by a quantised weight as
+
+ w = scales * code + biases
+
+so a ternary group is representable *exactly* in MLX's 4-bit affine format by
+taking `scales = scale` and `biases = -scale`, which puts the three values the
+weight can take at codes 0, 1 and 2:
+
+ code 0 -> -scale code 1 -> 0 code 2 -> +scale
+
+The trits on disk already use that numbering β€” `ternary.py` writes `sign + 1` β€”
+so a trit *is* its MLX code and conversion is pure bit shuffling: unpack base-3,
+repack as nibbles. No dequantisation, no re-quantisation, nothing rounded. The
+weights MLX multiplies by are bit-for-bit the weights the published checkpoint
+holds, at 4 bits each instead of the 16 the unpacked tensor would need.
+
+`mx.quantize` is not usable here: it fits its own min/max affine grid, whose
+16 levels straddle zero for a symmetric tensor, so a ternary weight's exact zero
+would land between two codes.
+"""
+
+import json
+
+import mlx.core as mx
+
+# How `ternary.py` writes the codes: five base-3 digits in one byte, least
+# significant digit first.
+TRITS_PER_BYTE = 5
+_POWERS = [3 ** i for i in range(TRITS_PER_BYTE)]
+
+# How MLX reads 4-bit codes: eight nibbles per uint32 word, lowest nibble first.
+BITS = 4
+CODES_PER_WORD = 32 // BITS
+
+PACKED_FORMAT = "kittenml-ternary-1.58"
+# MLX's quantised kernels exist for these group widths only.
+MLX_GROUP_SIZES = (32, 64, 128)
+
+
+def load_lm_weights(path, dtype=mx.bfloat16):
+ """Read a packed ternary checkpoint as MLX tensors.
+
+ Returns `(dense, quantised, group_size)`, where `dense` holds the tensors the
+ checkpoint stores unpacked β€” the token embedding, the norms, the speaker head
+ β€” and `quantised` maps each ternary weight's name to the
+ `(codes, scales, biases)` triple `mx.quantized_matmul` takes.
+ """
+ tensors, metadata = mx.load(str(path), return_metadata=True)
+ if metadata.get("format") != PACKED_FORMAT:
+ raise ValueError(f"not a packed ternary checkpoint: {metadata.get('format')!r}. "
+ "The MLX backend needs the repository's packed weights "
+ "(weights='packed').")
+ group_size = int(metadata["group_size"])
+ if group_size not in MLX_GROUP_SIZES:
+ raise ValueError(f"the checkpoint is quantised in groups of {group_size}, and "
+ f"MLX's 4-bit kernels support {MLX_GROUP_SIZES}")
+
+ dense = {name: tensor.astype(dtype) if tensor.dtype != dtype else tensor
+ for name, tensor in tensors.items() if "::" not in name}
+ quantised = {}
+ for name, spec in json.loads(metadata["packed"]).items():
+ rows, columns = spec["shape"]
+ scales = tensors[f"{name}::scale"].astype(dtype)
+ codes = _to_mlx_codes(tensors[f"{name}::codes"], rows, columns)
+ quantised[name] = (codes, scales, -scales)
+ # One tensor at a time: the unpacked trits are eight times the size of the
+ # nibbles they become, and holding every layer's at once would cost more
+ # memory than loading the model unpacked in the first place.
+ mx.eval(quantised[name])
+ del tensors[f"{name}::codes"], tensors[f"{name}::scale"]
+ return dense, quantised, group_size
+
+
+def _to_mlx_codes(packed, rows, columns):
+ """Base-3 bytes -> the uint32 nibble words `mx.quantized_matmul` reads."""
+ powers = mx.array(_POWERS, mx.uint32)
+ trits = (packed.astype(mx.uint32).reshape(-1, 1) // powers) % 3
+ # The packing pads the final byte to a whole five trits; drop that tail.
+ trits = trits.reshape(-1)[:rows * columns].reshape(rows, -1, CODES_PER_WORD)
+ shifts = mx.arange(0, 32, BITS, dtype=mx.uint32)
+ return mx.sum(mx.left_shift(trits, shifts), axis=-1).astype(mx.uint32)
diff --git a/kittenml/kittentts2/mlx/model.py b/kittenml/kittentts2/mlx/model.py
new file mode 100644
index 0000000..5d59ab5
--- /dev/null
+++ b/kittenml/kittentts2/mlx/model.py
@@ -0,0 +1,253 @@
+"""The KittenTTS 2 language model as MLX modules.
+
+Qwen3 decoder-only transformer, written against MLX directly rather than run
+through transformers, for two reasons. The ternary weights stay packed: every
+linear is an `mx.quantized_matmul` over the 4-bit codes `loader.py` produces, so
+the 1.4B ternary parameters are read as 4 bits each instead of being expanded to
+bf16 first. And the speaker head is part of the module rather than a forward hook
+β€” KittenTTS 2 overwrites the first position's embedding with a projected speaker
+embedding, which here is just an argument.
+
+Only what this checkpoint uses is implemented: full attention on every layer, no
+sliding window, no rope scaling, tied embeddings. `from_config` rejects anything
+else rather than quietly ignoring it.
+"""
+
+import mlx.core as mx
+import mlx.nn as nn
+
+BITS = 4
+
+# Every linear in the checkpoint, and the only ones this architecture has.
+LINEARS = ("self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj",
+ "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj")
+
+
+class TernaryLinear(nn.Module):
+ """A ternary linear layer, multiplied in its packed 4-bit form.
+
+ `loader.py` explains why the 4 bits are exact rather than a quantisation of
+ the published weights.
+ """
+
+ def __init__(self, codes, scales, biases, group_size):
+ super().__init__()
+ self.weight, self.scales, self.biases = codes, scales, biases
+ self.group_size = group_size
+
+ def __call__(self, x):
+ return mx.quantized_matmul(x, self.weight, self.scales, self.biases,
+ transpose=True, group_size=self.group_size, bits=BITS)
+
+
+class Attention(nn.Module):
+ """Grouped-query attention with Qwen3's per-head q/k normalisation."""
+
+ def __init__(self, args, build):
+ super().__init__()
+ self.n_heads = args["num_attention_heads"]
+ self.n_kv_heads = args["num_key_value_heads"]
+ self.head_dim = args["head_dim"]
+ self.scale = self.head_dim ** -0.5
+ self.q_proj = build("self_attn.q_proj")
+ self.k_proj = build("self_attn.k_proj")
+ self.v_proj = build("self_attn.v_proj")
+ self.o_proj = build("self_attn.o_proj")
+ self.q_norm = nn.RMSNorm(self.head_dim, eps=args["rms_norm_eps"])
+ self.k_norm = nn.RMSNorm(self.head_dim, eps=args["rms_norm_eps"])
+ self.rope = nn.RoPE(self.head_dim, traditional=False, base=args["rope_theta"])
+
+ def __call__(self, x, mask, cache):
+ batch, length, _ = x.shape
+ queries = self.q_norm(self.q_proj(x).reshape(batch, length, self.n_heads, -1))
+ keys = self.k_norm(self.k_proj(x).reshape(batch, length, self.n_kv_heads, -1))
+ values = self.v_proj(x).reshape(batch, length, self.n_kv_heads, -1)
+ queries, keys, values = (t.transpose(0, 2, 1, 3) for t in (queries, keys, values))
+
+ offset = cache.offset
+ queries = self.rope(queries, offset=offset)
+ keys = self.rope(keys, offset=offset)
+ keys, values = cache.update_and_fetch(keys, values)
+
+ out = mx.fast.scaled_dot_product_attention(queries, keys, values,
+ scale=self.scale, mask=mask)
+ return self.o_proj(out.transpose(0, 2, 1, 3).reshape(batch, length, -1))
+
+
+class MLP(nn.Module):
+ def __init__(self, build):
+ super().__init__()
+ self.gate_proj = build("mlp.gate_proj")
+ self.up_proj = build("mlp.up_proj")
+ self.down_proj = build("mlp.down_proj")
+
+ def __call__(self, x):
+ return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x))
+
+
+class Layer(nn.Module):
+ def __init__(self, args, build):
+ super().__init__()
+ self.self_attn = Attention(args, build)
+ self.mlp = MLP(build)
+ self.input_layernorm = nn.RMSNorm(args["hidden_size"], eps=args["rms_norm_eps"])
+ self.post_attention_layernorm = nn.RMSNorm(args["hidden_size"],
+ eps=args["rms_norm_eps"])
+
+ def __call__(self, x, mask, cache):
+ x = x + self.self_attn(self.input_layernorm(x), mask, cache)
+ return x + self.mlp(self.post_attention_layernorm(x))
+
+
+class SpeakerHead(nn.Module):
+ """The checkpoint's `spk_proj`: a linear projection and a layer norm.
+
+ Mirrors the `nn.Sequential(nn.Linear(...), nn.LayerNorm(...))` the Torch
+ backend builds, so the checkpoint's `spk_proj.0.*` and `spk_proj.1.*` map
+ across unchanged.
+ """
+
+ def __init__(self, spk_dim, hidden):
+ super().__init__()
+ self.proj = nn.Linear(spk_dim, hidden, bias=True)
+ self.norm = nn.LayerNorm(hidden)
+
+ def __call__(self, embedding):
+ return self.norm(self.proj(embedding))
+
+
+class KittenLM(nn.Module):
+ """Qwen3 with KittenTTS 2's speaker head, over packed ternary weights."""
+
+ def __init__(self, args, quantised, group_size, spk_dim):
+ super().__init__()
+ self.args = args
+ self.n_layers = args["num_hidden_layers"]
+ self.n_kv_heads = args["num_key_value_heads"]
+ self.head_dim = args["head_dim"]
+
+ def builder(index):
+ def build(name):
+ key = f"model.layers.{index}.{name}.weight"
+ if key not in quantised:
+ raise ValueError(f"{key} is not ternary in this checkpoint; the MLX "
+ "backend expects every linear to be packed")
+ return TernaryLinear(*quantised[key], group_size)
+ return build
+
+ self.layers = [Layer(args, builder(i)) for i in range(self.n_layers)]
+ unused = set(quantised) - {f"model.layers.{i}.{name}.weight"
+ for i in range(self.n_layers)
+ for name in LINEARS}
+ if unused:
+ raise ValueError(f"the checkpoint packs weights this architecture has no "
+ f"place for: {sorted(unused)[:5]}")
+ self.norm = nn.RMSNorm(args["hidden_size"], eps=args["rms_norm_eps"])
+ self.embed_tokens = nn.Embedding(args["vocab_size"], args["hidden_size"])
+ self.spk_proj = SpeakerHead(spk_dim, args["hidden_size"])
+
+ @classmethod
+ def from_config(cls, config, quantised, group_size, spk_dim):
+ """Build from the architecture `lm/config.json` declares."""
+ if config.get("model_type") != "qwen3":
+ raise ValueError(f"the MLX backend supports qwen3 KittenTTS 2 checkpoints, "
+ f"not {config.get('model_type')!r}")
+ for key, expected in (("rope_scaling", None), ("sliding_window", None),
+ ("use_sliding_window", False), ("attention_bias", False),
+ ("tie_word_embeddings", True)):
+ if config.get(key, expected) != expected:
+ raise ValueError(f"the MLX backend does not implement {key}="
+ f"{config.get(key)!r}")
+ args = {key: config[key] for key in (
+ "hidden_size", "num_hidden_layers", "num_attention_heads",
+ "num_key_value_heads", "head_dim", "rms_norm_eps", "rope_theta",
+ "vocab_size")}
+ return cls(args, quantised, group_size, spk_dim)
+
+ def load_dense(self, dense):
+ """Install the tensors the checkpoint does not pack.
+
+ The names are the checkpoint's own, so a renamed or truncated checkpoint
+ fails here rather than running on freshly initialised norms.
+ """
+ tree = {"embed_tokens": {"weight": dense["model.embed_tokens.weight"]},
+ "norm": {"weight": dense["model.norm.weight"]},
+ "spk_proj": {"proj": {"weight": dense["spk_proj.0.weight"],
+ "bias": dense["spk_proj.0.bias"]},
+ "norm": {"weight": dense["spk_proj.1.weight"],
+ "bias": dense["spk_proj.1.bias"]}},
+ "layers": [
+ {"input_layernorm": {"weight": dense[f"model.layers.{i}.input_layernorm.weight"]},
+ "post_attention_layernorm": {
+ "weight": dense[f"model.layers.{i}.post_attention_layernorm.weight"]},
+ "self_attn": {
+ "q_norm": {"weight": dense[f"model.layers.{i}.self_attn.q_norm.weight"]},
+ "k_norm": {"weight": dense[f"model.layers.{i}.self_attn.k_norm.weight"]}}}
+ for i in range(self.n_layers)]}
+ self.update(tree)
+ installed = {"model.embed_tokens.weight", "model.norm.weight"}
+ installed |= {f"spk_proj.{i}.{kind}" for i in (0, 1) for kind in ("weight", "bias")}
+ installed |= {f"model.layers.{i}.{name}.weight" for i in range(self.n_layers)
+ for name in ("input_layernorm", "post_attention_layernorm",
+ "self_attn.q_norm", "self_attn.k_norm")}
+ left_over = set(dense) - installed
+ if left_over:
+ raise ValueError(f"the checkpoint holds unpacked weights this architecture "
+ f"has no place for: {sorted(left_over)[:5]}")
+ return self
+
+ def embed(self, ids):
+ """Token ids -> input embeddings, as a (1, len, hidden) batch."""
+ return self.embed_tokens(mx.array(ids, mx.uint32)[None])
+
+ def speaker_embedding(self, embedding):
+ """A 512-dim speaker embedding -> the hidden state it occupies at prefill."""
+ return self.spk_proj(embedding.reshape(1, -1).astype(self.norm.weight.dtype))
+
+ def __call__(self, embeddings, cache):
+ """Logits for `embeddings`, in float32 for the sampler.
+
+ The lm_head is tied to the token embedding, so the output projection is
+ the embedding matrix itself.
+ """
+ mask = "causal" if embeddings.shape[1] > 1 else None
+ hidden = embeddings
+ for layer, layer_cache in zip(self.layers, cache):
+ hidden = layer(hidden, mask, layer_cache)
+ hidden = self.norm(hidden[:, -1:, :])
+ return self.embed_tokens.as_linear(hidden)[:, 0, :].astype(mx.float32)
+
+ def new_cache(self):
+ return [KVCache(self.n_kv_heads, self.head_dim) for _ in range(self.n_layers)]
+
+
+class KVCache:
+ """Keys and values for one layer, grown in blocks.
+
+ Reallocating per step would copy the whole cache every token; a block means
+ that happens once per `step` tokens instead.
+ """
+
+ step = 256
+
+ def __init__(self, n_kv_heads, head_dim):
+ self.n_kv_heads, self.head_dim = n_kv_heads, head_dim
+ self.keys = self.values = None
+ self.offset = 0
+
+ def update_and_fetch(self, keys, values):
+ length = keys.shape[2]
+ if self.keys is None or self.offset + length > self.keys.shape[2]:
+ capacity = ((self.offset + length + self.step - 1) // self.step) * self.step
+ shape = (keys.shape[0], self.n_kv_heads, capacity, self.head_dim)
+ grown_keys = mx.zeros(shape, keys.dtype)
+ grown_values = mx.zeros(shape, values.dtype)
+ if self.keys is not None:
+ grown_keys[..., :self.offset, :] = self.keys[..., :self.offset, :]
+ grown_values[..., :self.offset, :] = self.values[..., :self.offset, :]
+ self.keys, self.values = grown_keys, grown_values
+
+ self.keys[..., self.offset:self.offset + length, :] = keys
+ self.values[..., self.offset:self.offset + length, :] = values
+ self.offset += length
+ return self.keys[..., :self.offset, :], self.values[..., :self.offset, :]
diff --git a/kittenml/kittentts2/mlx/sample.py b/kittenml/kittentts2/mlx/sample.py
new file mode 100644
index 0000000..301ef0f
--- /dev/null
+++ b/kittenml/kittentts2/mlx/sample.py
@@ -0,0 +1,148 @@
+"""KittenTTS 2's decode-time sampling, in MLX.
+
+A port of `logits.py` and of the transformers warpers it composes, in the same
+order, so a generation on this backend is drawn from the same distribution the
+decode presets were tuned against:
+
+ token-run penalty -> repetition penalty -> temperature
+ -> top_k -> top_p -> min_p -> sample
+
+Every step runs on the GPU over the whole vocabulary, as the Torch backend's does;
+the history is kept as a device array so no token ever round-trips through Python
+to be penalised.
+"""
+
+import mlx.core as mx
+
+from ..logits import SILENCE_TOKEN
+
+FILTER_VALUE = -float("inf")
+
+
+class TokenRunPenalty:
+ """Escalating penalty on a codec token repeated past `grace` times in a row.
+
+ The trailing run length is a reversed cumulative product over the equality
+ mask, exactly as in `logits.TokenRunPenalty`.
+ """
+
+ def __init__(self, lo, hi, grace=10, strength=1.3):
+ self.lo, self.hi = int(lo), int(hi)
+ self.grace, self.strength = int(grace), float(strength)
+
+ def __call__(self, history, scores):
+ last = history[:, -1]
+ equal = (history == last[:, None]).astype(mx.int32)
+ run = mx.cumprod(equal[:, ::-1], axis=1).sum(axis=1)
+ hit = (last >= self.lo) & (last < self.hi) & (run >= self.grace)
+ penalty = mx.where(hit, (run - self.grace + 1).astype(scores.dtype) * self.strength, 0)
+ at_last = mx.arange(scores.shape[-1]) == last[:, None]
+ return mx.where(at_last, scores - penalty[:, None], scores)
+
+
+class RepetitionPenaltyExempt:
+ """Repetition penalty that never penalises the sequence-terminating tokens.
+
+ See `logits.RepetitionPenaltyExempt`: `<speech_end>`, `[STOP]` and the silence
+ codec token keep their original scores, and `window` restricts the scan to the
+ last N generated positions.
+ """
+
+ def __init__(self, penalty, exempt_ids, window=None, prompt_length=0):
+ self.penalty = float(penalty)
+ self.exempt_ids = sorted({int(i) for i in exempt_ids})
+ self.window = int(window) if window else None
+ self.prompt_length = int(prompt_length)
+ self._exempt = None
+
+ def __call__(self, history, scores):
+ if self.window is not None:
+ history = history[:, max(self.prompt_length, history.shape[1] - self.window):]
+ if history.shape[1] == 0:
+ return scores
+ got = mx.take_along_axis(scores, history, axis=-1)
+ got = mx.where(got < 0, got * self.penalty, got / self.penalty)
+ out = mx.put_along_axis(scores, history, got, axis=-1)
+ if self.exempt_ids:
+ if self._exempt is None:
+ index = mx.array(self.exempt_ids)[None, :]
+ self._exempt = mx.zeros((1, scores.shape[-1]), mx.bool_)
+ self._exempt = mx.put_along_axis(self._exempt, index,
+ mx.ones((1, index.shape[1]), mx.bool_),
+ axis=-1)
+ out = mx.where(self._exempt, scores, out)
+ return out
+
+
+def _temperature(temperature):
+ return lambda history, scores: scores / temperature
+
+
+def _top_k(top_k):
+ """Keep the `top_k` highest scores, as `TopKLogitsWarper` does."""
+ def apply(history, scores):
+ kth = mx.sort(scores, axis=-1)[..., -min(top_k, scores.shape[-1]), None]
+ return mx.where(scores < kth, FILTER_VALUE, scores)
+ return apply
+
+
+def _top_p(top_p):
+ """Nucleus truncation, following `TopPLogitsWarper` exactly.
+
+ Ascending order, dropping the tail whose cumulative probability stays at or
+ below `1 - top_p`, and always keeping the single most likely token.
+ """
+ def apply(history, scores):
+ order = mx.argsort(scores, axis=-1)
+ ordered = mx.take_along_axis(scores, order, axis=-1)
+ cumulative = mx.cumsum(mx.softmax(ordered, axis=-1), axis=-1)
+ drop = cumulative <= (1.0 - top_p)
+ # min_tokens_to_keep=1: the last column is the most likely token.
+ drop[..., -1:] = False
+ return mx.put_along_axis(scores, order, mx.where(drop, FILTER_VALUE, ordered),
+ axis=-1)
+ return apply
+
+
+def _min_p(min_p):
+ """Drop tokens below `min_p` of the most likely one, as `MinPLogitsWarper` does."""
+ def apply(history, scores):
+ probabilities = mx.softmax(scores, axis=-1)
+ threshold = min_p * mx.max(probabilities, axis=-1, keepdims=True)
+ drop = probabilities < threshold
+ keep_best = mx.arange(scores.shape[-1]) == mx.argmax(scores, axis=-1)[:, None]
+ return mx.where(drop & ~keep_best, FILTER_VALUE, scores)
+ return apply
+
+
+def build_logits_processors(token_map, temperature, top_k, top_p, min_p,
+ repetition_penalty=1.1, repetition_window=None,
+ token_run_penalty=1.3, token_run_grace=10,
+ prompt_length=0):
+ """The MLX counterpart of `logits.build_logits_processors`, in the same order."""
+ lo, hi = token_map.audio_id_base, token_map.audio_id_end
+ processors = []
+
+ if token_run_penalty:
+ processors.append(TokenRunPenalty(lo, hi, token_run_grace, token_run_penalty))
+ if repetition_penalty != 1.0:
+ exempt = {token_map.speech_end_id, token_map.stop_id, lo + SILENCE_TOKEN}
+ processors.append(RepetitionPenaltyExempt(
+ repetition_penalty, exempt, window=repetition_window,
+ prompt_length=prompt_length))
+ if temperature != 1.0:
+ processors.append(_temperature(float(temperature)))
+ if top_k:
+ processors.append(_top_k(int(top_k)))
+ if top_p < 1.0:
+ processors.append(_top_p(float(top_p)))
+ if min_p > 0.0:
+ processors.append(_min_p(float(min_p)))
+ return processors
+
+
+def sample(history, logits, processors):
+ """Apply every processor, then draw one token from the result."""
+ for processor in processors:
+ logits = processor(history, logits)
+ return mx.random.categorical(logits, axis=-1)
diff --git a/kittenml/kittentts2/model.py b/kittenml/kittentts2/model.py
index 8d356ee..9af8188 100644
--- a/kittenml/kittentts2/model.py
+++ b/kittenml/kittentts2/model.py
@@ -65,6 +65,43 @@ ADVANCED_OPTIONS = {
}
+def _resolve_backend(backend):
+ """Which language-model backend to build.
+
+ "auto" picks MLX on an Apple-silicon Mac with `mlx` installed and the Torch
+ backend everywhere else; it never selects vLLM, which has its own memory
+ settings to choose.
+ """
+ if backend in (None, "torch"):
+ return "torch"
+ if backend == "auto":
+ import importlib.util
+ import platform
+ apple_silicon = platform.system() == "Darwin" and platform.machine() == "arm64"
+ return "mlx" if apple_silicon and importlib.util.find_spec("mlx") else "torch"
+ if backend not in ("vllm", "mlx"):
+ raise ValueError(f"unknown backend {backend!r}; choose from "
+ "'torch', 'mlx', 'vllm' or 'auto'")
+ return backend
+
+
+def _resolve_device(device, backend):
+ """The Torch device for everything the chosen backend does not run itself.
+
+ The MLX backend runs the language model through MLX, so this is only the
+ device for the parts that stay in Torch: audio decoding, speaker embedding and
+ transcription. Those go to MPS, which is several times faster for s3gen than
+ the CPU is and shares the same unified memory, so nothing is copied between
+ them. Pass `device="cpu"` to keep them off the GPU β€” on a Torch build whose
+ MPS backend is missing an op s3gen needs, that is the fallback.
+ """
+ if device is not None:
+ return device
+ if backend == "mlx":
+ return "mps" if torch.backends.mps.is_available() else "cpu"
+ return "cuda" if torch.cuda.is_available() else "cpu"
+
+
@contextlib.contextmanager
def _quiet_unexpected_keys():
"""Quieten transformers' loading chatter for one from_pretrained call."""
@@ -92,14 +129,14 @@ class KittenTTS2:
"""
def __init__(self, repo_dir, config, device=None, cache_dir=None, hf_token=None,
- decoder=None, weights=None, backend=None, vllm_options=None):
+ decoder=None, weights=None, backend=None, vllm_options=None,
+ mlx_options=None):
self.repo_dir = pathlib.Path(repo_dir)
self.config = config
self.cache_dir = cache_dir
- if device is None:
- device = "cuda" if torch.cuda.is_available() else "cpu"
- self.device = device
+ self.backend = _resolve_backend(backend)
+ self.device = _resolve_device(device, self.backend)
self.token_map = TokenMap.from_config(config)
generation = config.get("generation", {})
@@ -112,10 +149,12 @@ class KittenTTS2:
self.chunk_min_chars = generation.get("chunk_min_chars", text_utils.CHUNK_MIN_CHARS)
self.weights = weights or config.get("default_weights", "packed")
- self.backend = "vllm" if backend == "vllm" else "torch"
if self.backend == "vllm":
from .vllm.backend import VLLMBackend
self.model = VLLMBackend(self, vllm_options)
+ elif self.backend == "mlx":
+ from .mlx.backend import MLXBackend
+ self.model = MLXBackend(self, mlx_options)
else:
self._load_language_model()
self.decoders = config.get("decoders", {})
@@ -315,12 +354,23 @@ class KittenTTS2:
transcript_ids = self.tokenizer.encode(transcript.strip(), add_special_tokens=False)
return {
"prefix": build_reference_prefix(self.token_map, transcript_ids, reference_tokens),
- "embedding": torch.tensor(np.asarray(embedding, np.float32),
- device=self.device, dtype=self.dtype).unsqueeze(0),
+ "embedding": self._speaker_embedding(embedding),
"conditioning": self.codec.reference_conditioning(reference_wav),
"transcript": transcript,
}
+ def _speaker_embedding(self, embedding):
+ """The conditioning the active backend's language model wants.
+
+ MLX keeps its own arrays, and projects the embedding once here rather than
+ once per chunk; the Torch and vLLM backends take the raw embedding as a
+ tensor and run `spk_proj` themselves at prefill.
+ """
+ array = np.asarray(embedding, np.float32)
+ if self.backend == "mlx":
+ return self.model.speaker_embedding(array)
+ return torch.tensor(array, device=self.device, dtype=self.dtype).unsqueeze(0)
+
# ── generation ────────────────────────────────────────────────────────────
def _resolve_advanced(self, advanced):
"""Merge caller overrides over the defaults, rejecting unknown keys."""
@@ -357,7 +407,7 @@ class KittenTTS2:
reference_prefix=reference["prefix"] if use_reference_prompt else None,
emotion_ids=emotion_ids)
- if self.backend == "vllm":
+ if self.backend in ("vllm", "mlx"):
return self.model.generate_tokens(prompt, reference["embedding"], settings,
max_new_tokens, advanced)
@@ -390,6 +440,17 @@ class KittenTTS2:
generated = output[0].tolist()[len(prompt):]
return [t - low for t in generated if low <= t < high]
+ def _seed(self, seed):
+ """Seed the active backend's sampler, once per generation.
+
+ Once per generation rather than once per chunk, so a seeded multi-chunk
+ generation is reproducible without every chunk drawing from the same
+ stream.
+ """
+ torch.manual_seed(seed)
+ if self.backend == "mlx":
+ self.model.seed(seed)
+
def _chunk_budget(self, chunk, max_new_tokens, single_chunk):
"""Cap a chunk's generation at what its text plausibly needs.
@@ -411,7 +472,7 @@ class KittenTTS2:
min_chars=advanced["chunk_min_chars"])
settings = self._resolve_preset(preset, overrides)
if advanced["seed"] is not None:
- torch.manual_seed(int(advanced["seed"]))
+ self._seed(int(advanced["seed"]))
use_emotion = advanced["use_emotion"]
if use_emotion is None:
diff --git a/kittenml/kittentts_legacy/model.py b/kittenml/kittentts_legacy/model.py
index d92510a..50b16c7 100644
--- a/kittenml/kittentts_legacy/model.py
+++ b/kittenml/kittentts_legacy/model.py
@@ -25,7 +25,8 @@ class KittenTTSOnnx:
"""
def __init__(self, model_name="KittenML/kitten-tts-nano-0.8", cache_dir=None,
- backend=None, device=None, hf_token=None, *, vllm_options=None):
+ backend=None, device=None, hf_token=None, *, vllm_options=None,
+ mlx_options=None):
"""Initialize an ONNX KittenTTS model.
Args:
@@ -37,6 +38,8 @@ class KittenTTSOnnx:
"""
if vllm_options is not None:
raise ValueError("the vLLM backend requires a KittenTTS 2 model")
+ if mlx_options is not None:
+ raise ValueError("the MLX backend requires a KittenTTS 2 model")
local_dir, repo_id, config = getattr(self, "_resolved", None) or \
resolve_repo(model_name, cache_dir)
self.model = build_onnx_model(config, local_dir, repo_id, cache_dir, backend)
diff --git a/pyproject.toml b/pyproject.toml
index d28404e..c2341f6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -54,6 +54,7 @@ Issues = "https://github.com/KittenML/KittenTTS/issues"
[project.optional-dependencies]
vllm = ["vllm==0.31.0; sys_platform == 'linux'"]
+mlx = ["mlx>=0.29.0; sys_platform == 'darwin' and platform_machine == 'arm64'"]
[project.entry-points."vllm.general_plugins"]
kittenml = "kittenml.kittentts2.vllm.loader:register"
diff --git a/requirements.txt b/requirements.txt
index 113437d..c45326d 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -31,3 +31,7 @@ kitten-text-processing>=0.1.0
espeakng_loader
phonemizer
onnxruntime
+
+# Optional language-model backends, neither installed by default:
+# pip install "kittenml[mlx]" Apple-silicon GPU, see docs/mlx.md
+# pip install "kittenml[vllm]" NVIDIA GPU on Linux, see docs/vllm.md
diff --git a/tests/test_mlx.py b/tests/test_mlx.py
new file mode 100644
index 0000000..df0bdc0
--- /dev/null
+++ b/tests/test_mlx.py
@@ -0,0 +1,154 @@
+"""MLX backend: exact weight conversion and sampler parity; no model download."""
+
+from dataclasses import asdict
+from types import SimpleNamespace
+from unittest import mock
+
+import numpy as np
+import pytest
+import torch
+from safetensors.torch import save_file
+
+from kittenml import KittenTTS
+from kittenml.kittentts2.ternary import pack_state_dict
+from kittenml.kittentts2.tokens import TokenMap
+
+mx = pytest.importorskip("mlx.core", reason="the MLX backend is an optional extra")
+
+from kittenml.kittentts2.mlx import loader, sample # noqa: E402
+
+# The real codec vocabulary size: the repetition penalty exempts the silence
+# token at offset 4299, so a toy audio range would not reach it.
+TOKEN_MAP = TokenMap(audio_id_base=100, num_audio_tokens=6561, speech_start_id=1,
+ speech_end_id=2, text_start_id=3, text_end_id=4, start_id=5,
+ stop_id=6)
+
+
+def _write_packed(tmp_path, state):
+ lm = tmp_path / "lm"
+ lm.mkdir(exist_ok=True)
+ tensors, metadata = pack_state_dict(state)
+ save_file(tensors, lm / "model-ternary.safetensors", metadata=metadata)
+ return lm / "model-ternary.safetensors"
+
+
+def test_ternary_weights_convert_to_mlx_4bit_exactly(tmp_path):
+ """The whole point of the backend: 4 bits, and not one weight changed."""
+ generator = torch.Generator().manual_seed(0)
+ scales = torch.tensor([[0.125], [0.5], [2.0], [0.0625]])
+ ternary = (torch.randint(-1, 2, (4, 256), generator=generator).reshape(4, 2, 128)
+ * scales.unsqueeze(1)).reshape(4, 256).to(torch.bfloat16)
+ dense = torch.tensor([0.3, -1.7], dtype=torch.bfloat16)
+ path = _write_packed(tmp_path, {"model.layer.weight": ternary, "spk_proj.0.bias": dense})
+
+ weights, quantised, group_size = loader.load_lm_weights(path, dtype=mx.bfloat16)
+ assert group_size == 128
+ codes, scale, bias = quantised["model.layer.weight"]
+ # 4 bits per weight: eight of them in each uint32 word.
+ assert codes.shape == (4, 256 // 8) and codes.dtype == mx.uint32
+ rebuilt = mx.dequantize(codes, scale, bias, group_size=group_size, bits=4)
+ assert np.array_equal(np.array(rebuilt.astype(mx.float32)), ternary.float().numpy())
+ assert np.array_equal(np.array(weights["spk_proj.0.bias"].astype(mx.float32)),
+ dense.float().numpy())
+ # And every code really is one of the three a ternary weight can take.
+ assert set(np.unique(np.array(mx.dequantize(codes, mx.ones_like(scale),
+ mx.zeros_like(bias), group_size=group_size,
+ bits=4).astype(mx.int32)))) <= {0, 1, 2}
+
+
+def test_unpacked_checkpoints_are_refused_with_a_usable_message(tmp_path):
+ path = tmp_path / "plain.safetensors"
+ save_file({"model.layer.weight": torch.zeros(2, 128, dtype=torch.bfloat16)}, path)
+ with pytest.raises(ValueError, match="packed"):
+ loader.load_lm_weights(path)
+
+
[email protected]("settings", [
+ {"temperature": 0.8, "top_k": 50, "top_p": 0.8, "min_p": 0.0},
+ {"temperature": 1.0, "top_k": 0, "top_p": 1.0, "min_p": 0.05},
+ {"temperature": 0.9, "top_k": 8, "top_p": 0.95, "min_p": 0.02},
+])
+def test_sampling_pipeline_matches_the_torch_one(settings):
+ """Same distribution, not merely the same shape: the presets were tuned on it."""
+ from kittenml.kittentts2 import logits as torch_logits
+
+ rng = np.random.default_rng(0)
+ vocabulary = TOKEN_MAP.audio_id_end + 5
+ history = np.concatenate([
+ rng.integers(0, 100, 12), # prompt-side text tokens
+ rng.integers(TOKEN_MAP.audio_id_base, TOKEN_MAP.audio_id_end, 30),
+ np.full(14, TOKEN_MAP.audio_id_base + 7), # a run, for TokenRunPenalty
+ ]).astype(np.int64)[None]
+ scores = rng.normal(size=(1, vocabulary)).astype(np.float32) * 4
+
+ common = dict(repetition_penalty=1.1, repetition_window=20, token_run_penalty=1.3,
+ token_run_grace=10, prompt_length=12, **settings)
+ expected = torch_logits.build_logits_processors(TOKEN_MAP, **common)(
+ torch.from_numpy(history), torch.from_numpy(scores.copy()))
+ actual = mx.array(scores)
+ for processor in sample.build_logits_processors(TOKEN_MAP, **common):
+ actual = processor(mx.array(history), actual)
+
+ np.testing.assert_allclose(np.array(actual), expected.numpy(), rtol=1e-5, atol=1e-5)
+
+
+def test_sampling_is_reproducible_and_stays_inside_the_filtered_set():
+ processors = sample.build_logits_processors(
+ TOKEN_MAP, temperature=0.8, top_k=4, top_p=1.0, min_p=0.0,
+ repetition_penalty=1.0, token_run_penalty=0)
+ scores = mx.array(np.linspace(-5, 5, TOKEN_MAP.audio_id_end + 5,
+ dtype=np.float32)[None])
+ history = mx.array(np.array([[TOKEN_MAP.start_id]]))
+ allowed = set(range(scores.shape[-1] - 4, scores.shape[-1]))
+
+ mx.random.seed(11)
+ drawn = [int(sample.sample(history, scores, processors).item()) for _ in range(20)]
+ assert set(drawn) <= allowed
+ mx.random.seed(11)
+ assert [int(sample.sample(history, scores, processors).item()) for _ in range(20)] == drawn
+
+
+def test_backend_selection_and_its_refusals(tmp_path):
+ from kittenml.kittentts2.model import KittenTTS2, _resolve_backend
+
+ config = {"token_map": asdict(TOKEN_MAP), "type": "KITTEN2"}
+ with mock.patch("kittenml.kittentts2.mlx.backend.MLXBackend") as backend, \
+ mock.patch("kittenml.kittentts2.model.S3Codec"), \
+ mock.patch("kittenml.kittentts2.model.SpeakerEncoder"), \
+ mock.patch("kittenml.kittentts2.model.ReferenceTranscriber"):
+ model = KittenTTS2(tmp_path, config, backend="mlx", device="cpu")
+ backend.assert_called_once_with(model, None)
+ assert model.backend == "mlx"
+
+ assert _resolve_backend("auto") == "mlx" # this test only runs where mlx imports
+ assert _resolve_backend(None) == "torch"
+ with pytest.raises(ValueError, match="unknown backend"):
+ _resolve_backend("metal")
+
+ with pytest.raises(ValueError, match="mlx_options requires"):
+ KittenTTS("KittenML/kitten-tts-2", mlx_options={"threads": 4})
+
+
+def test_emb4_weights_are_refused_rather_than_silently_dequantised(tmp_path):
+ from kittenml.kittentts2.mlx.backend import MLXBackend
+
+ owner = SimpleNamespace(token_map=TOKEN_MAP, repo_dir=tmp_path, config={},
+ weights="emb4", device="cpu",
+ _weights_path=lambda name: tmp_path / name)
+ with pytest.raises(ValueError, match="weights='packed'"):
+ MLXBackend(owner)
+
+
+def test_speaker_embedding_is_projected_once_per_reference():
+ from kittenml.kittentts2.model import KittenTTS2
+
+ owner = SimpleNamespace(backend="mlx", model=mock.Mock(), device="cpu",
+ dtype=torch.float32)
+ embedding = np.arange(8, dtype=np.float32)
+ result = KittenTTS2._speaker_embedding(owner, embedding)
+ assert result is owner.model.speaker_embedding.return_value
+ np.testing.assert_array_equal(owner.model.speaker_embedding.call_args[0][0], embedding)
+
+ owner.backend = "torch"
+ tensor = KittenTTS2._speaker_embedding(owner, embedding)
+ assert tensor.shape == (1, 8) and tensor.dtype is torch.float32