tiny-voca-hindi / scripts /to_gguf.py
RL10x's picture
Add inference code (Python + C++ engine + web page)
ab1b068 verified
Raw History Blame Contribute Delete
4.4 kB
"""Hindi tiny-voca checkpoint -> GGUF for the C++ engine (tts_cpp/).
python scripts/to_gguf.py --checkpoint models/tiny_voca_hindi.pt --out models/tts_hi_q8_0.gguf --type q8_0
python scripts/to_gguf.py ... --type f32 (exact reference for checking the C++ engine)
Tensor names are the PyTorch state_dict names. The transformer and duration-predictor Linear weights become Q8_0 with
--type q8_0 (rows of 256 or 1024 values); everything else stays float32: embeddings, norms, biases, convolutions, the
3-wide prosody Linears and the synthesizer heads (they set filter cepstra and gains directly, where rounding is audible).
Predictor Conv1d weights [out, in, 3] are stored as three [out, in] matrices "<name>.k0/k1/k2" so the engine runs each
tap as a matrix multiply.
"""
import argparse
import sys
from pathlib import Path
import numpy as np
import torch
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
import gguf # noqa: E402
from tiny_voca.infer import load_model # noqa: E402
from tiny_voca.text import PHONE_IDS, SYMBOLS, SYMBOL_TO_ID, VOWELS # noqa: E402
ARCH = "tinyvoca"
def quantizable(name, array):
if array.ndim != 2 or array.shape[1] % 32 or name.startswith("vocoder."):
return False
return name.endswith(".weight") and any(k in name for k in (".qkv.", ".out.", ".expand.", ".project.")) \
and not name.startswith(("prosody_head", "prosody_projection", "frame_position"))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--checkpoint", default="models/tiny_voca_hindi.pt")
ap.add_argument("--out", required=True)
ap.add_argument("--type", choices=("q8_0", "f32"), default="q8_0")
a = ap.parse_args()
model = load_model(a.checkpoint, "cpu").eval()
c = model.config
w = gguf.GGUFWriter(a.out, ARCH)
w.add_name("tts-hi-tiny-voca")
w.add_description("Hindi tiny-voca TTS (Rasa female, 8 styles): phonemes -> transformer -> source-filter synthesizer")
for key in ("sample_rate", "hop", "channels", "heads", "feedforward", "kernel", "encoder_layers", "prosody_layers",
"acoustic_layers", "predictor_channels", "synth_fft", "synth_hop", "noise_fft", "noise_hop", "cep_causal",
"cep_anti", "noise_cep", "max_tokens", "max_frames", "vocab_size"):
w.add_uint32(f"{ARCH}.{key}", int(getattr(c, key)))
for key in ("f0_min", "f0_max", "harmonic_limit", "pitch_reference_hz"):
w.add_float32(f"{ARCH}.{key}", float(getattr(c, key)))
w.add_array(f"{ARCH}.styles", list(c.speakers))
w.add_array(f"{ARCH}.symbols", list(SYMBOLS))
w.add_array(f"{ARCH}.phone_ids", sorted(int(i) for i in PHONE_IDS))
w.add_array(f"{ARCH}.vowel_ids", sorted(int(SYMBOL_TO_ID[v]) for v in VOWELS))
# lifters are buffers (not in the state dict): store them so the engine needs no formula
v = model.vocoder
tensors = {k: t.detach().float().numpy() for k, t in model.state_dict().items()}
tensors["vocoder.causal_lifter"] = v.causal_lifter.numpy()
tensors["vocoder.anti_lifter"] = v.anti_lifter.numpy()
tensors["vocoder.noise_lifter"] = v.noise_lifter.numpy()
n_q = n_f = 0
for name, arr in tensors.items():
if arr.ndim == 3 and name.startswith("duration.conv"): # [out, in, 3] -> three [out, in] taps
for k in range(arr.shape[2]):
w.add_tensor(f"{name}.k{k}", np.ascontiguousarray(arr[:, :, k]))
n_f += arr[:, :, k].size
continue
if arr.ndim == 3: # depthwise conv [C, 1, K] -> [K, C] (tap k = row k)
arr = arr[:, 0, :].T
arr = np.ascontiguousarray(arr.astype(np.float32))
if a.type == "q8_0" and quantizable(name, arr):
q = gguf.quants.quantize(arr, gguf.GGMLQuantizationType.Q8_0)
w.add_tensor(name, q, raw_shape=q.shape, raw_dtype=gguf.GGMLQuantizationType.Q8_0)
n_q += arr.size
else:
w.add_tensor(name, arr)
n_f += arr.size
w.write_header_to_file(); w.write_kv_data_to_file(); w.write_tensors_to_file(); w.close()
print(f"{a.out}: {Path(a.out).stat().st_size / 1e6:.1f} MB, {n_q:,} values Q8_0, {n_f:,} values F32, {len(tensors)} tensors")
if __name__ == "__main__":
main()