Skip to content

A TTS that fits in your CPU (and pocket)

Python

Reject a voice state of another model when loading it (#450)

Toma Stefan Ionescu8b93a5aae5dd
diff --git a/pocket_tts/models/model_state.py b/pocket_tts/models/model_state.py
index d255e5a..a4e7140 100644
--- a/pocket_tts/models/model_state.py
+++ b/pocket_tts/models/model_state.py
@@ -30,12 +30,14 @@ def _is_safetensors_source(source: str | Path) -> bool:
def _import_model_state(
- source: str | Path, device: torch.device
+ source: str | Path, device: torch.device, expected: dict[str, dict[str, torch.Tensor]]
) -> dict[str, dict[str, torch.Tensor]]:
+ """`expected` is the `init_states()` of the model the state is loaded into."""
result = {}
with safetensors.safe_open(source, framework="pt") as f:
for key in f.keys():
- module_name, tensor_key = key.split("/")
+ # The voices of pocket-tts 1.0 hold a bare `audio_prompt`, rejected by the check below.
+ module_name, _, tensor_key = key.rpartition("/")
result.setdefault(module_name, {})
if tensor_key == "current_end":
# we used the shape[0] as step index before for torch.compile() compatibility,
@@ -46,4 +48,30 @@ def _import_model_state(
)
else:
result[module_name][tensor_key] = f.get_tensor(key).to(device)
+ _check_model_state(result, expected, source)
return result
+
+
+def _check_model_state(
+ state: dict[str, dict[str, torch.Tensor]],
+ expected: dict[str, dict[str, torch.Tensor]],
+ source: str | Path,
+):
+ """Fail on a state exported with a model of another size: otherwise the attention fails
+ at the first generation step or, when the state has more layers, the extra ones are
+ silently ignored."""
+ error = f"{source} is not a voice state of this model"
+ hint = "a voice state only works with the model that exported it, re-export it"
+ missing, extra = sorted(expected.keys() - state.keys()), sorted(state.keys() - expected.keys())
+ if missing or extra:
+ what = f"it has no {missing[0]}" if missing else f"this model has no {extra[0]}"
+ raise ValueError(f"{error}: {what} ({hint})")
+ for name, module_state in expected.items():
+ want, got = module_state["cache"].shape, state[name].get("cache")
+ # Only the time axis (dim 2) depends on the voice.
+ if got is None or got.shape[:2] != want[:2] or got.shape[3:] != want[3:]:
+ shape = None if got is None else list(got.shape)
+ raise ValueError(
+ f"{error}: {name}/cache has shape {shape}, this model needs "
+ f"[2, 1, _, {want[3]}, {want[4]}] ({hint})"
+ )
diff --git a/pocket_tts/models/tts_model.py b/pocket_tts/models/tts_model.py
index 3552b91..0e5051b 100644
--- a/pocket_tts/models/tts_model.py
+++ b/pocket_tts/models/tts_model.py
@@ -1087,7 +1087,11 @@ class TTSModel(nn.Module):
if isinstance(audio_conditioning, str):
audio_conditioning = download_if_necessary(audio_conditioning)
- return _import_model_state(audio_conditioning, self.device)
+ return _import_model_state(
+ audio_conditioning,
+ self.device,
+ init_states(self.flow_lm, batch_size=1, sequence_length=0),
+ )
elif (
isinstance(audio_conditioning, str)
@@ -1112,6 +1116,7 @@ class TTSModel(nn.Module):
get_predefined_voice(language=self.origin.stem, name=audio_conditioning)
),
self.device,
+ init_states(self.flow_lm, batch_size=1, sequence_length=0),
)
if not self.has_voice_cloning and isinstance(audio_conditioning, (str, Path)):
diff --git a/tests/test_model_state.py b/tests/test_model_state.py
new file mode 100644
index 0000000..5ea2412
--- /dev/null
+++ b/tests/test_model_state.py
@@ -0,0 +1,35 @@
+from pathlib import Path
+
+import pytest
+import safetensors.torch
+import torch
+
+from pocket_tts import TTSModel, export_model_state
+from pocket_tts.modules.stateful_module import init_states
+
+
+def test_a_voice_state_of_another_model_is_rejected_when_loading(tmp_path: Path):
+ model = TTSModel.load_model()
+ state = init_states(model.flow_lm, batch_size=1, sequence_length=3)
+ export_model_state(state, tmp_path / "same_model.safetensors")
+ model.get_state_for_audio_prompt(tmp_path / "same_model.safetensors")
+
+ # A model with fewer key/value heads, one with more layers, and a pocket-tts 1.0 voice.
+ one_kv_head = {
+ name: {**s, "cache": s["cache"][:, :, :, :1].contiguous()} for name, s in state.items()
+ }
+ export_model_state(one_kv_head, tmp_path / "one_kv_head.safetensors")
+ first_layer = state["transformer.layers.0.self_attn"]
+ more_layers = {
+ **state,
+ f"transformer.layers.{len(state)}.self_attn": {
+ k: v.clone() for k, v in first_layer.items()
+ },
+ }
+ export_model_state(more_layers, tmp_path / "more_layers.safetensors")
+ safetensors.torch.save_file(
+ {"audio_prompt": torch.zeros(1, 125, 1024)}, tmp_path / "v1.safetensors"
+ )
+ for name in ["one_kv_head", "more_layers", "v1"]:
+ with pytest.raises(ValueError, match="is not a voice state of this model"):
+ model.get_state_for_audio_prompt(tmp_path / f"{name}.safetensors")