mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-26 23:29:34 +00:00
mtmd: support tiny-voca (#32427)
* mtmd: support tiny-voca * improve G2P
This commit is contained in:
parent
2e53a0bab7
commit
3574df84b7
32 changed files with 4591 additions and 59 deletions
|
|
@ -871,7 +871,7 @@ bool common_tts_dict_find(const common_tts_dict & dict, const std::string & key,
|
|||
return true;
|
||||
}
|
||||
|
||||
void common_chat_tts_norm_add_builtins(context & ctx, std::shared_ptr<const common_tts_dicts> dicts) {
|
||||
void common_chat_tts_norm_add_builtins(context & ctx, std::shared_ptr<const common_tts_dicts> dicts, common_tts_g2p g2p) {
|
||||
ctx.set_val("tts_norm_scan", mk_val<value_func>("tts_norm_scan", tts_norm_builtin_scan));
|
||||
ctx.set_val("tts_norm_sub", mk_val<value_func>("tts_norm_sub", tts_norm_builtin_sub));
|
||||
ctx.set_val("tts_dict", mk_val<value_func>("tts_dict", [dicts](const func_args & args) -> value {
|
||||
|
|
@ -888,5 +888,15 @@ void common_chat_tts_norm_add_builtins(context & ctx, std::shared_ptr<const comm
|
|||
}
|
||||
return value_from_json(common_json::parse(doc), false);
|
||||
}));
|
||||
// none when the caller gives no letter-to-sound model, or the model has no pronunciation
|
||||
ctx.set_val("tts_g2p", mk_val<value_func>("tts_g2p", [g2p](const func_args & args) -> value {
|
||||
args.ensure_count(1, 1);
|
||||
args.ensure_vals<value_string>();
|
||||
const std::string out = g2p ? g2p(args.get_pos(0)->as_string().str()) : std::string();
|
||||
if (out.empty()) {
|
||||
return mk_val<value_none>();
|
||||
}
|
||||
return mk_val<value_string>(out);
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
|
@ -70,6 +71,11 @@ using common_tts_dicts = std::map<std::string, common_tts_dict>;
|
|||
// binary search of key in a dictionary; on success, value is set to the JSON document
|
||||
bool common_tts_dict_find(const common_tts_dict & dict, const std::string & key, std::string & value);
|
||||
|
||||
// add tts_norm_scan(), tts_norm_sub() and tts_dict() to the context of a task template
|
||||
// pronunciation of a word by a letter-to-sound model, as phonemes separated by spaces (e.g. CMUdict notation)
|
||||
// empty when there is none; the notation is the one of the model, its "tts" template knows it
|
||||
using common_tts_g2p = std::function<std::string(const std::string & word)>;
|
||||
|
||||
// add tts_norm_scan(), tts_norm_sub(), tts_dict() and tts_g2p() to the context of a task template
|
||||
// they are not jinja global builtins on purpose: chat templates are not affected
|
||||
void common_chat_tts_norm_add_builtins(jinja::context & ctx, std::shared_ptr<const common_tts_dicts> dicts = nullptr);
|
||||
void common_chat_tts_norm_add_builtins(jinja::context & ctx, std::shared_ptr<const common_tts_dicts> dicts = nullptr,
|
||||
common_tts_g2p g2p = nullptr);
|
||||
|
|
|
|||
|
|
@ -807,10 +807,11 @@ bool common_chat_templates_was_explicit(const struct common_chat_templates * tmp
|
|||
}
|
||||
|
||||
// renders a task template (e.g. "tts") with the given variables
|
||||
static std::string common_chat_template_render(const common_chat_template & tmpl, const json & vars, const std::shared_ptr<common_tts_dicts> & tts_dicts) {
|
||||
static std::string common_chat_template_render(const common_chat_template & tmpl, const json & vars, const std::shared_ptr<common_tts_dicts> & tts_dicts,
|
||||
const common_tts_g2p & g2p = nullptr) {
|
||||
jinja::context ctx(tmpl.source());
|
||||
// text normalization helpers: tts_norm_scan(), tts_norm_sub() and tts_dict(), see docs/tts-norm-patterns.md
|
||||
common_chat_tts_norm_add_builtins(ctx, tts_dicts);
|
||||
// text normalization helpers: tts_norm_scan(), tts_norm_sub(), tts_dict() and tts_g2p(), see docs/tts-norm-patterns.md
|
||||
common_chat_tts_norm_add_builtins(ctx, tts_dicts, g2p);
|
||||
jinja::global_from_json(ctx, vars, false);
|
||||
ctx.set_val("bos_token", jinja::mk_val<jinja::value_string>(tmpl.bos_token()));
|
||||
ctx.set_val("eos_token", jinja::mk_val<jinja::value_string>(tmpl.eos_token()));
|
||||
|
|
@ -886,7 +887,7 @@ common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates
|
|||
}
|
||||
|
||||
std::string common_chat_get_tts_prompt(const common_chat_templates * chat_templates, const std::string & text,
|
||||
const std::string & language, const std::string & voice) {
|
||||
const std::string & language, const std::string & voice, const common_tts_g2p & g2p) {
|
||||
if (!chat_templates || !chat_templates->template_tts) {
|
||||
return "";
|
||||
}
|
||||
|
|
@ -894,7 +895,7 @@ std::string common_chat_get_tts_prompt(const common_chat_templates * chat_templa
|
|||
{"messages", json::array({{{"role", "user"}, {"content", text}}})},
|
||||
{"language", language},
|
||||
{"voice", voice},
|
||||
}, chat_templates->tts_dicts);
|
||||
}, chat_templates->tts_dicts, g2p);
|
||||
}
|
||||
|
||||
std::string common_chat_get_speech_system_prompt(const common_chat_templates * chat_templates,
|
||||
|
|
|
|||
|
|
@ -504,8 +504,10 @@ common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates
|
|||
|
||||
// prompt of the model's "tts" chat template for the text to speak, empty if the model has none
|
||||
// language and voice are optional, the template defines their defaults
|
||||
// g2p (optional): the letter-to-sound model of the template's tts_g2p(), e.g. mtmd_gen_audio_g2p()
|
||||
std::string common_chat_get_tts_prompt(const common_chat_templates * chat_templates, const std::string & text,
|
||||
const std::string & language = "", const std::string & voice = "");
|
||||
const std::string & language = "", const std::string & voice = "",
|
||||
const std::function<std::string(const std::string & word)> & g2p = nullptr);
|
||||
|
||||
// system prompt line for the speech language and voice (e.g. LFM3-Audio), empty if not used
|
||||
std::string common_chat_get_speech_system_prompt(const common_chat_templates * chat_templates,
|
||||
|
|
|
|||
|
|
@ -284,6 +284,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
|||
"Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
|
||||
"PocketTTSModel": "pockettts",
|
||||
"KokoroModel": "kokoro",
|
||||
"TinyVocaModel": "tiny_voca",
|
||||
"Zonos3Model": "zonos3",
|
||||
"YuE2ForCausalLM": "yue2",
|
||||
"MiniMaxMusic3ForConditionalGeneration": "minimax_music3",
|
||||
|
|
@ -425,6 +426,7 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
|
|||
"Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
|
||||
"PocketTTSModel": "pockettts",
|
||||
"KokoroModel": "kokoro",
|
||||
"TinyVocaModel": "tiny_voca",
|
||||
"SopranoModel": "soprano",
|
||||
"Qwen3TTSForConditionalGeneration": "qwen3tts",
|
||||
"Qwen3VLForConditionalGeneration": "qwen3vl",
|
||||
|
|
|
|||
443
conversion/tiny_voca.py
Normal file
443
conversion/tiny_voca.py
Normal file
|
|
@ -0,0 +1,443 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from .base import ModelBase, TextModel, MmprojModel, gguf, logger
|
||||
|
||||
# tiny-voca, https://huggingface.co/n4ze3m/tiny-voca
|
||||
#
|
||||
# text model: phoneme encoder (4 blocks), the input rows are built by the audio pipeline (token + stress + voice)
|
||||
# mmproj: input tables, voices, duration predictor, prosody and acoustic stacks, source-filter heads
|
||||
#
|
||||
# the text to phonemes step (dizione) is the "tts" chat template, see models/templates/n4ze3m-tiny-voca-tts.jinja
|
||||
# its lexicon comes from the phonemizer/ directory of the model, the other tables from the dizione python package
|
||||
#
|
||||
# the prosody and acoustic stacks have the same blocks as the encoder, they are stored with the libllama names
|
||||
# of the tiny-voca arch under a.gen.prosody. and a.gen.acoustic., mtmd runs them on llama contexts of its own
|
||||
|
||||
CHECKPOINT = "tiny-voca.pt"
|
||||
DEFAULT_VOICE = "M2"
|
||||
|
||||
# phone classes of the reference (text.py): the phones get at least one frame, the vowels are always voiced
|
||||
VOWELS = ("ə", "ɐ", "ɚ", "ᵻ", "ɪ", "i", "iː", "ɛ", "æ", "ʌ", "ɑː", "ɔ", "ɔː", "ʊ", "uː", "ɜː",
|
||||
"eɪ", "aɪ", "ɔɪ", "oʊ", "aʊ", "iə", "oː",
|
||||
"ɑːɹ", "ɔːɹ", "oːɹ", "ɪɹ", "ɛɹ", "ʊɹ", "aɪɚ", "aɪə", "əl", "n̩")
|
||||
CONSONANTS = ("p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h",
|
||||
"m", "n", "ŋ", "l", "ɹ", "j", "w", "tʃ", "dʒ", "ɾ", "ʔ")
|
||||
|
||||
# input letters and output phonemes of the unknown-word model, fixed in mtmd (see mtmd_graph_tiny_voca)
|
||||
G2P_LETTERS = "abcdefghijklmnopqrstuvwxyz'"
|
||||
G2P_SYMBOLS = [v + d for v in ("AA", "AE", "AH", "AO", "AW", "AY") for d in "012"] + ["B", "CH", "D", "DH"] + \
|
||||
[v + d for v in ("EH", "ER", "EY") for d in "012"] + ["F", "G", "HH"] + [v + d for v in ("IH", "IY") for d in "012"] + \
|
||||
["JH", "K", "L", "M", "N", "NG"] + [v + d for v in ("OW", "OY") for d in "012"] + ["P", "R", "S", "SH", "T", "TH"] + \
|
||||
[v + d for v in ("UH", "UW") for d in "012"] + ["V", "W", "Y", "Z", "ZH"]
|
||||
|
||||
# block tensors: reference name -> libllama name
|
||||
BLOCK_MAP = {
|
||||
"norm1": "attn_norm",
|
||||
"attention.qkv": "attn_qkv",
|
||||
"attention.out": "attn_output",
|
||||
"norm2": "ffn_norm",
|
||||
"depthwise": "ssm_conv1d",
|
||||
"expand": "ffn_up",
|
||||
"project": "ffn_down",
|
||||
}
|
||||
|
||||
# mmproj stacks: reference module -> prefix
|
||||
STACK_PREFIX = {
|
||||
"prosody_stack": "a.gen.prosody.",
|
||||
"acoustic_stack": "a.gen.acoustic.",
|
||||
}
|
||||
|
||||
# other mmproj tensors: reference module -> name
|
||||
MMPROJ_MAP = {
|
||||
"tokens": "a.gen.tok_embd",
|
||||
"stress": "a.gen.stress_embd",
|
||||
"duration.conv1": "a.gen.dur.conv1",
|
||||
"duration.conv2": "a.gen.dur.conv2",
|
||||
"duration.norm1": "a.gen.dur.norm1",
|
||||
"duration.norm2": "a.gen.dur.norm2",
|
||||
"duration.out": "a.gen.dur.out",
|
||||
"frame_position": "a.gen.frame_pos",
|
||||
"prosody_head": "a.gen.prosody_head",
|
||||
"prosody_projection": "a.gen.prosody_proj",
|
||||
"vocoder.harmonic": "a.gen.voc.harmonic",
|
||||
"vocoder.noise": "a.gen.voc.noise",
|
||||
}
|
||||
|
||||
|
||||
def _is_tiny_voca_checkpoint(dir_model: Path) -> bool:
|
||||
if not (dir_model / CHECKPOINT).is_file() or not (dir_model / "config.json").is_file():
|
||||
return False
|
||||
with open(dir_model / "config.json", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
return config.get("phonemizer", {}).get("name") == "dizione" and "vocab" in config and "model" in config
|
||||
|
||||
|
||||
@ModelBase.register_hparams_loader(_is_tiny_voca_checkpoint)
|
||||
def _load_tiny_voca_hparams(dir_model: Path) -> dict[str, Any]:
|
||||
logger.info("gguf: detected tiny-voca checkpoint")
|
||||
with open(dir_model / "config.json", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
c = config["model"]
|
||||
return {
|
||||
"architectures": ["TinyVocaModel"],
|
||||
"model_type": "tiny-voca",
|
||||
"num_hidden_layers": c["encoder_layers"],
|
||||
"hidden_size": c["channels"],
|
||||
"intermediate_size": c["feedforward"],
|
||||
"num_attention_heads": c["heads"],
|
||||
"num_key_value_heads": c["heads"],
|
||||
"max_position_embeddings": c["max_tokens"],
|
||||
"vocab_size": c["vocab_size"],
|
||||
"layer_norm_eps": 1e-5, # torch LayerNorm default
|
||||
"rope_theta": 10000.0,
|
||||
"tiny_voca": config,
|
||||
# the mmproj tensors are named explicitly, they do not go through the block tensor map
|
||||
"audio_config": {"num_hidden_layers": 0},
|
||||
}
|
||||
|
||||
|
||||
def _table_rows(path: Path) -> Iterable[list[str]]:
|
||||
# dizione tables: columns separated by tabs or two or more spaces, "#" comments
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.split("#", 1)[0].rstrip() if line.lstrip().startswith("#") else line.rstrip()
|
||||
if line.strip():
|
||||
yield [c.strip() for c in re.split(r"\t+| {2,}", line.strip())]
|
||||
|
||||
|
||||
def _g2p_dicts(dir_model: Path) -> dict[str, dict[str, Any]] | None:
|
||||
lexicon_path = dir_model / "phonemizer" / "lexicon.tsv"
|
||||
spec = importlib.util.find_spec("dizione")
|
||||
if not lexicon_path.is_file() or spec is None or spec.origin is None:
|
||||
logger.warning("dizione or phonemizer/lexicon.tsv not found, the model will take phonemes as prompt "
|
||||
"(pip install git+https://github.com/n4ze3m/dizione)")
|
||||
return None
|
||||
data = Path(spec.origin).parent / "data"
|
||||
lexicon: dict[str, str] = {}
|
||||
for line in lexicon_path.read_text(encoding="utf-8").splitlines():
|
||||
if "\t" in line:
|
||||
word, phones = line.split("\t", 1)
|
||||
lexicon[word] = phones.strip()
|
||||
|
||||
# word -> [stress class, form, final form or ""], see function_words.txt
|
||||
functions = {r[0]: [r[1], r[2], r[3] if len(r) > 3 else ""] for r in _table_rows(data / "function_words.txt")}
|
||||
# words -> [class, forms (one, or one per word), final form or ""], see phrases.txt
|
||||
phrases = {r[0]: [r[1], [f.strip() for f in r[2].split("|")], r[3] if len(r) > 3 else ""] for r in _table_rows(data / "phrases.txt")}
|
||||
letters = {r[0]: r[1] for r in _table_rows(data / "letters.txt")}
|
||||
# a value is phones, or CMUdict notation (converted by the template, like the output of the unknown-word model)
|
||||
exceptions = {r[0].lower(): r[1] for r in _table_rows(data / "exceptions.txt") if " " not in r[0]}
|
||||
# a name of several words: "w1 w2 ..." -> one pronunciation per word; first word -> the longest name it starts
|
||||
names: dict[str, Any] = {}
|
||||
name_starts: dict[str, int] = {}
|
||||
for r in _table_rows(data / "exceptions.txt"):
|
||||
words = r[0].lower().split()
|
||||
if len(words) > 1:
|
||||
names[" ".join(words)] = [part.strip() for part in r[1].split("|")]
|
||||
name_starts[words[0]] = max(name_starts.get(words[0], 0), len(words))
|
||||
# phoneme (CMUdict, no stress) -> {letters: log probability}: aligns the letters of a word to its phonemes
|
||||
with open(dir_model / "phonemizer" / "align.json", encoding="utf-8") as f:
|
||||
align = json.load(f)
|
||||
# abbreviation -> [when, words]
|
||||
abbreviations = {r[0]: [r[1], r[2]] for r in _table_rows(data / "abbreviations.txt")}
|
||||
# chat spelling -> [words to say ("*LOL": letter by letter, "-": nothing), only as a reply by itself], see chat.txt
|
||||
chat = {r[0].lower(): [r[1] if len(r) > 1 else "-", len(r) > 2] for r in _table_rows(data / "chat.txt")}
|
||||
# accented latin letter -> plain letter(s): "café" is in the dictionary as "cafe" (dizione: _plain_letter)
|
||||
accents = {"ß": "ss", "æ": "ae", "Æ": "Ae", "œ": "oe", "Œ": "Oe", "ø": "o", "Ø": "O", "đ": "d", "ł": "l", "Ł": "L"}
|
||||
for cp in range(0x80, 0x2000):
|
||||
char = chr(cp)
|
||||
if char.isalpha() and char not in accents:
|
||||
plain = "".join(c for c in unicodedata.normalize("NFKD", char) if not unicodedata.combining(c))
|
||||
if plain.isascii() and plain.isalpha():
|
||||
accents[char] = plain
|
||||
# compatibility forms of the text (NFKC), a character at a time: "…" is "...", "fi" is "fi", "№" is "No", full
|
||||
# width letters. Sequences that NFKC would compose are left as they are
|
||||
nfkc: dict[str, str] = {}
|
||||
for cp in list(range(0x80, 0x3000)) + list(range(0xFB00, 0xFB07)) + list(range(0xFF01, 0xFF5F)):
|
||||
if unicodedata.normalize("NFKC", chr(cp)) != chr(cp):
|
||||
nfkc[chr(cp)] = unicodedata.normalize("NFKC", chr(cp))
|
||||
# units after a number: name -> [one, many]; "exact" ones are written in one letter case only ("m", not "M")
|
||||
units: dict[str, Any] = {}
|
||||
exact_units: dict[str, Any] = {}
|
||||
for r in _table_rows(data / "units.txt"):
|
||||
if len(r) > 3 and r[3] == "exact":
|
||||
exact_units[r[0]] = [r[1], r[2]]
|
||||
else:
|
||||
units[r[0].lower()] = [r[1], r[2]]
|
||||
# the unit names as a pattern of tts_norm_scan(), the longest first; a unit does not stop inside a word
|
||||
unit_names = sorted(set(units) | set(exact_units), key=lambda name: (-len(name), name))
|
||||
# (the pattern ignores the case of ASCII letters only, the greek letter is written in both)
|
||||
unit_pattern = "|".join("".join("[μΜ]" if c == "μ" else c if c.isalnum() else "%" + c for c in name) + "(?![A-Za-z])" for name in unit_names)
|
||||
# endings of file names and addresses: "word" (dot com) or "letters" (dot P D F)
|
||||
endings = {r[0]: (r[1] if len(r) > 1 else "") for r in _table_rows(data / "endings.txt")}
|
||||
out = {
|
||||
"lexicon": lexicon,
|
||||
"functions": functions,
|
||||
"phrases": phrases,
|
||||
"letters": letters,
|
||||
"exceptions": exceptions,
|
||||
"abbreviations": abbreviations,
|
||||
"align": align,
|
||||
"names": names,
|
||||
"chat": chat,
|
||||
"accents": accents,
|
||||
"nfkc": nfkc,
|
||||
"units": units,
|
||||
"exact_units": exact_units,
|
||||
"endings": endings,
|
||||
"patterns": {"units": unit_pattern},
|
||||
"name_starts": name_starts,
|
||||
}
|
||||
out.update(_homograph_dicts(dir_model, data))
|
||||
return out
|
||||
|
||||
|
||||
def _homograph_dicts(dir_model: Path, data: Path) -> dict[str, dict[str, Any]]:
|
||||
# words spelled alike and pronounced differently (dizione homographs.py): a linear classifier on the neighbouring
|
||||
# words, and hand-written rules that are tried first. Weights are stored x10000 (they have four decimals), so the
|
||||
# template adds integers.
|
||||
path = dir_model / "phonemizer" / "homographs.json"
|
||||
if not path.is_file():
|
||||
return {"homographs": {}, "homograph_shared": {}, "homograph_plurals": {}, "homograph_rules": {}}
|
||||
with open(path, encoding="utf-8") as f:
|
||||
source = json.load(f)
|
||||
|
||||
def fixed(x: float) -> int:
|
||||
value = round(x * 10000)
|
||||
if abs(value - x * 10000) > 1e-6:
|
||||
raise ValueError(f"homographs.json: weight {x} has more than four decimals")
|
||||
return value
|
||||
|
||||
words: dict[str, Any] = {}
|
||||
for word, entry in source["words"].items():
|
||||
model = entry["model"]
|
||||
noun_verb = model["kind"] == "noun-verb"
|
||||
if not noun_verb and model["kind"] != "senses":
|
||||
raise ValueError(f"homographs.json: unknown model kind {model['kind']!r}")
|
||||
words[word] = {
|
||||
# sense: [id, role, phones]
|
||||
"senses": [[s["id"], s["role"], s["phones"]] for s in entry["senses"]],
|
||||
# noun-verb: one score for the verb reading; else one score per sense
|
||||
"noun_verb": noun_verb,
|
||||
"bias": [fixed(model["bias"])] if noun_verb else [fixed(b) for b in model["bias"]],
|
||||
"weights": [{k: fixed(v) for k, v in w.items()} for w in ([model["weights"]] if noun_verb else model["weights"])],
|
||||
}
|
||||
# the weights all noun-or-verb homographs share; "" is the bias
|
||||
shared = {k: fixed(v) for k, v in source["pooled"]["weights"].items()}
|
||||
shared[""] = fixed(source["pooled"]["bias"])
|
||||
# word -> [[sense id, [[condition, [words]], ...]], ...], see homograph_rules.txt
|
||||
rules: dict[str, Any] = {}
|
||||
for r in _table_rows(data / "homograph_rules.txt"):
|
||||
conditions = []
|
||||
for part in r[2].split(";"):
|
||||
name, _, listed = part.strip().partition(":")
|
||||
conditions.append([name, listed.split()])
|
||||
rules.setdefault(r[0], []).append([r[1], conditions])
|
||||
return {
|
||||
"homographs": words,
|
||||
"homograph_shared": shared,
|
||||
"homograph_plurals": {base: 1 for base in source.get("plural_bases", ())},
|
||||
"homograph_rules": rules,
|
||||
}
|
||||
|
||||
|
||||
def _load_state(dir_model: Path) -> dict[str, Tensor]:
|
||||
ckpt = torch.load(dir_model / CHECKPOINT, map_location="cpu", weights_only=True)
|
||||
if ckpt.get("format_version") != 4:
|
||||
raise ValueError(f"unsupported tiny-voca checkpoint format {ckpt.get('format_version')}")
|
||||
return ckpt["model"]
|
||||
|
||||
|
||||
def _block_name(name: str) -> tuple[int, str] | None:
|
||||
# "blocks.<i>.<module>.<weight|bias>" -> (i, "blk.<i>.<libllama name>.<weight|bias>")
|
||||
parts = name.split(".")
|
||||
if len(parts) < 4 or parts[0] != "blocks":
|
||||
return None
|
||||
bid = int(parts[1])
|
||||
module, suffix = ".".join(parts[2:-1]), parts[-1]
|
||||
return bid, f"blk.{bid}.{BLOCK_MAP[module]}.{suffix}"
|
||||
|
||||
|
||||
def _block_tensors(new_name: str, t: Tensor) -> Iterable[tuple[str, Tensor]]:
|
||||
# depthwise conv [C, 1, K] -> [C, K], the layout of ggml_ssm_conv
|
||||
if ".ssm_conv1d.weight" in new_name:
|
||||
yield (new_name, t.squeeze(1))
|
||||
return
|
||||
# separate q, k, v: a model that libllama builds from metadata (the mmproj stacks) has no fused qkv
|
||||
if ".attn_qkv." in new_name:
|
||||
for part, chunk in zip(("attn_q", "attn_k", "attn_v"), t.chunk(3, dim=0)):
|
||||
yield (new_name.replace("attn_qkv", part), chunk.contiguous())
|
||||
return
|
||||
yield (new_name, t)
|
||||
|
||||
|
||||
@ModelBase.register("TinyVocaModel")
|
||||
@ModelBase.example("n4ze3m/tiny-voca")
|
||||
class TinyVocaTextModel(TextModel):
|
||||
model_arch = gguf.MODEL_ARCH.TINY_VOCA
|
||||
|
||||
def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]:
|
||||
del remote_hf_model_id
|
||||
state = _load_state(self.dir_model)
|
||||
out: dict[str, Callable[[], Tensor]] = {}
|
||||
for name, t in state.items():
|
||||
if name == "tokens.weight" or name.startswith("encoder."):
|
||||
out[name] = (lambda t=t: t)
|
||||
return out
|
||||
|
||||
def set_vocab(self):
|
||||
config = self.hparams["tiny_voca"]
|
||||
n_vocab = config["model"]["vocab_size"]
|
||||
tokens: list[str] = [""] * n_vocab
|
||||
toktypes = [gguf.TokenType.NORMAL] * n_vocab
|
||||
for text, i in config["vocab"].items():
|
||||
tokens[i] = text
|
||||
if text.startswith("<") and text.endswith(">"):
|
||||
toktypes[i] = gguf.TokenType.CONTROL
|
||||
assert all(tokens)
|
||||
|
||||
# the prompt is split into phonemes by the audio pipeline, see mtmd-helper-gen.cpp
|
||||
self.gguf_writer.add_tokenizer_model("llama")
|
||||
self.gguf_writer.add_tokenizer_pre("default")
|
||||
self.gguf_writer.add_token_list(tokens)
|
||||
self.gguf_writer.add_token_scores([0.0] * n_vocab)
|
||||
self.gguf_writer.add_token_types(toktypes)
|
||||
self.gguf_writer.add_bos_token_id(config["vocab"]["<bos>"])
|
||||
self.gguf_writer.add_eos_token_id(config["vocab"]["<eos>"])
|
||||
self.gguf_writer.add_pad_token_id(config["vocab"]["<pad>"])
|
||||
self.gguf_writer.add_unk_token_id(config["vocab"]["<unk>"])
|
||||
self.gguf_writer.add_add_bos_token(False)
|
||||
self.gguf_writer.add_add_eos_token(False)
|
||||
|
||||
dicts = _g2p_dicts(self.dir_model)
|
||||
if dicts is not None:
|
||||
template_path = Path(__file__).parent.parent / "models" / "templates" / "n4ze3m-tiny-voca-tts.jinja"
|
||||
with open(template_path, encoding="utf-8") as f:
|
||||
self.gguf_writer.add_chat_template([{"name": "tts", "template": f.read()}])
|
||||
self.gguf_writer.add_tts_dicts(dicts)
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
super().set_gguf_parameters()
|
||||
self.gguf_writer.add_causal_attention(False)
|
||||
self.gguf_writer.add_pooling_type(gguf.PoolingType.NONE)
|
||||
|
||||
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
|
||||
del bid
|
||||
if name == "tokens.weight":
|
||||
yield ("token_embd.weight", data_torch)
|
||||
return
|
||||
if name.startswith("encoder.norm."):
|
||||
yield ("output_norm." + name.rsplit(".", 1)[1], data_torch)
|
||||
return
|
||||
res = _block_name(name.removeprefix("encoder."))
|
||||
if res is None:
|
||||
raise ValueError(f"unexpected tensor {name}")
|
||||
yield from _block_tensors(res[1], data_torch)
|
||||
|
||||
def tensor_force_quant(self, name, new_name, bid, n_dims):
|
||||
del name, bid, n_dims
|
||||
# ggml_ssm_conv takes F32 weights; token_embd is also read row by row on the host side
|
||||
if ".ssm_conv1d." in new_name or new_name == "token_embd.weight":
|
||||
return gguf.GGMLQuantizationType.F32
|
||||
return False
|
||||
|
||||
|
||||
@ModelBase.register("TinyVocaModel")
|
||||
@ModelBase.example("n4ze3m/tiny-voca")
|
||||
class TinyVocaMmprojModel(MmprojModel):
|
||||
has_vision_encoder = False
|
||||
has_audio_encoder = False
|
||||
|
||||
def get_audio_config(self) -> dict[str, Any] | None:
|
||||
return self.global_config.get("audio_config")
|
||||
|
||||
def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]:
|
||||
del remote_hf_model_id
|
||||
state = _load_state(self.dir_model)
|
||||
out: dict[str, Callable[[], Tensor]] = {}
|
||||
for name, t in state.items():
|
||||
if name.startswith("encoder.") or name in ("voices.weight", "frame_voices.weight"):
|
||||
continue
|
||||
out[name] = (lambda t=t: t)
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
|
||||
return item
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
c = self.global_config["tiny_voca"]["model"]
|
||||
self.gguf_writer.add_file_type(self.ftype)
|
||||
self.gguf_writer.add_clip_has_gen_audio_encoder(True)
|
||||
self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.TINY_VOCA)
|
||||
self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text)
|
||||
self.gguf_writer.add_gen_audio_embedding_length(c["channels"])
|
||||
self.gguf_writer.add_gen_audio_feed_forward_length(c["feedforward"])
|
||||
self.gguf_writer.add_gen_audio_block_count(c["acoustic_layers"])
|
||||
self.gguf_writer.add_gen_audio_head_count(c["heads"])
|
||||
self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-5)
|
||||
self.gguf_writer.add_gen_audio_default_voice(DEFAULT_VOICE)
|
||||
|
||||
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
|
||||
del bid
|
||||
# from generate_extra_tensors(), named already
|
||||
if name.startswith(("voice.", "a.gen.")):
|
||||
yield (name, data_torch)
|
||||
return
|
||||
stack, _, rest = name.partition(".")
|
||||
if stack in STACK_PREFIX:
|
||||
prefix = STACK_PREFIX[stack]
|
||||
if rest.startswith("norm."):
|
||||
yield (prefix + "output_norm." + rest.rsplit(".", 1)[1], data_torch)
|
||||
return
|
||||
res = _block_name(rest)
|
||||
if res is None:
|
||||
raise ValueError(f"unexpected tensor {name}")
|
||||
yield from _block_tensors(prefix + res[1], data_torch)
|
||||
return
|
||||
module, suffix = name.rsplit(".", 1)
|
||||
if module not in MMPROJ_MAP:
|
||||
raise ValueError(f"unexpected tensor {name}")
|
||||
yield (MMPROJ_MAP[module] + "." + suffix, data_torch)
|
||||
|
||||
def tensor_force_quant(self, name, new_name, bid, n_dims):
|
||||
del name, bid
|
||||
# the blocks of the stacks are loaded by libllama, like the text model
|
||||
if new_name.startswith(tuple(STACK_PREFIX.values())) and ".ssm_conv1d." not in new_name and n_dims >= 2:
|
||||
return False
|
||||
# the rest is small and partly read on the host
|
||||
return gguf.GGMLQuantizationType.F32
|
||||
|
||||
def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
|
||||
# the unknown-word model of dizione (letters -> CMUdict phonemes), run on the host by mtmd_gen_audio_g2p()
|
||||
g2p_dir = self.dir_model / "phonemizer"
|
||||
if (g2p_dir / "g2p.npz").is_file():
|
||||
with open(g2p_dir / "g2p.json", encoding="utf-8") as f:
|
||||
settings = json.load(f)
|
||||
if settings["letters"] != G2P_LETTERS or settings["symbols"] != G2P_SYMBOLS or settings["convs"] != 0 or settings["slots"] != 2:
|
||||
raise ValueError("unsupported g2p model in phonemizer/g2p.json")
|
||||
with np.load(g2p_dir / "g2p.npz") as arrays:
|
||||
for name in arrays.files:
|
||||
yield ("a.gen.g2p." + name.replace("__", "."), torch.from_numpy(arrays[name].astype(np.float32)))
|
||||
config = self.global_config["tiny_voca"]
|
||||
state = _load_state(self.dir_model)
|
||||
# a voice row is the embedding added to the encoder input, then the one added to the frames
|
||||
for i, voice in enumerate(config["voices"]):
|
||||
yield (f"voice.{voice}", torch.cat([state["voices.weight"][i], state["frame_voices.weight"][i]]).float())
|
||||
# class of each token: 0 = pause (special or punctuation), 1 = consonant or <unk>, 2 = vowel
|
||||
vocab = config["vocab"]
|
||||
cls = torch.zeros(len(vocab), dtype=torch.float32)
|
||||
for p in CONSONANTS + ("<unk>",):
|
||||
cls[vocab[p]] = 1.0
|
||||
for p in VOWELS:
|
||||
cls[vocab[p]] = 2.0
|
||||
yield ("a.gen.token_class", cls)
|
||||
|
|
@ -16,6 +16,7 @@ Supported models:
|
|||
- [YuE2](#yue2) (songs)
|
||||
- [MiniMax Music 3](#minimax-music-3) (songs)
|
||||
- [Kokoro](#kokoro)
|
||||
- [tiny-voca](#tiny-voca)
|
||||
|
||||
The sections below list the params supported by each model, with `llama-tts` examples. In `llama-server`, the same options are set with `--tts-lang` and `--tts-voice`, or per request (see the [`/tts` endpoint](../../tools/server/README.md#post-tts-generate-speech-audio-from-text)).
|
||||
|
||||
|
|
@ -423,3 +424,46 @@ python -m nltk.downloader averaged_perceptron_tagger_eng
|
|||
```
|
||||
|
||||
Without them the converter writes no `tts` template, and the prompt must be a phoneme string (as produced by misaki).
|
||||
|
||||
## tiny-voca
|
||||
|
||||
[tiny-voca](https://huggingface.co/n4ze3m/tiny-voca): a 4.5M-parameter English TTS model. A phoneme encoder (the text model), then a duration predictor, two frame transformers and a source-filter synthesizer (in the mmproj).
|
||||
|
||||
Available params:
|
||||
- `--tts-voice` can be `M2` (default) or `F2`
|
||||
- Note: `--tts-speaker-file` is not supported, the model has no voice cloning
|
||||
- Note: sampling params are not used, the model is not autoregressive. `--seed` only changes the noise of the synthesizer
|
||||
- `speed` (`llama-server` only) changes the speaking rate, from `0.25` to `4`; `loudness` is not supported
|
||||
|
||||
Example usage:
|
||||
|
||||
```sh
|
||||
llama-tts -m tiny-voca.gguf \
|
||||
-mm mmproj-tiny-voca.gguf \
|
||||
-p "Hello! The meeting moved to 3:30 pm." \
|
||||
--tts-voice F2 \
|
||||
--output out.wav
|
||||
```
|
||||
|
||||
The model speaks phonemes. The text to phonemes step is the model's `tts` chat template, a port of [dizione](https://github.com/n4ze3m/dizione) (the reference one), with its pronunciation dictionary and tables stored in the model:
|
||||
- the choice of a pronunciation for each word: exceptions and names, the dictionary, function words and their sentence stress, words spelled alike and read differently ("I read it yesterday", "to read"), hyphenated words, capitals read letter by letter, mixed case ("iPhone"), stretched words ("soooo"), accents, chat spellings ("lol", "btw")
|
||||
- a word missing from the dictionary is built from a known word when it can be (endings, prefixes, compounds), else it goes through the unknown-word model of dizione (stored in the mmproj) and its conversion rules
|
||||
- a pronunciation can be given in the text, in CMUdict notation or as phonemes: `Say {HH AH0 L OW1} to Samir{s ə m ˈɪɹ}`
|
||||
- the text rules are ported too: numbers, money, times, dates, telephone numbers, versions, codes, units, fractions, ranges, math signs and comparisons, web addresses and file names, abbreviations, chat spellings
|
||||
|
||||
With `llama-server`, send `"raw_prompt": true` to pass phonemes directly, in the format printed by dizione: symbols separated by spaces, `<sp>` between words, a stress mark (`ˈ` or `ˌ`) before a stressed vowel, e.g. `h ə l ˈoʊ <sp> w ˈɜː l d .`
|
||||
|
||||
Each sentence is spoken as one utterance. The template splits the text as the reference does (before a capital or a figure, not after a title or an initial), ends each sentence with `<eos>`, and adds a full stop when the text ends without a mark. Phonemes without `<eos>` are cut after each `.`, `?`, `!` or `…`, and a sentence without a final mark gets a full stop.
|
||||
|
||||
**Note for GGUF conversion:**
|
||||
|
||||
Convert the root of the repository (it needs `config.json`, `tiny-voca.pt` and `phonemizer/lexicon.tsv`). The other tables of the `tts` template come from the `dizione` python package; without it the converter writes no `tts` template, and the prompt must be phonemes:
|
||||
|
||||
```sh
|
||||
pip install git+https://github.com/n4ze3m/dizione
|
||||
```
|
||||
|
||||
```sh
|
||||
python convert_hf_to_gguf.py path/to/tiny-voca --outfile tiny-voca.gguf
|
||||
python convert_hf_to_gguf.py path/to/tiny-voca --mmproj --outfile mmproj-tiny-voca.gguf
|
||||
```
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ Jinja has no regex support, and exposing `std::regex` / Python `re` would not he
|
|||
|
||||
A third function, `tts_dict(name, key)`, gives the template access to dictionaries stored in the model (e.g. a pronunciation lexicon).
|
||||
|
||||
A fourth one, `tts_g2p(word)`, gives the pronunciation of a word by the letter-to-sound model of the mmproj, when the caller provides one (see below).
|
||||
|
||||
Implementations:
|
||||
- C++: [common/chat-tts-norm.cpp](../common/chat-tts-norm.cpp), injected into task templates by `common_chat_template_render()` in [common/chat.cpp](../common/chat.cpp). They are not available to chat templates.
|
||||
- Python reference: [scripts/chat_tts_norm.py](../scripts/chat_tts_norm.py), for use with `jinja2` (`env.globals["tts_norm_scan"] = chat_tts_norm.tts_norm_scan`)
|
||||
|
|
@ -87,6 +89,17 @@ The lookup is exact: no case folding and no normalization, do them in the templa
|
|||
|
||||
The GGUF lists the names of the dictionaries in `tokenizer.tts_dicts`. Each one is stored as two arrays of strings of the same length: `tokenizer.tts_dict.<name>.keys`, sorted by the UTF-8 bytes of the key, and `tokenizer.tts_dict.<name>.values`. A value is a JSON document (string, number, list, object, ...) and is returned decoded. `GGUFWriter.add_tts_dicts(dicts)` writes all of this.
|
||||
|
||||
### `tts_g2p(word)`
|
||||
|
||||
Pronunciation of `word` by a letter-to-sound model, as phonemes separated by spaces, in the notation of the model (e.g. CMUdict with stress digits for tiny-voca), or `none`. The template converts it to the symbols of the model. It is `none` when the model has no letter-to-sound model, or when the caller gives none: `common_chat_get_tts_prompt()` takes it as an optional callback, `llama-tts` and `llama-server` pass `mtmd_gen_audio_g2p()`. A template must keep working without it, e.g. by spelling the word.
|
||||
|
||||
```jinja
|
||||
{%- set g = tts_g2p(word) -%}
|
||||
{%- if g is none -%}{{ spell(word) }}{%- else -%}{{ from_cmudict(word, g.split(' ')) }}{%- endif -%}
|
||||
```
|
||||
|
||||
There is no Python reference for it: a test passes its own function (`env.globals["tts_g2p"]`).
|
||||
|
||||
## Pattern syntax
|
||||
|
||||
Patterns operate on Unicode codepoints. Invalid UTF-8 bytes (C++ only) are seen as U+FFFD, one per byte, and preserved in the output.
|
||||
|
|
|
|||
|
|
@ -771,6 +771,7 @@ class MODEL_ARCH(IntEnum):
|
|||
POCKETTTS = auto()
|
||||
ZONOS3 = auto()
|
||||
KOKORO = auto()
|
||||
TINY_VOCA = auto()
|
||||
K2HORIZON = auto()
|
||||
KOLIBRI1 = auto()
|
||||
LIMITE = auto()
|
||||
|
|
@ -1758,6 +1759,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
|
|||
MODEL_ARCH.POCKETTTS: "pockettts",
|
||||
MODEL_ARCH.ZONOS3: "zonos3",
|
||||
MODEL_ARCH.KOKORO: "kokoro",
|
||||
MODEL_ARCH.TINY_VOCA: "tiny-voca",
|
||||
MODEL_ARCH.K2HORIZON: "k2-horizon",
|
||||
MODEL_ARCH.KOLIBRI1: "kolibri1",
|
||||
MODEL_ARCH.LIMITE: "limite",
|
||||
|
|
@ -6866,6 +6868,19 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
|
|||
MODEL_TENSOR.FFN_DOWN,
|
||||
MODEL_TENSOR.FFN_UP,
|
||||
],
|
||||
MODEL_ARCH.TINY_VOCA: [
|
||||
MODEL_TENSOR.TOKEN_EMBD,
|
||||
MODEL_TENSOR.OUTPUT_NORM,
|
||||
MODEL_TENSOR.ATTN_NORM,
|
||||
MODEL_TENSOR.ATTN_Q,
|
||||
MODEL_TENSOR.ATTN_K,
|
||||
MODEL_TENSOR.ATTN_V,
|
||||
MODEL_TENSOR.ATTN_OUT,
|
||||
MODEL_TENSOR.FFN_NORM,
|
||||
MODEL_TENSOR.SSM_CONV1D,
|
||||
MODEL_TENSOR.FFN_UP,
|
||||
MODEL_TENSOR.FFN_DOWN,
|
||||
],
|
||||
MODEL_ARCH.KOKORO: [
|
||||
MODEL_TENSOR.TOKEN_EMBD,
|
||||
MODEL_TENSOR.TOKEN_EMBD_NORM,
|
||||
|
|
@ -7356,6 +7371,7 @@ class VisionProjectorType:
|
|||
FISH_S2_GEN = "fish_s2_gen" # audio generation: fast AR code predictor + Fish DAC decoder
|
||||
FISH_S2_SPKENC = "fish_s2_spkenc" # audio: Fish DAC encoder + RVQ, reference clip -> prompt rows
|
||||
KOKORO = "kokoro" # audio generation: StyleTTS2 prosody predictor + iSTFTNet decoder
|
||||
TINY_VOCA = "tiny_voca" # audio generation: duration predictor, frame transformers, source-filter vocoder
|
||||
HUNYUANVL = "hunyuanvl"
|
||||
PARAKEET = "parakeet" # audio
|
||||
MINIMAXM3 = "minimax_m3"
|
||||
|
|
|
|||
2672
models/templates/n4ze3m-tiny-voca-tts.jinja
Normal file
2672
models/templates/n4ze3m-tiny-voca-tts.jinja
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -177,6 +177,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
|
|||
{ LLM_ARCH_POCKETTTS, "pockettts" },
|
||||
{ LLM_ARCH_ZONOS3, "zonos3" },
|
||||
{ LLM_ARCH_KOKORO, "kokoro" },
|
||||
{ LLM_ARCH_TINY_VOCA, "tiny-voca" },
|
||||
{ LLM_ARCH_K2_HORIZON, "k2-horizon" },
|
||||
{ LLM_ARCH_BEAM, "beam" },
|
||||
{ LLM_ARCH_KOLIBRI1, "kolibri1" },
|
||||
|
|
|
|||
|
|
@ -178,6 +178,7 @@ enum llm_arch {
|
|||
LLM_ARCH_POCKETTTS,
|
||||
LLM_ARCH_ZONOS3,
|
||||
LLM_ARCH_KOKORO,
|
||||
LLM_ARCH_TINY_VOCA,
|
||||
LLM_ARCH_MINIMAX_01,
|
||||
LLM_ARCH_HRM_TEXT,
|
||||
LLM_ARCH_K2_HORIZON,
|
||||
|
|
|
|||
|
|
@ -130,6 +130,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params
|
|||
return new llama_model_zonos3(params);
|
||||
case LLM_ARCH_KOKORO:
|
||||
return new llama_model_kokoro(params);
|
||||
case LLM_ARCH_TINY_VOCA:
|
||||
return new llama_model_tiny_voca(params);
|
||||
case LLM_ARCH_PHI2:
|
||||
return new llama_model_phi2(params);
|
||||
case LLM_ARCH_PHI3:
|
||||
|
|
@ -2990,6 +2992,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,
|
|||
case LLM_ARCH_RND1:
|
||||
case LLM_ARCH_CLEF:
|
||||
case LLM_ARCH_KOKORO:
|
||||
case LLM_ARCH_TINY_VOCA:
|
||||
{
|
||||
res = nullptr;
|
||||
} break;
|
||||
|
|
@ -3774,6 +3777,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) {
|
|||
case LLM_ARCH_POCKETTTS:
|
||||
case LLM_ARCH_ZONOS3:
|
||||
case LLM_ARCH_LIMITE:
|
||||
case LLM_ARCH_TINY_VOCA:
|
||||
return LLAMA_ROPE_TYPE_NORM;
|
||||
case LLM_ARCH_BAILINGMOE3:
|
||||
// VL files carry mrope sections; text-only files keep NORM rope
|
||||
|
|
|
|||
|
|
@ -785,6 +785,18 @@ struct llama_model_kokoro : public llama_model_base {
|
|||
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
|
||||
};
|
||||
|
||||
struct llama_model_tiny_voca : public llama_model_base {
|
||||
llama_model_tiny_voca(const struct llama_model_params & params) : llama_model_base(params) {}
|
||||
void load_arch_hparams(llama_model_loader & ml) override;
|
||||
void load_arch_tensors(llama_model_loader & ml) override;
|
||||
|
||||
struct graph : public llm_graph_context {
|
||||
graph(const llm_graph_params & params);
|
||||
};
|
||||
|
||||
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
|
||||
};
|
||||
|
||||
struct llama_model_zonos3 : public llama_model_base {
|
||||
llama_model_zonos3(const struct llama_model_params & params) : llama_model_base(params) {}
|
||||
void load_arch_hparams(llama_model_loader & ml) override;
|
||||
|
|
|
|||
171
src/models/tiny-voca.cpp
Normal file
171
src/models/tiny-voca.cpp
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
#include "models.h"
|
||||
|
||||
#include <map>
|
||||
|
||||
// one transformer stack of the tiny-voca TTS model, bidirectional, no KV cache
|
||||
// - the text model is the phoneme encoder, its input rows are built by the audio pipeline (token + stress + voice)
|
||||
// - mtmd runs the prosody and acoustic stacks of the mmproj with this arch too
|
||||
// block: x + attn(LN(x)), then x + up/down(gelu(dwconv(LN(x)))), LN at the end
|
||||
|
||||
void llama_model_tiny_voca::load_arch_hparams(llama_model_loader & ml) {
|
||||
ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
|
||||
|
||||
type = LLM_TYPE_UNKNOWN;
|
||||
}
|
||||
|
||||
void llama_model_tiny_voca::load_arch_tensors(llama_model_loader & ml) {
|
||||
LLAMA_LOAD_LOCALS;
|
||||
GGML_UNUSED(ml);
|
||||
|
||||
tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
|
||||
|
||||
output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
|
||||
output_norm_b = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, 0);
|
||||
|
||||
// no output head, the logits are unused; reuse the embedding table so a sampler can still run
|
||||
output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
|
||||
|
||||
for (int i = 0; i < n_layer; ++i) {
|
||||
auto & layer = layers[i];
|
||||
|
||||
layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
|
||||
layer.attn_norm_b = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, 0);
|
||||
|
||||
create_tensor_qkv(layer, i, n_embd, n_embd, n_embd_gqa, n_embd_gqa, 0);
|
||||
|
||||
layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
|
||||
layer.wo_b = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, 0);
|
||||
|
||||
layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
|
||||
layer.ffn_norm_b = create_tensor(tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, 0);
|
||||
|
||||
// depthwise conv over time, 7 taps
|
||||
layer.ssm_conv1d = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {7, n_embd}, 0);
|
||||
layer.ssm_conv1d_b = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {n_embd}, 0);
|
||||
|
||||
layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
|
||||
layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0);
|
||||
layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
|
||||
layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// row of each tap of the depthwise conv: for token t and tap k, the token of the same sequence at pos(t) + k - pad,
|
||||
// or the zero row n_tokens past the edges, so sequences that share a ubatch do not mix
|
||||
class llm_graph_input_tiny_voca_conv : public llm_graph_input_i {
|
||||
public:
|
||||
llm_graph_input_tiny_voca_conv(int d_conv) : d_conv(d_conv) {}
|
||||
virtual ~llm_graph_input_tiny_voca_conv() = default;
|
||||
|
||||
void set_input(const llama_ubatch * ubatch) override {
|
||||
const int64_t n_tokens = ubatch->n_tokens;
|
||||
const int pad = (d_conv - 1) / 2;
|
||||
GGML_ASSERT(ubatch->pos && ubatch->seq_id);
|
||||
std::map<std::pair<llama_seq_id, llama_pos>, int32_t> row_of;
|
||||
for (int64_t i = 0; i < n_tokens; ++i) {
|
||||
row_of[{ ubatch->seq_id[i][0], ubatch->pos[i] }] = (int32_t) i;
|
||||
}
|
||||
std::vector<int32_t> rows((size_t) n_tokens * d_conv);
|
||||
for (int64_t i = 0; i < n_tokens; ++i) {
|
||||
for (int k = 0; k < d_conv; ++k) {
|
||||
const auto it = row_of.find({ ubatch->seq_id[i][0], ubatch->pos[i] + k - pad });
|
||||
rows[i * d_conv + k] = it == row_of.end() ? (int32_t) n_tokens : it->second;
|
||||
}
|
||||
}
|
||||
ggml_backend_tensor_set(idx, rows.data(), 0, ggml_nbytes(idx));
|
||||
}
|
||||
|
||||
ggml_tensor * idx = nullptr; // I32 [d_conv * n_tokens]
|
||||
const int d_conv;
|
||||
};
|
||||
|
||||
std::unique_ptr<llm_graph_context> llama_model_tiny_voca::build_arch_graph(const llm_graph_params & params) const {
|
||||
return std::make_unique<graph>(params);
|
||||
}
|
||||
|
||||
llama_model_tiny_voca::graph::graph(const llm_graph_params & params) : llm_graph_context(params) {
|
||||
const int64_t n_embd_head = hparams.n_embd_head_v();
|
||||
|
||||
GGML_ASSERT(n_embd_head == hparams.n_embd_head_k());
|
||||
ggml_tensor * cur;
|
||||
ggml_tensor * inpL = build_inp_embd(model.tok_embd);
|
||||
|
||||
ggml_tensor * inp_pos = build_inp_pos();
|
||||
|
||||
auto * inp_attn = build_attn_inp_no_cache();
|
||||
|
||||
ggml_tensor * inp_out_ids = build_inp_out_ids();
|
||||
|
||||
const int d_conv = (int) model.layers[0].ssm_conv1d->ne[0];
|
||||
auto inp_conv = std::make_unique<llm_graph_input_tiny_voca_conv>(d_conv);
|
||||
inp_conv->idx = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, (int64_t) d_conv * n_tokens);
|
||||
ggml_set_input(inp_conv->idx);
|
||||
ggml_tensor * conv_idx = inp_conv->idx;
|
||||
res->add_input(std::move(inp_conv));
|
||||
|
||||
for (int il = 0; il < n_layer; ++il) {
|
||||
const auto & layer = model.layers[il];
|
||||
|
||||
cur = build_norm(inpL, layer.attn_norm, layer.attn_norm_b, LLM_NORM, il);
|
||||
cb(cur, "attn_norm", il);
|
||||
|
||||
{
|
||||
auto [Qcur, Kcur, Vcur] = build_qkv(layer, cur, n_embd_head, n_head, n_head_kv, il);
|
||||
|
||||
Qcur = build_rope(Qcur, inp_pos, il);
|
||||
Kcur = build_rope(Kcur, inp_pos, il);
|
||||
|
||||
cb(Qcur, "Qcur", il);
|
||||
cb(Kcur, "Kcur", il);
|
||||
cb(Vcur, "Vcur", il);
|
||||
|
||||
cur = build_attn(inp_attn,
|
||||
layer.wo, layer.wo_b, layer.wo_s,
|
||||
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
|
||||
cb(cur, "kqv_out", il);
|
||||
}
|
||||
|
||||
ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
|
||||
cb(ffn_inp, "ffn_inp", il);
|
||||
|
||||
cur = build_norm(ffn_inp, layer.ffn_norm, layer.ffn_norm_b, LLM_NORM, il);
|
||||
cb(cur, "ffn_norm", il);
|
||||
|
||||
// same-length depthwise conv over the positions of each sequence: gather the taps, weight them, sum
|
||||
{
|
||||
ggml_tensor * x = ggml_pad(ctx0, cur, 0, 1, 0, 0); // [n_embd, n_tokens + 1], last row 0
|
||||
x = ggml_get_rows(ctx0, x, conv_idx); // [n_embd, d_conv * n_tokens]
|
||||
x = ggml_reshape_3d(ctx0, x, n_embd, d_conv, n_tokens);
|
||||
ggml_tensor * w = ggml_cont(ctx0, ggml_transpose(ctx0, layer.ssm_conv1d)); // [n_embd, d_conv]
|
||||
x = ggml_mul(ctx0, x, ggml_reshape_3d(ctx0, w, n_embd, d_conv, 1));
|
||||
x = ggml_sum_rows(ctx0, ggml_cont(ctx0, ggml_permute(ctx0, x, 1, 0, 2, 3))); // [1, n_embd, n_tokens]
|
||||
cur = ggml_add(ctx0, ggml_reshape_2d(ctx0, x, n_embd, n_tokens), layer.ssm_conv1d_b);
|
||||
cb(cur, "dwconv", il);
|
||||
}
|
||||
|
||||
cur = build_ffn(cur,
|
||||
layer.ffn_up, layer.ffn_up_b, NULL,
|
||||
NULL, NULL, NULL,
|
||||
layer.ffn_down, layer.ffn_down_b, NULL, NULL,
|
||||
LLM_FFN_GELU_ERF, LLM_FFN_SEQ, il);
|
||||
cb(cur, "ffn_out", il);
|
||||
|
||||
cur = ggml_add(ctx0, cur, ffn_inp);
|
||||
|
||||
inpL = cur;
|
||||
}
|
||||
|
||||
cur = build_norm(inpL, model.output_norm, model.output_norm_b, LLM_NORM, -1);
|
||||
|
||||
if (inp_out_ids) {
|
||||
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
|
||||
}
|
||||
|
||||
cb(cur, "result_embd", -1);
|
||||
res->t_embd = cur;
|
||||
|
||||
cur = build_lora_mm(model.output, cur);
|
||||
|
||||
cb(cur, "result_output", -1);
|
||||
res->t_logits = cur;
|
||||
}
|
||||
|
|
@ -1184,7 +1184,7 @@ static bool arch_supported(const llm_arch arch) {
|
|||
arch == LLM_ARCH_NEO_BERT || arch == LLM_ARCH_JINA_BERT_V2 || arch == LLM_ARCH_JINA_BERT_V3 || arch == LLM_ARCH_EUROBERT) {
|
||||
return false; // TODO vocab
|
||||
}
|
||||
if (arch == LLM_ARCH_KOKORO) {
|
||||
if (arch == LLM_ARCH_KOKORO || arch == LLM_ARCH_TINY_VOCA) {
|
||||
return false; // TODO encoder without memory, a sequence must fit in one ubatch
|
||||
}
|
||||
if (arch == LLM_ARCH_PLM) {
|
||||
|
|
|
|||
|
|
@ -96,6 +96,7 @@ add_library(mtmd
|
|||
models/pockettts-gen.cpp
|
||||
models/soprano.cpp
|
||||
models/kokoro.cpp
|
||||
models/tiny-voca.cpp
|
||||
models/step3vl.cpp
|
||||
models/siglip.cpp
|
||||
models/whisper-enc.cpp
|
||||
|
|
|
|||
|
|
@ -780,6 +780,52 @@ struct mtmd_graph_music3_gen : mtmd_graph_snake_vae {
|
|||
ggml_cgraph * build_vocoder();
|
||||
};
|
||||
|
||||
// tiny-voca: small graphs around the stacks, the stacks run on libllama (see mtmd_gen_wav_tiny_voca())
|
||||
// LATENT_IN: token states [n_embd, n_rows] -> duration outputs [2, n_rows]
|
||||
// LATENT_OUT: acoustic states [n_embd, n_rows] -> source-filter params [n_voc, n_rows]
|
||||
struct mtmd_graph_tiny_voca : mtmd_graph {
|
||||
mtmd_graph_tiny_voca(mtmd_subcontext * ctx, const mtmd_image_f32 & img, mtmd_subctx_gen_process gen_process, int n_rows)
|
||||
: mtmd_graph(ctx, img), gen_process(gen_process), n_rows(n_rows) {}
|
||||
ggml_cgraph * build() override;
|
||||
|
||||
static constexpr int n_prosody_layer = 2;
|
||||
static constexpr int n_acoustic_layer = 5;
|
||||
static constexpr int n_max_frames = 3000;
|
||||
static constexpr int hop = 256; // samples per frame
|
||||
static constexpr int n_cep_causal = 80;
|
||||
static constexpr int n_cep_anti = 16;
|
||||
static constexpr int n_noise_cep = 32;
|
||||
static constexpr int harm_fft = 512;
|
||||
static constexpr int harm_hop = 128;
|
||||
static constexpr int harm_steps = hop / harm_hop;
|
||||
static constexpr int noise_fft = 256;
|
||||
static constexpr int noise_hop = 64;
|
||||
static constexpr int noise_steps = hop / noise_hop;
|
||||
static constexpr int n_voc = n_cep_causal + n_cep_anti + harm_steps + n_noise_cep + noise_steps;
|
||||
static constexpr float rope_theta = 10000.0f;
|
||||
static constexpr float sample_rate = 24000.0f;
|
||||
static constexpr float harmonic_limit = 0.47f; // highest harmonic, relative to the sample rate
|
||||
static constexpr float f0_ref = 200.0f; // Hz, log F0 is predicted relative to it
|
||||
static constexpr float f0_min = 50.0f;
|
||||
static constexpr float f0_max = 600.0f;
|
||||
static constexpr float max_dur = 400.0f; // frames per token before the speed
|
||||
|
||||
mtmd_subctx_gen_process gen_process;
|
||||
int n_rows;
|
||||
|
||||
// host: frame params [n_frames, n_voc] and F0 [n_frames] in Hz -> waveform [n_frames * hop]
|
||||
static void synth(const std::vector<float> & voc, const std::vector<float> & f0, std::mt19937 & rng, std::vector<float> & audio);
|
||||
|
||||
// unknown-word model: letters (a-z and ') -> CMUdict phonemes separated by spaces, other characters are skipped
|
||||
static constexpr int n_g2p_slot = 2; // positions per letter
|
||||
static constexpr int n_g2p_letter = 27;
|
||||
static constexpr int n_g2p_symbol = 69;
|
||||
static std::string g2p(const mtmd_tiny_voca & tv, const std::string & word);
|
||||
|
||||
private:
|
||||
ggml_tensor * conv3(ggml_tensor * x, ggml_tensor * w, ggml_tensor * b) const;
|
||||
};
|
||||
|
||||
struct mtmd_graph_soprano : mtmd_graph {
|
||||
mtmd_graph_soprano(mtmd_subcontext * ctx, const mtmd_image_f32 & img, int n_frames) : mtmd_graph(ctx, img), n_frames(n_frames) {}
|
||||
ggml_cgraph * build() override;
|
||||
|
|
|
|||
307
tools/mtmd/models/tiny-voca.cpp
Normal file
307
tools/mtmd/models/tiny-voca.cpp
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
#include "models.h"
|
||||
#include "../mtmd-audio.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
// same-length conv with 3 taps; x: [T, IC], w: [3, IC, OC], returns [T, OC]
|
||||
ggml_tensor * mtmd_graph_tiny_voca::conv3(ggml_tensor * x, ggml_tensor * w, ggml_tensor * b) const {
|
||||
ggml_tensor * col = ggml_im2col(ctx0, w, x, 1, 0, 1, 0, 1, 0, false, GGML_TYPE_F32);
|
||||
ggml_tensor * y = ggml_mul_mat(ctx0,
|
||||
ggml_reshape_2d(ctx0, col, col->ne[0], col->ne[1] * col->ne[2]),
|
||||
ggml_reshape_2d(ctx0, w, w->ne[0] * w->ne[1], w->ne[2]));
|
||||
return ggml_add(ctx0, y, ggml_reshape_2d(ctx0, b, 1, b->ne[0]));
|
||||
}
|
||||
|
||||
ggml_cgraph * mtmd_graph_tiny_voca::build() {
|
||||
const auto & tv = model.tiny_voca;
|
||||
|
||||
ggml_tensor * inp = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, hparams.n_embd, n_rows);
|
||||
ggml_set_name(inp, "inp_feats");
|
||||
ggml_set_input(inp);
|
||||
|
||||
ggml_tensor * cur;
|
||||
if (gen_process == MTMD_SUBCTX_GEN_PROCESS_LATENT_IN) {
|
||||
// duration predictor: (conv, gelu, layer norm) x 2, then a linear layer
|
||||
cur = ggml_cont(ctx0, ggml_transpose(ctx0, inp));
|
||||
cur = conv3(cur, tv.dur_conv1_w, tv.dur_conv1_b);
|
||||
cur = ggml_gelu_erf(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)));
|
||||
cur = build_norm(cur, tv.dur_norm1_w, tv.dur_norm1_b, NORM_TYPE_NORMAL, eps, -1);
|
||||
cur = conv3(ggml_cont(ctx0, ggml_transpose(ctx0, cur)), tv.dur_conv2_w, tv.dur_conv2_b);
|
||||
cur = ggml_gelu_erf(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)));
|
||||
cur = build_norm(cur, tv.dur_norm2_w, tv.dur_norm2_b, NORM_TYPE_NORMAL, eps, -1);
|
||||
cur = ggml_add(ctx0, build_mm(tv.dur_out_w, cur), tv.dur_out_b);
|
||||
} else {
|
||||
GGML_ASSERT(gen_process == MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT);
|
||||
ggml_tensor * h = ggml_add(ctx0, build_mm(tv.harm_w, inp), tv.harm_b);
|
||||
ggml_tensor * n = ggml_add(ctx0, build_mm(tv.noise_w, inp), tv.noise_b);
|
||||
cur = ggml_concat(ctx0, h, n, 0);
|
||||
}
|
||||
ggml_set_name(cur, "out_feats");
|
||||
ggml_set_output(cur);
|
||||
ggml_build_forward_expand(gf, cur);
|
||||
return gf;
|
||||
}
|
||||
|
||||
//
|
||||
// host: harmonic plus noise synthesis, see SourceFilter in the reference (model.py)
|
||||
//
|
||||
|
||||
// band-limited pulse train with unit power, F0 given per frame and interpolated in the log domain
|
||||
static void tiny_voca_pulse_train(const std::vector<float> & f0, std::vector<float> & out) {
|
||||
using g = mtmd_graph_tiny_voca;
|
||||
const int64_t n_frames = (int64_t) f0.size();
|
||||
std::vector<double> knots(n_frames + 1);
|
||||
for (int64_t i = 0; i < n_frames; i++) {
|
||||
knots[i] = std::log(std::max((double) f0[i], 1.0));
|
||||
}
|
||||
knots[n_frames] = knots[n_frames - 1];
|
||||
|
||||
out.resize((size_t) (n_frames * g::hop));
|
||||
double acc = 0.0;
|
||||
for (int64_t n = 0; n < n_frames * g::hop; n++) {
|
||||
const int64_t low = n / g::hop;
|
||||
const double w = (double) (n - low * g::hop) / g::hop;
|
||||
const double freq = std::exp(knots[low] * (1.0 - w) + knots[low + 1] * w);
|
||||
acc += freq / g::sample_rate;
|
||||
const double theta = std::fmod(2.0 * M_PI * acc, 2.0 * M_PI);
|
||||
const double harmonics = std::max((double) g::harmonic_limit * g::sample_rate / freq, 1.0);
|
||||
const double whole = std::floor(harmonics);
|
||||
const double denom = 2.0 * std::sin(theta / 2.0);
|
||||
const double core = std::fabs(denom) < 1e-7 ? whole : std::sin((whole + 0.5) * theta) / denom - 0.5;
|
||||
const double wave = core + (harmonics - whole) * std::cos((whole + 1.0) * theta);
|
||||
out[n] = (float) (wave * std::sqrt(2.0 / harmonics));
|
||||
}
|
||||
}
|
||||
|
||||
// time-varying filter: STFT of the source (center, zero padding), times exp(rfft(cepstrum)) of each frame, ISTFT
|
||||
// cep(j, buf) writes the n_fft cepstrum of STFT frame j, the source gets n_fft / 2 trailing zeros first
|
||||
static void tiny_voca_filter(const std::vector<float> & src, int n_fft, int hop,
|
||||
const std::function<void(int64_t, float *)> & cep, std::vector<float> & out) {
|
||||
const int n_bins = n_fft / 2 + 1;
|
||||
const int64_t n_src = (int64_t) src.size();
|
||||
const int64_t n_pad = n_src + n_fft / 2; // length given to the STFT
|
||||
const int64_t n_stft = 1 + n_pad / hop; // frames, center = true
|
||||
const int64_t n_full = n_pad + n_fft; // with the center padding
|
||||
|
||||
mtmd_audio_cache cache;
|
||||
cache.fill_sin_cos_table(n_fft);
|
||||
cache.fill_hann_window(n_fft, true);
|
||||
const float * win = cache.hann_window.data();
|
||||
|
||||
std::vector<float> x((size_t) n_full, 0.0f);
|
||||
std::copy(src.begin(), src.end(), x.begin() + n_fft / 2);
|
||||
|
||||
std::vector<float> ola((size_t) n_full, 0.0f), env((size_t) n_full, 0.0f);
|
||||
std::vector<float> fin(8 * n_fft), fout(8 * n_fft), rin(8 * n_fft), rout(8 * n_fft), cbuf(n_fft);
|
||||
std::vector<float> resp(2 * n_bins);
|
||||
for (int64_t j = 0; j < n_stft; j++) {
|
||||
// response of this frame
|
||||
std::fill(cbuf.begin(), cbuf.end(), 0.0f);
|
||||
cep(j, cbuf.data());
|
||||
std::copy(cbuf.begin(), cbuf.end(), rin.begin());
|
||||
mtmd_audio_fft(cache, rin.data(), n_fft, rout.data());
|
||||
for (int k = 0; k < n_bins; k++) {
|
||||
const float mag = std::exp(std::clamp(rout[2 * k], -14.0f, 6.0f));
|
||||
resp[2 * k + 0] = mag * std::cos(rout[2 * k + 1]);
|
||||
resp[2 * k + 1] = mag * std::sin(rout[2 * k + 1]);
|
||||
}
|
||||
|
||||
// spectrum of the source frame
|
||||
const float * seg = x.data() + j * hop;
|
||||
for (int i = 0; i < n_fft; i++) {
|
||||
fin[i] = seg[i] * win[i];
|
||||
}
|
||||
mtmd_audio_fft(cache, fin.data(), n_fft, fout.data());
|
||||
|
||||
// filtered spectrum, mirrored for the complex inverse FFT; irfft ignores the imaginary parts of DC and Nyquist
|
||||
for (int k = 0; k < n_bins; k++) {
|
||||
const float a = fout[2 * k], b = fout[2 * k + 1];
|
||||
const float c = resp[2 * k], d = resp[2 * k + 1];
|
||||
rin[2 * k + 0] = a * c - b * d;
|
||||
rin[2 * k + 1] = (k == 0 || k == n_fft / 2) ? 0.0f : a * d + b * c;
|
||||
}
|
||||
for (int k = 1; k < n_fft - n_bins + 1; k++) {
|
||||
rin[2 * (n_fft - k) + 0] = rin[2 * k + 0];
|
||||
rin[2 * (n_fft - k) + 1] = -rin[2 * k + 1];
|
||||
}
|
||||
mtmd_audio_ifft(cache, rin.data(), n_fft, rout.data());
|
||||
|
||||
float * o = ola.data() + j * hop;
|
||||
float * e = env.data() + j * hop;
|
||||
for (int i = 0; i < n_fft; i++) {
|
||||
o[i] += rout[2 * i] * win[i];
|
||||
e[i] += win[i] * win[i];
|
||||
}
|
||||
}
|
||||
|
||||
out.resize((size_t) n_src);
|
||||
for (int64_t i = 0; i < n_src; i++) {
|
||||
const int64_t k = i + n_fft / 2; // drop the center padding
|
||||
out[i] = env[k] > 1e-11f ? ola[k] / env[k] : 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
void mtmd_graph_tiny_voca::synth(const std::vector<float> & voc, const std::vector<float> & f0, std::mt19937 & rng, std::vector<float> & audio) {
|
||||
const int64_t n_frames = (int64_t) f0.size();
|
||||
GGML_ASSERT(n_frames > 0 && voc.size() == (size_t) (n_frames * n_voc));
|
||||
|
||||
// liftering: coefficient i scaled by 1 / (1 + i / 4), the gain (coefficient 0) by 2
|
||||
auto lifter = [](int i, int first) { return i == 0 && first == 0 ? 2.0f : 1.0f / (1.0f + (float) (i + first) / 4.0f); };
|
||||
|
||||
// harmonic branch: envelope interpolated between frames, one gain per sub-frame
|
||||
const int split = n_cep_causal + n_cep_anti;
|
||||
auto harm_cep = [&](int64_t j, float * buf) {
|
||||
const int64_t s = std::min(j, harm_steps * n_frames - 1);
|
||||
const float * here = voc.data() + (s / harm_steps) * n_voc;
|
||||
const float * next = voc.data() + std::min((s + 1) / harm_steps, n_frames - 1) * n_voc;
|
||||
for (int i = 0; i < n_cep_causal; i++) {
|
||||
buf[i] = 0.5f * (here[i] + next[i]) * lifter(i, 0);
|
||||
}
|
||||
buf[0] += here[split + s % harm_steps];
|
||||
for (int i = 0; i < n_cep_anti; i++) {
|
||||
buf[harm_fft - 1 - i] = 0.5f * (here[n_cep_causal + i] + next[n_cep_causal + i]) * lifter(i, 1);
|
||||
}
|
||||
};
|
||||
// noise branch: one envelope per frame, one gain per sub-frame
|
||||
auto noise_cep = [&](int64_t j, float * buf) {
|
||||
const int64_t s = std::min(j, noise_steps * n_frames - 1);
|
||||
const float * row = voc.data() + (s / noise_steps) * n_voc + split + harm_steps;
|
||||
for (int i = 0; i < n_noise_cep; i++) {
|
||||
buf[i] = row[i] * lifter(i, 0);
|
||||
}
|
||||
buf[0] += row[n_noise_cep + s % noise_steps];
|
||||
};
|
||||
|
||||
std::vector<float> pulses, noise((size_t) (n_frames * hop)), harm_out, noise_out;
|
||||
tiny_voca_pulse_train(f0, pulses);
|
||||
std::normal_distribution<float> dist(0.0f, 1.0f);
|
||||
for (auto & v : noise) {
|
||||
v = dist(rng);
|
||||
}
|
||||
tiny_voca_filter(pulses, harm_fft, harm_hop, harm_cep, harm_out);
|
||||
tiny_voca_filter(noise, noise_fft, noise_hop, noise_cep, noise_out);
|
||||
|
||||
audio.resize(pulses.size());
|
||||
for (size_t i = 0; i < audio.size(); i++) {
|
||||
audio[i] = harm_out[i] + noise_out[i];
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// host: unknown-word model of the phonemizer, see g2p.py of dizione
|
||||
//
|
||||
|
||||
static const char * const tiny_voca_g2p_letters = "abcdefghijklmnopqrstuvwxyz'";
|
||||
static const char * const tiny_voca_g2p_symbols[mtmd_graph_tiny_voca::n_g2p_symbol] = {
|
||||
"AA0", "AA1", "AA2", "AE0", "AE1", "AE2", "AH0", "AH1", "AH2", "AO0", "AO1", "AO2", "AW0", "AW1", "AW2", "AY0", "AY1", "AY2",
|
||||
"B", "CH", "D", "DH", "EH0", "EH1", "EH2", "ER0", "ER1", "ER2", "EY0", "EY1", "EY2", "F", "G", "HH",
|
||||
"IH0", "IH1", "IH2", "IY0", "IY1", "IY2", "JH", "K", "L", "M", "N", "NG", "OW0", "OW1", "OW2", "OY0", "OY1", "OY2",
|
||||
"P", "R", "S", "SH", "T", "TH", "UH0", "UH1", "UH2", "UW0", "UW1", "UW2", "V", "W", "Y", "Z", "ZH",
|
||||
};
|
||||
|
||||
// one direction of a GRU layer over x [n, n_in] -> y [n, n_hidden], written at column offset of rows of width stride
|
||||
// the products are summed in double and rounded once, as close as can be to the reference (numpy, float32): two
|
||||
// symbols are sometimes almost as likely, and the order of a float32 sum would decide between them
|
||||
static void tiny_voca_gru(const mtmd_tiny_voca::g2p_gru & g, const std::vector<float> & x, int64_t n, int64_t n_in, int64_t n_hidden,
|
||||
bool reverse, std::vector<float> & y, int64_t offset, int64_t stride) {
|
||||
const int64_t h3 = 3 * n_hidden;
|
||||
std::vector<float> inp((size_t) (n * h3));
|
||||
for (int64_t t = 0; t < n; t++) {
|
||||
for (int64_t r = 0; r < h3; r++) {
|
||||
const float * w = g.w_ih.data() + r * n_in;
|
||||
const float * xt = x.data() + t * n_in;
|
||||
double acc = 0.0;
|
||||
for (int64_t c = 0; c < n_in; c++) {
|
||||
acc += (double) w[c] * xt[c];
|
||||
}
|
||||
inp[t * h3 + r] = (float) acc + g.b_ih[r];
|
||||
}
|
||||
}
|
||||
std::vector<float> state((size_t) n_hidden, 0.0f), rec((size_t) h3);
|
||||
for (int64_t s = 0; s < n; s++) {
|
||||
const int64_t t = reverse ? n - 1 - s : s;
|
||||
for (int64_t r = 0; r < h3; r++) {
|
||||
const float * w = g.w_hh.data() + r * n_hidden;
|
||||
double acc = 0.0;
|
||||
for (int64_t c = 0; c < n_hidden; c++) {
|
||||
acc += (double) w[c] * state[c];
|
||||
}
|
||||
rec[r] = (float) acc + g.b_hh[r];
|
||||
}
|
||||
const float * in = inp.data() + t * h3;
|
||||
for (int64_t k = 0; k < n_hidden; k++) {
|
||||
const float reset = 1.0f / (1.0f + std::exp(-(in[k] + rec[k])));
|
||||
const float update = 1.0f / (1.0f + std::exp(-(in[n_hidden + k] + rec[n_hidden + k])));
|
||||
const float cand = std::tanh(in[2 * n_hidden + k] + reset * rec[2 * n_hidden + k]);
|
||||
state[k] = (1.0f - update) * cand + update * state[k];
|
||||
}
|
||||
std::copy(state.begin(), state.end(), y.begin() + t * stride + offset);
|
||||
}
|
||||
}
|
||||
|
||||
std::string mtmd_graph_tiny_voca::g2p(const mtmd_tiny_voca & tv, const std::string & word) {
|
||||
const int64_t w = tv.g2p_n_width;
|
||||
const int64_t h = tv.g2p_n_hidden;
|
||||
if (w == 0 || tv.g2p_layers.empty()) {
|
||||
return "";
|
||||
}
|
||||
std::vector<int> ids;
|
||||
for (char c : word) {
|
||||
const char * p = strchr(tiny_voca_g2p_letters, std::tolower((unsigned char) c));
|
||||
if (c != '\0' && p) {
|
||||
ids.push_back((int) (p - tiny_voca_g2p_letters) + 1);
|
||||
}
|
||||
}
|
||||
if (ids.empty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// each letter takes n_g2p_slot positions: its embedding plus the embedding of the slot
|
||||
const int64_t n = (int64_t) ids.size() * n_g2p_slot;
|
||||
std::vector<float> x((size_t) (n * w));
|
||||
for (size_t l = 0; l < ids.size(); l++) {
|
||||
for (int s = 0; s < n_g2p_slot; s++) {
|
||||
float * row = x.data() + ((int64_t) l * n_g2p_slot + s) * w;
|
||||
for (int64_t c = 0; c < w; c++) {
|
||||
row[c] = tv.g2p_embd[ids[l] * w + c] + tv.g2p_slot[s * w + c];
|
||||
}
|
||||
}
|
||||
}
|
||||
int64_t n_in = w;
|
||||
for (size_t il = 0; il + 1 < tv.g2p_layers.size(); il += 2) {
|
||||
std::vector<float> y((size_t) (n * 2 * h));
|
||||
tiny_voca_gru(tv.g2p_layers[il], x, n, n_in, h, false, y, 0, 2 * h);
|
||||
tiny_voca_gru(tv.g2p_layers[il + 1], x, n, n_in, h, true, y, h, 2 * h);
|
||||
x = std::move(y);
|
||||
n_in = 2 * h;
|
||||
}
|
||||
|
||||
// CTC, read greedily: a label repeated or the blank (0) is no new symbol
|
||||
std::string out;
|
||||
int prev = 0;
|
||||
for (int64_t t = 0; t < n; t++) {
|
||||
int best = 0;
|
||||
float best_v = -INFINITY;
|
||||
for (int k = 0; k <= n_g2p_symbol; k++) {
|
||||
const float * wr = tv.g2p_out_w.data() + k * n_in;
|
||||
double sum = 0.0;
|
||||
for (int64_t c = 0; c < n_in; c++) {
|
||||
sum += (double) wr[c] * x[t * n_in + c];
|
||||
}
|
||||
const float acc = (float) sum + tv.g2p_out_b[k];
|
||||
if (acc > best_v) {
|
||||
best_v = acc;
|
||||
best = k;
|
||||
}
|
||||
}
|
||||
if (best != prev && best != 0) {
|
||||
out += (out.empty() ? "" : " ") + std::string(tiny_voca_g2p_symbols[best - 1]);
|
||||
}
|
||||
prev = best;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -270,6 +270,14 @@ static void ifft(const mtmd_audio_cache & cache, float * in, int N, float * out)
|
|||
fft_impl<true, false>(cache, in, N, out);
|
||||
}
|
||||
|
||||
void mtmd_audio_fft(const mtmd_audio_cache & cache, float * in, int N, float * out) {
|
||||
fft(cache, in, N, out);
|
||||
}
|
||||
|
||||
void mtmd_audio_ifft(const mtmd_audio_cache & cache, float * in, int N, float * out) {
|
||||
ifft(cache, in, N, out);
|
||||
}
|
||||
|
||||
static void mtmd_audio_fill_entries(std::vector<mtmd_audio_mel> & mels, bool shape_only, std::vector<mtmd_image_f32> & entries) {
|
||||
entries.clear();
|
||||
for (auto & mel : mels) {
|
||||
|
|
|
|||
|
|
@ -52,6 +52,11 @@ struct mtmd_audio_cache {
|
|||
);
|
||||
};
|
||||
|
||||
// FFT of N real samples -> N complex values (interleaved), in needs 2 * N floats and out 8 * N floats (scratch)
|
||||
void mtmd_audio_fft(const mtmd_audio_cache & cache, float * in, int N, float * out);
|
||||
// inverse FFT of N complex values (interleaved), scaled by 1 / N; in and out need 8 * N floats (scratch)
|
||||
void mtmd_audio_ifft(const mtmd_audio_cache & cache, float * in, int N, float * out);
|
||||
|
||||
// compute one log10-mel frame from n_fft windowed samples, cache must be initialized for n_fft
|
||||
void mtmd_audio_log_mel_frame(const mtmd_audio_cache & cache, const float * samples, int n_fft, int n_mel, float * out);
|
||||
|
||||
|
|
|
|||
|
|
@ -1104,6 +1104,17 @@ std::unique_ptr<mtmd_graph> mtmd_get_graph_builder(mtmd_subcontext * ctx, const
|
|||
builder = io ? std::make_unique<mtmd_graph_kokoro>(ctx, img, (mtmd_graph_kokoro::stage_type) io->stage, io->n_tok, io->n_frames, io->n_har)
|
||||
: std::make_unique<mtmd_graph_kokoro>(ctx, img, mtmd_graph_kokoro::STAGE_DEC, 0, 2, 241);
|
||||
} break;
|
||||
case PROJECTOR_TYPE_TINY_VOCA:
|
||||
{
|
||||
const auto gen_process = params ? params->gen_process : MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT;
|
||||
int n_rows = 1;
|
||||
if (params && params->feats) {
|
||||
const size_t n_embd = (size_t) ctx->model.hparams.n_embd;
|
||||
GGML_ASSERT(!params->feats->empty() && params->feats->size() % n_embd == 0);
|
||||
n_rows = (int) (params->feats->size() / n_embd);
|
||||
}
|
||||
builder = std::make_unique<mtmd_graph_tiny_voca>(ctx, img, gen_process, n_rows);
|
||||
} break;
|
||||
case PROJECTOR_TYPE_YOUTUVL:
|
||||
{
|
||||
builder = std::make_unique<mtmd_graph_youtuvl>(ctx, img);
|
||||
|
|
|
|||
|
|
@ -1361,6 +1361,366 @@ private:
|
|||
bool sent = false;
|
||||
};
|
||||
|
||||
// tiny-voca is not autoregressive: the backbone encodes the phonemes of one sentence, the mmproj turns its states into audio
|
||||
// the prompt is a phoneme string, symbols separated by spaces, a stress mark (ˈ or ˌ) before a stressed vowel
|
||||
// each sentence is one utterance, like the reference pipeline: the "tts" template ends each one with <eos>
|
||||
// a prompt without <eos> (phonemes given by the user) is cut after each sentence mark, and a missing final mark is added
|
||||
class tiny_voca_gen_audio_pipeline : public mtmd_gen_audio_pipeline {
|
||||
public:
|
||||
using mtmd_gen_audio_pipeline::mtmd_gen_audio_pipeline;
|
||||
|
||||
// the predicted durations are divided by the speed
|
||||
bool supports_speed() const override { return true; }
|
||||
|
||||
void reset() override {
|
||||
segments.clear();
|
||||
audio.clear();
|
||||
wav.clear();
|
||||
n_encoded = 0;
|
||||
decoded = false;
|
||||
sent = false;
|
||||
}
|
||||
|
||||
int32_t set_input(const mtmd_helper_gen_audio_inp * inp) override {
|
||||
reset();
|
||||
if (!inp->prompt || inp->prompt_len == 0 || inp->seq_id < 0 || (uint32_t) inp->seq_id >= llama_n_seq_max(lctx)) {
|
||||
LOG_ERR("mtmd_helper_gen_audio: tiny-voca requires a prompt\n");
|
||||
return 1;
|
||||
}
|
||||
if (inp->speaker_ref && !mtmd_bitmap_is_voice(inp->speaker_ref)) {
|
||||
LOG_ERR("mtmd_helper_gen_audio: tiny-voca has no voice cloning, use one of its voices\n");
|
||||
return 1;
|
||||
}
|
||||
seq_id = inp->seq_id;
|
||||
out_type = inp->out_type;
|
||||
stream = inp->stream;
|
||||
speed = inp->speed;
|
||||
|
||||
if (!load_tables()) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char * voice = inp->speaker_ref ? mtmd_bitmap_get_id(inp->speaker_ref) : mtmd_gen_audio_voice_name(mctx, 0);
|
||||
std::vector<float> voice_row(2 * (size_t) n_embd);
|
||||
const std::string name = std::string("voice.") + (voice ? voice : "");
|
||||
if (!voice || mtmd_gen_audio_read_tensor(mctx, name.c_str(), voice_row.data(), voice_row.size()) != voice_row.size()) {
|
||||
LOG_ERR("mtmd_helper_gen_audio: unknown voice \"%s\"\n", voice ? voice : "");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// symbols -> (token, stress); the begin and end tokens are added per sentence
|
||||
std::vector<std::pair<llama_token, int32_t>> phones;
|
||||
explicit_ends = false;
|
||||
const std::string prompt(inp->prompt, inp->prompt_len);
|
||||
size_t n_unknown = 0;
|
||||
for (size_t i = 0; i < prompt.size();) {
|
||||
while (i < prompt.size() && isspace((unsigned char) prompt[i])) {
|
||||
i++;
|
||||
}
|
||||
size_t j = i;
|
||||
while (j < prompt.size() && !isspace((unsigned char) prompt[j])) {
|
||||
j++;
|
||||
}
|
||||
if (j == i) {
|
||||
break;
|
||||
}
|
||||
std::string sym = prompt.substr(i, j - i);
|
||||
i = j;
|
||||
int32_t stress = 0;
|
||||
if (sym.rfind("\xcb\x88", 0) == 0) { // ˈ primary
|
||||
stress = 1;
|
||||
} else if (sym.rfind("\xcb\x8c", 0) == 0) { // ˌ secondary
|
||||
stress = 2;
|
||||
}
|
||||
if (stress > 0) {
|
||||
sym = sym.substr(2);
|
||||
}
|
||||
if (sym == "<eos>") {
|
||||
// the end of a sentence, as the text was split by the template
|
||||
explicit_ends = true;
|
||||
phones.push_back({ tok_eos, 0 });
|
||||
continue;
|
||||
}
|
||||
if (sym == "<bos>" || sym == "<pad>") {
|
||||
continue;
|
||||
}
|
||||
auto it = token_of.find(sym);
|
||||
if (it == token_of.end()) {
|
||||
n_unknown++;
|
||||
phones.push_back({ tok_unk, 0 });
|
||||
continue;
|
||||
}
|
||||
phones.push_back({ it->second, stress });
|
||||
}
|
||||
if (n_unknown > 0) {
|
||||
LOG_WRN("mtmd_helper_gen_audio: %zu symbols of the prompt are not phonemes of the model, they are read as <unk>\n", n_unknown);
|
||||
}
|
||||
|
||||
// cut after each sentence end, then cut long sentences at weaker breaks
|
||||
const size_t n_max = std::min({ (size_t) llama_n_ctx_seq(lctx), (size_t) llama_n_ubatch(lctx), (size_t) llama_model_n_ctx_train(model) });
|
||||
if (n_max < 8) {
|
||||
LOG_ERR("mtmd_helper_gen_audio: the context is too small\n");
|
||||
return 1;
|
||||
}
|
||||
for (size_t pos = 0; pos < phones.size();) {
|
||||
while (pos < phones.size() && (phones[pos].first == tok_sp || phones[pos].first == tok_eos)) {
|
||||
pos++;
|
||||
}
|
||||
if (pos == phones.size()) {
|
||||
break;
|
||||
}
|
||||
const size_t len = split_len(phones, pos, n_max - 3);
|
||||
add_segment(phones, pos, len, voice_row);
|
||||
pos += len;
|
||||
}
|
||||
if (segments.empty()) {
|
||||
LOG_ERR("mtmd_helper_gen_audio: the prompt has no phoneme\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!init_gen_state(inp->seed)) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// the encoder is not causal, it takes one whole sentence per call
|
||||
int32_t step_prompt(int32_t) override {
|
||||
if (segments.empty()) {
|
||||
return -1;
|
||||
}
|
||||
if (n_encoded == segments.size()) {
|
||||
return 0;
|
||||
}
|
||||
auto & seg = segments[n_encoded];
|
||||
const int n = (int) seg.tokens.size();
|
||||
decode_embd_batch batch(seg.embd.data(), n, 1, n_embd);
|
||||
batch.set_position_normal(0, seq_id);
|
||||
std::fill(batch.logits.begin(), batch.logits.end(), 1);
|
||||
if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch.render(lctx, 0, n)) != 0) {
|
||||
LOG_ERR("mtmd_helper_gen_audio: tiny-voca encoder failed\n");
|
||||
return -1;
|
||||
}
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const float * h = llama_get_embeddings_ith(lctx, i);
|
||||
if (!h) {
|
||||
return -1;
|
||||
}
|
||||
seg.feats.insert(seg.feats.end(), h, h + n_embd);
|
||||
}
|
||||
seg.embd.clear();
|
||||
n_encoded++;
|
||||
return (int32_t) (segments.size() - n_encoded);
|
||||
}
|
||||
|
||||
// nothing is generated step by step
|
||||
int32_t step_gen(llama_token, const float *, const float ** h_state_out, bool * out_stop) override {
|
||||
*h_state_out = nullptr;
|
||||
*out_stop = true;
|
||||
return !segments.empty() && n_encoded == segments.size() ? 0 : 1;
|
||||
}
|
||||
|
||||
int32_t get_output(int32_t * sample_rate, const char ** data, size_t * data_len, int64_t * n_samples) override {
|
||||
*sample_rate = info.sample_rate;
|
||||
*data_len = 0;
|
||||
if (n_samples) { *n_samples = 0; }
|
||||
if (stream) {
|
||||
// the audio comes out in one chunk after flush()
|
||||
if (!decoded || sent) {
|
||||
return 0;
|
||||
}
|
||||
sent = true;
|
||||
} else if (!decode_audio()) {
|
||||
return 1;
|
||||
}
|
||||
if (n_samples) { *n_samples = audio.size(); }
|
||||
if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
|
||||
*data = (const char *) audio.data();
|
||||
*data_len = audio.size() * sizeof(float);
|
||||
} else {
|
||||
wav.clear();
|
||||
if (!write_wav16(wav, audio, info.sample_rate)) {
|
||||
return 1;
|
||||
}
|
||||
*data = wav.data();
|
||||
*data_len = wav.size();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int32_t flush() override {
|
||||
return decode_audio() ? 0 : 1;
|
||||
}
|
||||
|
||||
private:
|
||||
struct segment {
|
||||
std::vector<llama_token> tokens;
|
||||
std::vector<float> embd; // encoder input rows
|
||||
std::vector<float> feats; // the voice row, then the encoder state of each token
|
||||
};
|
||||
|
||||
bool load_tables() {
|
||||
if (!token_of.empty()) {
|
||||
return true;
|
||||
}
|
||||
const llama_token n_vocab = llama_vocab_n_tokens(vocab);
|
||||
for (llama_token id = 0; id < n_vocab; id++) {
|
||||
token_of[llama_vocab_get_text(vocab, id)] = id;
|
||||
}
|
||||
auto find = [&](const char * text) {
|
||||
auto it = token_of.find(text);
|
||||
return it == token_of.end() ? LLAMA_TOKEN_NULL : it->second;
|
||||
};
|
||||
tok_bos = find("<bos>");
|
||||
tok_eos = find("<eos>");
|
||||
tok_sp = find("<sp>");
|
||||
tok_unk = find("<unk>");
|
||||
tok_dot = find(".");
|
||||
tok_emb.resize((size_t) n_vocab * n_embd);
|
||||
str_emb.resize(3 * (size_t) n_embd);
|
||||
if (tok_bos == LLAMA_TOKEN_NULL || tok_eos == LLAMA_TOKEN_NULL || tok_sp == LLAMA_TOKEN_NULL || tok_unk == LLAMA_TOKEN_NULL || tok_dot == LLAMA_TOKEN_NULL ||
|
||||
mtmd_gen_audio_read_tensor(mctx, "a.gen.tok_embd.weight", tok_emb.data(), tok_emb.size()) != tok_emb.size() ||
|
||||
mtmd_gen_audio_read_tensor(mctx, "a.gen.stress_embd.weight", str_emb.data(), str_emb.size()) != str_emb.size()) {
|
||||
LOG_ERR("mtmd_helper_gen_audio: the backbone and the mmproj are not a tiny-voca pair\n");
|
||||
token_of.clear();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool is_any(llama_token id, const char * chars) const {
|
||||
const char * text = llama_vocab_get_text(vocab, id);
|
||||
return text[0] != '\0' && strstr(chars, text) != nullptr;
|
||||
}
|
||||
|
||||
// phones of the sentence that starts at pos, cut after a weaker break if it is longer than n_max
|
||||
size_t split_len(const std::vector<std::pair<llama_token, int32_t>> & phones, size_t pos, size_t n_max) const {
|
||||
size_t n_left = phones.size() - pos;
|
||||
if (explicit_ends) {
|
||||
// up to the next <eos>
|
||||
for (size_t len = 0; len < n_left; len++) {
|
||||
if (phones[pos + len].first == tok_eos) {
|
||||
n_left = len;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (size_t len = 1; len <= std::min(n_left, n_max); len++) {
|
||||
if (is_any(phones[pos + len - 1].first, "!.?\xe2\x80\xa6")) {
|
||||
return len;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (n_left <= n_max) {
|
||||
return n_left;
|
||||
}
|
||||
for (const char * breaks : {":;", ",\xe2\x80\x94"}) {
|
||||
for (size_t len = n_max; len > 1; len--) {
|
||||
if (is_any(phones[pos + len - 1].first, breaks)) {
|
||||
return len;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (size_t len = n_max; len > 1; len--) {
|
||||
if (phones[pos + len - 1].first == tok_sp) {
|
||||
return len;
|
||||
}
|
||||
}
|
||||
return n_max;
|
||||
}
|
||||
|
||||
// <bos> phones <eos>; without a final mark the last word breaks off, so a full stop is added
|
||||
// (not when the template has split the text: it adds the stop where the reference does)
|
||||
void add_segment(const std::vector<std::pair<llama_token, int32_t>> & phones, size_t pos, size_t len, const std::vector<float> & voice_row) {
|
||||
segment seg;
|
||||
std::vector<int32_t> stress;
|
||||
seg.tokens.push_back(tok_bos);
|
||||
stress.push_back(0);
|
||||
size_t end = pos + len;
|
||||
while (end > pos && phones[end - 1].first == tok_sp) {
|
||||
end--;
|
||||
}
|
||||
for (size_t i = pos; i < end; i++) {
|
||||
seg.tokens.push_back(phones[i].first);
|
||||
stress.push_back(phones[i].second);
|
||||
}
|
||||
const char * last = llama_vocab_get_text(vocab, seg.tokens.back());
|
||||
if (!explicit_ends && (!is_any(seg.tokens.back(), "!.?\xe2\x80\xa6,;:") || last[0] == '\0')) {
|
||||
seg.tokens.push_back(tok_dot);
|
||||
stress.push_back(0);
|
||||
}
|
||||
seg.tokens.push_back(tok_eos);
|
||||
stress.push_back(0);
|
||||
|
||||
seg.embd.resize(seg.tokens.size() * n_embd);
|
||||
for (size_t i = 0; i < seg.tokens.size(); i++) {
|
||||
const float * t = tok_emb.data() + (size_t) seg.tokens[i] * n_embd;
|
||||
const float * s = str_emb.data() + (size_t) stress[i] * n_embd;
|
||||
for (int c = 0; c < n_embd; c++) {
|
||||
seg.embd[i * n_embd + c] = t[c] + s[c] + voice_row[c];
|
||||
}
|
||||
}
|
||||
seg.feats = voice_row;
|
||||
segments.push_back(std::move(seg));
|
||||
}
|
||||
|
||||
bool decode_audio() {
|
||||
if (decoded) {
|
||||
return true;
|
||||
}
|
||||
if (segments.empty() || n_encoded != segments.size()) {
|
||||
return false;
|
||||
}
|
||||
for (const auto & seg : segments) {
|
||||
std::vector<int32_t> codes(seg.tokens.begin(), seg.tokens.end());
|
||||
mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
|
||||
inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
|
||||
inp.codes = codes.data();
|
||||
inp.n_codes = codes.size();
|
||||
inp.feats = seg.feats.data();
|
||||
inp.n_feats = seg.feats.size();
|
||||
inp.speed = speed;
|
||||
mtmd_gen_out out{};
|
||||
if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
|
||||
return false;
|
||||
}
|
||||
audio.insert(audio.end(), out.audio, out.audio + out.n_samples);
|
||||
}
|
||||
// the model can peak above 1.0, the reference scales the whole text down to a peak of 0.99
|
||||
float peak = 0.0f;
|
||||
for (float v : audio) {
|
||||
peak = std::max(peak, std::fabs(v));
|
||||
}
|
||||
if (peak > 0.99f) {
|
||||
for (float & v : audio) {
|
||||
v *= 0.99f / peak;
|
||||
}
|
||||
}
|
||||
decoded = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
llama_seq_id seq_id = 0;
|
||||
std::unordered_map<std::string, llama_token> token_of;
|
||||
llama_token tok_bos = LLAMA_TOKEN_NULL;
|
||||
llama_token tok_eos = LLAMA_TOKEN_NULL;
|
||||
llama_token tok_sp = LLAMA_TOKEN_NULL;
|
||||
llama_token tok_unk = LLAMA_TOKEN_NULL;
|
||||
llama_token tok_dot = LLAMA_TOKEN_NULL;
|
||||
bool explicit_ends = false; // the prompt marks the end of each sentence with <eos>
|
||||
std::vector<float> tok_emb; // [n_vocab, n_embd]
|
||||
std::vector<float> str_emb; // [3, n_embd]
|
||||
std::vector<segment> segments;
|
||||
size_t n_encoded = 0;
|
||||
float speed = 1.0f;
|
||||
std::vector<float> audio;
|
||||
std::vector<char> wav;
|
||||
mtmd_helper_gen_audio_outtype out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV;
|
||||
bool stream = false;
|
||||
bool decoded = false;
|
||||
bool sent = false;
|
||||
};
|
||||
|
||||
// Soprano uses the hidden state that predicts each non-EOS token, including the prompt's last state.
|
||||
class soprano_gen_audio_pipeline : public mtmd_gen_audio_pipeline {
|
||||
public:
|
||||
|
|
@ -4564,6 +4924,8 @@ static std::unique_ptr<mtmd_gen_audio_pipeline> make_pipeline(llama_context * lc
|
|||
return std::unique_ptr<mtmd_gen_audio_pipeline>(new soprano_gen_audio_pipeline(lctx, mctx));
|
||||
case MTMD_GEN_AUDIO_TYPE_KOKORO:
|
||||
return std::unique_ptr<mtmd_gen_audio_pipeline>(new kokoro_gen_audio_pipeline(lctx, mctx));
|
||||
case MTMD_GEN_AUDIO_TYPE_TINY_VOCA:
|
||||
return std::unique_ptr<mtmd_gen_audio_pipeline>(new tiny_voca_gen_audio_pipeline(lctx, mctx));
|
||||
case MTMD_GEN_AUDIO_TYPE_LFM3A:
|
||||
return std::unique_ptr<mtmd_gen_audio_pipeline>(new lfm3a_gen_audio_pipeline(lctx, mctx));
|
||||
case MTMD_GEN_AUDIO_TYPE_CHATTERBOX:
|
||||
|
|
|
|||
|
|
@ -616,6 +616,7 @@ enum projector_type {
|
|||
PROJECTOR_TYPE_POCKETTTS_GEN,
|
||||
PROJECTOR_TYPE_SOPRANO,
|
||||
PROJECTOR_TYPE_KOKORO,
|
||||
PROJECTOR_TYPE_TINY_VOCA,
|
||||
PROJECTOR_TYPE_LFM3A_GEN,
|
||||
PROJECTOR_TYPE_DRAMA3_GEN,
|
||||
PROJECTOR_TYPE_ZONOS3_GEN,
|
||||
|
|
@ -713,6 +714,7 @@ static std::map<projector_type, std::string> PROJECTOR_TYPE_NAMES = {
|
|||
{ PROJECTOR_TYPE_POCKETTTS_GEN, "pockettts_gen"},
|
||||
{ PROJECTOR_TYPE_SOPRANO, "soprano"},
|
||||
{ PROJECTOR_TYPE_KOKORO, "kokoro"},
|
||||
{ PROJECTOR_TYPE_TINY_VOCA, "tiny_voca"},
|
||||
{ PROJECTOR_TYPE_LFM3A_GEN, "lfm3a_gen"},
|
||||
{ PROJECTOR_TYPE_DRAMA3_GEN, "drama3_gen"},
|
||||
{ PROJECTOR_TYPE_ZONOS3_GEN, "zonos3_gen"},
|
||||
|
|
|
|||
|
|
@ -1173,6 +1173,7 @@ struct mtmd_model_loader {
|
|||
hparams.audio_hop_len = 512;
|
||||
} break;
|
||||
case PROJECTOR_TYPE_KOKORO:
|
||||
case PROJECTOR_TYPE_TINY_VOCA:
|
||||
{
|
||||
hparams.audio_sample_rate = 24000;
|
||||
} break;
|
||||
|
|
@ -1583,6 +1584,7 @@ struct mtmd_model_loader {
|
|||
model.proj_type != PROJECTOR_TYPE_POCKETTTS_GEN &&
|
||||
model.proj_type != PROJECTOR_TYPE_SOPRANO &&
|
||||
model.proj_type != PROJECTOR_TYPE_KOKORO &&
|
||||
model.proj_type != PROJECTOR_TYPE_TINY_VOCA &&
|
||||
model.proj_type != PROJECTOR_TYPE_MUSE_SPARK_AUDIO &&
|
||||
model.proj_type != PROJECTOR_TYPE_VIBEVOICE_ASR &&
|
||||
model.proj_type != PROJECTOR_TYPE_CHATTERBOX &&
|
||||
|
|
@ -3479,6 +3481,97 @@ struct mtmd_model_loader {
|
|||
}
|
||||
LOG_INF("%s: %zu predefined voices\n", __func__, model.gen_voices.size());
|
||||
} break;
|
||||
case PROJECTOR_TYPE_TINY_VOCA:
|
||||
{
|
||||
using g = mtmd_graph_tiny_voca;
|
||||
auto & tv = model.tiny_voca;
|
||||
tv.dur_conv1_w = get_tensor("a.gen.dur.conv1.weight");
|
||||
tv.dur_conv1_b = get_tensor("a.gen.dur.conv1.bias");
|
||||
tv.dur_norm1_w = get_tensor("a.gen.dur.norm1.weight");
|
||||
tv.dur_norm1_b = get_tensor("a.gen.dur.norm1.bias");
|
||||
tv.dur_conv2_w = get_tensor("a.gen.dur.conv2.weight");
|
||||
tv.dur_conv2_b = get_tensor("a.gen.dur.conv2.bias");
|
||||
tv.dur_norm2_w = get_tensor("a.gen.dur.norm2.weight");
|
||||
tv.dur_norm2_b = get_tensor("a.gen.dur.norm2.bias");
|
||||
tv.dur_out_w = get_tensor("a.gen.dur.out.weight");
|
||||
tv.dur_out_b = get_tensor("a.gen.dur.out.bias");
|
||||
tv.harm_w = get_tensor("a.gen.voc.harmonic.weight");
|
||||
tv.harm_b = get_tensor("a.gen.voc.harmonic.bias");
|
||||
tv.noise_w = get_tensor("a.gen.voc.noise.weight");
|
||||
tv.noise_b = get_tensor("a.gen.voc.noise.bias");
|
||||
if (tv.harm_w->ne[0] != hparams.n_embd || tv.harm_w->ne[1] != g::n_cep_causal + g::n_cep_anti + g::harm_steps ||
|
||||
tv.noise_w->ne[0] != hparams.n_embd || tv.noise_w->ne[1] != g::n_noise_cep + g::noise_steps ||
|
||||
tv.dur_out_w->ne[1] != 2) {
|
||||
throw std::runtime_error(mtmd_format("%s: tiny_voca: unexpected head shape\n", __func__));
|
||||
}
|
||||
|
||||
auto read_host = [&](const std::string & name, std::vector<float> & dst, int64_t ne0, int64_t ne1) {
|
||||
const ggml_tensor * t = ggml_get_tensor(ctx_meta.get(), name.c_str());
|
||||
if (!t || t->type != GGML_TYPE_F32 || t->ne[0] != ne0 || t->ne[1] != ne1 || ggml_n_dims(t) > 2) {
|
||||
throw std::runtime_error(mtmd_format("%s: invalid or missing tensor %s\n", __func__, name.c_str()));
|
||||
}
|
||||
dst.resize(ggml_nelements(t));
|
||||
fin.seekg(tensor_offset.at(name), std::ios::beg);
|
||||
if (!fin.read(reinterpret_cast<char *>(dst.data()), ggml_nbytes(t))) {
|
||||
throw std::runtime_error(mtmd_format("%s: failed to read %s\n", __func__, name.c_str()));
|
||||
}
|
||||
};
|
||||
const int64_t n_embd = hparams.n_embd;
|
||||
const ggml_tensor * tok = ggml_get_tensor(ctx_meta.get(), "a.gen.tok_embd.weight");
|
||||
if (!tok) {
|
||||
throw std::runtime_error(mtmd_format("%s: tiny_voca: missing token table\n", __func__));
|
||||
}
|
||||
read_host("a.gen.token_class", tv.token_class, tok->ne[1], 1);
|
||||
read_host("a.gen.frame_pos.weight", tv.frame_pos_w, 3, n_embd);
|
||||
read_host("a.gen.frame_pos.bias", tv.frame_pos_b, n_embd, 1);
|
||||
read_host("a.gen.prosody_head.weight", tv.prosody_head_w, n_embd, 3);
|
||||
read_host("a.gen.prosody_head.bias", tv.prosody_head_b, 3, 1);
|
||||
read_host("a.gen.prosody_proj.weight", tv.prosody_proj_w, 3, n_embd);
|
||||
read_host("a.gen.prosody_proj.bias", tv.prosody_proj_b, n_embd, 1);
|
||||
|
||||
// unknown-word model, optional
|
||||
if (const ggml_tensor * e = ggml_get_tensor(ctx_meta.get(), "a.gen.g2p.embed.weight")) {
|
||||
const ggml_tensor * hh = ggml_get_tensor(ctx_meta.get(), "a.gen.g2p.gru.weight_hh_l0");
|
||||
if (!hh || e->ne[1] != g::n_g2p_letter + 1) {
|
||||
throw std::runtime_error(mtmd_format("%s: tiny_voca: unexpected g2p model\n", __func__));
|
||||
}
|
||||
const int64_t w = e->ne[0];
|
||||
const int64_t h = hh->ne[0];
|
||||
tv.g2p_n_width = w;
|
||||
tv.g2p_n_hidden = h;
|
||||
read_host("a.gen.g2p.embed.weight", tv.g2p_embd, w, g::n_g2p_letter + 1);
|
||||
read_host("a.gen.g2p.slot", tv.g2p_slot, w, g::n_g2p_slot);
|
||||
for (int il = 0; ggml_get_tensor(ctx_meta.get(), ("a.gen.g2p.gru.weight_ih_l" + std::to_string(il)).c_str()); il++) {
|
||||
for (const char * dir : { "", "_reverse" }) {
|
||||
const std::string sfx = "_l" + std::to_string(il) + dir;
|
||||
mtmd_tiny_voca::g2p_gru gru;
|
||||
read_host("a.gen.g2p.gru.weight_ih" + sfx, gru.w_ih, il == 0 ? w : 2 * h, 3 * h);
|
||||
read_host("a.gen.g2p.gru.weight_hh" + sfx, gru.w_hh, h, 3 * h);
|
||||
read_host("a.gen.g2p.gru.bias_ih" + sfx, gru.b_ih, 3 * h, 1);
|
||||
read_host("a.gen.g2p.gru.bias_hh" + sfx, gru.b_hh, 3 * h, 1);
|
||||
tv.g2p_layers.push_back(std::move(gru));
|
||||
}
|
||||
}
|
||||
read_host("a.gen.g2p.out.weight", tv.g2p_out_w, 2 * h, g::n_g2p_symbol + 1);
|
||||
read_host("a.gen.g2p.out.bias", tv.g2p_out_b, g::n_g2p_symbol + 1, 1);
|
||||
}
|
||||
|
||||
// read by the audio pipeline: input tables and voices (encoder row, then frame row)
|
||||
for (const char * name : { "a.gen.tok_embd.weight", "a.gen.stress_embd.weight" }) {
|
||||
model.cbx_tensors[name] = get_tensor(name);
|
||||
}
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx_meta.get()); t; t = ggml_get_next_tensor(ctx_meta.get(), t)) {
|
||||
const std::string name = t->name;
|
||||
if (name.rfind("voice.", 0) == 0) {
|
||||
if (t->ne[0] != 2 * n_embd) {
|
||||
throw std::runtime_error(mtmd_format("%s: tiny_voca: unexpected voice shape\n", __func__));
|
||||
}
|
||||
model.cbx_tensors[name] = get_tensor(name);
|
||||
model.gen_voices[name.substr(6)] = {};
|
||||
}
|
||||
}
|
||||
LOG_INF("%s: %zu predefined voices\n", __func__, model.gen_voices.size());
|
||||
} break;
|
||||
case PROJECTOR_TYPE_SOPRANO:
|
||||
{
|
||||
auto & v = model.vocos;
|
||||
|
|
@ -4976,6 +5069,7 @@ int mtmd_model::n_mmproj_embd() const {
|
|||
return cbx_tensors.at("a.cenc.spkr_enc.weight")->ne[1];
|
||||
case PROJECTOR_TYPE_SOPRANO:
|
||||
case PROJECTOR_TYPE_KOKORO:
|
||||
case PROJECTOR_TYPE_TINY_VOCA:
|
||||
return hparams.projection_dim;
|
||||
case PROJECTOR_TYPE_PARAKEET:
|
||||
return mm_1_w->ne[1];
|
||||
|
|
|
|||
|
|
@ -945,6 +945,50 @@ struct mtmd_zonos3_wav {
|
|||
int64_t rs_kernel_len = 0;
|
||||
};
|
||||
|
||||
// tiny-voca: duration predictor and source-filter heads (graphs), the small linear layers between the stacks (host)
|
||||
// the prosody and acoustic stacks are loaded by libllama, see mtmd_owned_llama_load()
|
||||
struct mtmd_tiny_voca {
|
||||
ggml_tensor * dur_conv1_w = nullptr; // [3, n_embd, n_pred]
|
||||
ggml_tensor * dur_conv1_b = nullptr;
|
||||
ggml_tensor * dur_norm1_w = nullptr;
|
||||
ggml_tensor * dur_norm1_b = nullptr;
|
||||
ggml_tensor * dur_conv2_w = nullptr; // [3, n_pred, n_pred]
|
||||
ggml_tensor * dur_conv2_b = nullptr;
|
||||
ggml_tensor * dur_norm2_w = nullptr;
|
||||
ggml_tensor * dur_norm2_b = nullptr;
|
||||
ggml_tensor * dur_out_w = nullptr; // [n_pred, 2]: log(1 + frames), pause logit
|
||||
ggml_tensor * dur_out_b = nullptr;
|
||||
ggml_tensor * harm_w = nullptr; // [n_embd, n_cep_causal + n_cep_anti + harm_steps]
|
||||
ggml_tensor * harm_b = nullptr;
|
||||
ggml_tensor * noise_w = nullptr; // [n_embd, n_noise_cep + noise_steps]
|
||||
ggml_tensor * noise_b = nullptr;
|
||||
|
||||
// read on the host, row-major as in the reference
|
||||
std::vector<float> token_class; // [n_vocab]: 0 = pause, 1 = consonant, 2 = vowel
|
||||
std::vector<float> frame_pos_w; // [n_embd, 3]
|
||||
std::vector<float> frame_pos_b; // [n_embd]
|
||||
std::vector<float> prosody_head_w; // [3, n_embd]: log(F0 / 200 Hz), voiced logit, energy
|
||||
std::vector<float> prosody_head_b;
|
||||
std::vector<float> prosody_proj_w; // [n_embd, 3]
|
||||
std::vector<float> prosody_proj_b;
|
||||
|
||||
// unknown-word model of the phonemizer, run on the host by mtmd_gen_audio_g2p(): letters -> CMUdict phonemes
|
||||
// embedding (each letter takes n_slot positions), bidirectional GRU layers, CTC output read greedily
|
||||
struct g2p_gru {
|
||||
std::vector<float> w_ih; // [3 * n_hidden, n_in]: reset, update, new
|
||||
std::vector<float> w_hh; // [3 * n_hidden, n_hidden]
|
||||
std::vector<float> b_ih;
|
||||
std::vector<float> b_hh;
|
||||
};
|
||||
std::vector<float> g2p_embd; // [n_letter + 1, n_width], row 0 unused
|
||||
std::vector<float> g2p_slot; // [n_slot, n_width]
|
||||
std::vector<g2p_gru> g2p_layers; // forward, reverse, for each layer
|
||||
std::vector<float> g2p_out_w; // [n_symbol + 1, 2 * n_hidden], output 0 is the CTC blank
|
||||
std::vector<float> g2p_out_b;
|
||||
int64_t g2p_n_width = 0;
|
||||
int64_t g2p_n_hidden = 0;
|
||||
};
|
||||
|
||||
// snake-activated conv decoder of the DAC / Oobleck family (a.gen.vae.*): yue2 VAE, minimax_music3 vocoder
|
||||
struct mtmd_snake_vae {
|
||||
// x + beta * sin(alpha * x)^2, alpha and beta folded at conversion
|
||||
|
|
@ -1320,6 +1364,7 @@ struct mtmd_model {
|
|||
mtmd_yue2 yue2;
|
||||
mtmd_music3 music3;
|
||||
mtmd_snake_vae snake_vae; // yue2, minimax_music3
|
||||
mtmd_tiny_voca tiny_voca;
|
||||
|
||||
// pocket-tts: SEANet stack, shared by the encoder (speaker path) and the decoder (gen path)
|
||||
mtmd_seanet seanet;
|
||||
|
|
|
|||
|
|
@ -1596,6 +1596,7 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) {
|
|||
} break;
|
||||
case PROJECTOR_TYPE_SOPRANO:
|
||||
case PROJECTOR_TYPE_YUE2_GEN:
|
||||
case PROJECTOR_TYPE_TINY_VOCA:
|
||||
{
|
||||
set_input_f32("inp_feats", *params->feats);
|
||||
} break;
|
||||
|
|
|
|||
|
|
@ -69,8 +69,8 @@ enum mtmd_subctx_gen_process {
|
|||
MTMD_SUBCTX_GEN_PROCESS_TTS, // full utterance of codes to raw PCM audio
|
||||
MTMD_SUBCTX_GEN_PROCESS_TTS_VOCODE, // internal: mel + source stft to istft input
|
||||
MTMD_SUBCTX_GEN_PROCESS_TOKENIZE, // raw PCM audio to semantic speech tokens
|
||||
MTMD_SUBCTX_GEN_PROCESS_LATENT_IN, // internal: flow latent rows to backbone embd rows
|
||||
MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT, // internal: backbone hidden rows to flow velocity rows
|
||||
MTMD_SUBCTX_GEN_PROCESS_LATENT_IN, // internal: flow latent rows to backbone embd rows (tiny-voca: token states to durations)
|
||||
MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT, // internal: backbone hidden rows to flow velocity rows (tiny-voca: to source-filter params)
|
||||
MTMD_SUBCTX_GEN_PROCESS_FLOW_COND, // internal: frame rows to flow condition rows
|
||||
MTMD_SUBCTX_GEN_PROCESS_FLOW_STEP, // internal: one velocity pass of the flow transformer
|
||||
};
|
||||
|
|
|
|||
|
|
@ -615,29 +615,39 @@ static bool cbx_is_mtl(const mtmd_model & model) {
|
|||
return model.cbx_read_tensor("a.cenc.perceiver.pre_attention_query", nullptr, 0) > 0;
|
||||
}
|
||||
|
||||
// yue2: the NAR layers are a qwen3 text model, libllama loads them from a synthetic GGUF
|
||||
// the tensor data is read from the mmproj file, mtmd keeps no copy
|
||||
struct yue2_nar_source {
|
||||
// a stage of the mmproj that is a libllama text model: its layers are stored under a prefix, with the libllama names
|
||||
// libllama loads them from a synthetic GGUF: gdst holds the arch hparams, the tensor data is read from the mmproj file
|
||||
struct mtmd_owned_llama_source {
|
||||
std::ifstream f;
|
||||
std::map<std::string, std::pair<size_t, size_t>> tensors; // name in the synthetic model -> offset and size in the mmproj
|
||||
};
|
||||
|
||||
static void yue2_nar_set_tensor_data(ggml_tensor * t, void * user_data) {
|
||||
auto * src = (yue2_nar_source *) user_data;
|
||||
static void mtmd_owned_llama_set_tensor_data(ggml_tensor * t, void * user_data) {
|
||||
auto * src = (mtmd_owned_llama_source *) user_data;
|
||||
std::vector<uint8_t> buf(ggml_nbytes(t), 0);
|
||||
const std::string name = t->name;
|
||||
auto it = src->tensors.find(name);
|
||||
if (it != src->tensors.end()) {
|
||||
if (it->second.second != buf.size()) {
|
||||
throw std::runtime_error(mtmd_format("yue2: unexpected size of %s", t->name));
|
||||
throw std::runtime_error(mtmd_format("unexpected size of %s", t->name));
|
||||
}
|
||||
src->f.seekg((std::streamoff) it->second.first, std::ios::beg);
|
||||
if (!src->f.read((char *) buf.data(), (std::streamsize) buf.size())) {
|
||||
throw std::runtime_error(mtmd_format("yue2: failed to read %s", t->name));
|
||||
throw std::runtime_error(mtmd_format("failed to read %s", t->name));
|
||||
}
|
||||
} else {
|
||||
// optional tensors that libllama creates by itself, give them neutral values (scale = 1, dense_2 = identity, others = 0)
|
||||
GGML_ASSERT(t->type == GGML_TYPE_F32);
|
||||
// any other missing tensor is an error: a weight left at 0 gives wrong output without any error
|
||||
// (e.g. a model built from metadata has separate q, k, v and no fused qkv)
|
||||
auto ends_with = [&](const char * suffix) {
|
||||
const size_t n = strlen(suffix);
|
||||
return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0;
|
||||
};
|
||||
const bool optional = ends_with("scale") || ends_with(".bias") || name == "dense_2.weight" ||
|
||||
name == "token_embd.weight" || name == "output.weight"; // inputs are embedding rows, outputs are hidden states
|
||||
if (!optional || t->type != GGML_TYPE_F32) {
|
||||
throw std::runtime_error(mtmd_format("tensor %s is missing from the mmproj", t->name));
|
||||
}
|
||||
float * w = (float *) buf.data();
|
||||
if (name.size() >= 5 && name.compare(name.size() - 5, 5, "scale") == 0) {
|
||||
std::fill(w, w + ggml_nelements(t), 1.0f);
|
||||
|
|
@ -651,15 +661,52 @@ static void yue2_nar_set_tensor_data(ggml_tensor * t, void * user_data) {
|
|||
ggml_backend_tensor_set(t, buf.data(), 0, buf.size());
|
||||
}
|
||||
|
||||
static llama_model * mtmd_yue2_nar_load(const char * fname, ggml_backend_dev_t device, const mtmd_hparams & hparams) {
|
||||
// the layers are the tensors "<prefix>blk.*" and "<prefix>output_norm.*" of the mmproj, n_tensors receives their count
|
||||
static llama_model * mtmd_owned_llama_load(const char * fname, ggml_backend_dev_t device, gguf_context * gdst, const std::string & prefix, size_t & n_tensors) {
|
||||
ggml_context * meta = nullptr;
|
||||
gguf_init_params gparams = { /*no_alloc =*/ true, /*ctx =*/ &meta };
|
||||
gguf_context_ptr gsrc(gguf_init_from_file(fname, gparams));
|
||||
ggml_context_ptr meta_ptr(meta);
|
||||
if (!gsrc) {
|
||||
throw std::runtime_error(mtmd_format("yue2: failed to read %s", fname));
|
||||
throw std::runtime_error(mtmd_format("failed to read %s", fname));
|
||||
}
|
||||
|
||||
mtmd_owned_llama_source src;
|
||||
for (int64_t i = 0; i < gguf_get_n_tensors(gsrc.get()); i++) {
|
||||
const std::string name = gguf_get_tensor_name(gsrc.get(), i);
|
||||
if (name.rfind(prefix + "blk.", 0) != 0 && name.rfind(prefix + "output_norm.", 0) != 0) {
|
||||
continue;
|
||||
}
|
||||
// the synthetic model only takes the type from here, the shapes come from the hparams
|
||||
ggml_tensor t = *ggml_get_tensor(meta, name.c_str());
|
||||
ggml_set_name(&t, name.substr(prefix.size()).c_str());
|
||||
gguf_add_tensor(gdst, &t);
|
||||
src.tensors[t.name] = { gguf_get_data_offset(gsrc.get()) + gguf_get_tensor_offset(gsrc.get(), i), ggml_nbytes(&t) };
|
||||
}
|
||||
n_tensors = src.tensors.size();
|
||||
src.f = open_ifstream_binary(fname);
|
||||
if (!src.f) {
|
||||
throw std::runtime_error(mtmd_format("failed to open %s", fname));
|
||||
}
|
||||
|
||||
llama_model_params mparams = llama_model_default_params();
|
||||
std::vector<ggml_backend_dev_t> devs;
|
||||
if (device && ggml_backend_dev_type(device) != GGML_BACKEND_DEVICE_TYPE_CPU) {
|
||||
devs = { device, nullptr };
|
||||
mparams.devices = devs.data();
|
||||
mparams.n_gpu_layers = -1;
|
||||
} else {
|
||||
mparams.n_gpu_layers = 0;
|
||||
}
|
||||
llama_model * model = llama_model_init_from_user(gdst, mtmd_owned_llama_set_tensor_data, &src, mparams);
|
||||
if (!model) {
|
||||
throw std::runtime_error(mtmd_format("failed to load the layers under %s", prefix.c_str()));
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
// yue2: the NAR layers are a qwen3 text model
|
||||
static llama_model * mtmd_yue2_nar_load(const char * fname, ggml_backend_dev_t device, const mtmd_hparams & hparams) {
|
||||
const llm_arch arch = LLM_ARCH_QWEN3;
|
||||
gguf_context_ptr gdst(gguf_init_empty());
|
||||
auto key = [&](llm_kv kv) { return llama_arch_kv_name(arch, kv); };
|
||||
|
|
@ -675,39 +722,38 @@ static llama_model * mtmd_yue2_nar_load(const char * fname, ggml_backend_dev_t d
|
|||
gguf_set_val_f32(gdst.get(), key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS).c_str(), hparams.eps);
|
||||
gguf_set_val_f32(gdst.get(), key(LLM_KV_ROPE_FREQ_BASE).c_str(), mtmd_graph_yue2_gen::rope_theta);
|
||||
|
||||
yue2_nar_source src;
|
||||
const std::string prefix = "a.gen.nar.";
|
||||
for (int64_t i = 0; i < gguf_get_n_tensors(gsrc.get()); i++) {
|
||||
const std::string name = gguf_get_tensor_name(gsrc.get(), i);
|
||||
if (name.rfind(prefix + "blk.", 0) != 0 && name != prefix + "output_norm.weight") {
|
||||
continue;
|
||||
}
|
||||
// the synthetic model only takes the type from here, the shapes come from the hparams
|
||||
ggml_tensor t = *ggml_get_tensor(meta, name.c_str());
|
||||
ggml_set_name(&t, name.substr(prefix.size()).c_str());
|
||||
gguf_add_tensor(gdst.get(), &t);
|
||||
src.tensors[t.name] = { gguf_get_data_offset(gsrc.get()) + gguf_get_tensor_offset(gsrc.get(), i), ggml_nbytes(&t) };
|
||||
}
|
||||
if (src.tensors.size() != (size_t) hparams.n_layer * 11 + 1) {
|
||||
size_t n_tensors = 0;
|
||||
llama_model * model = mtmd_owned_llama_load(fname, device, gdst.get(), "a.gen.nar.", n_tensors);
|
||||
if (n_tensors != (size_t) hparams.n_layer * 11 + 1) {
|
||||
llama_model_free(model);
|
||||
throw std::runtime_error("yue2: unexpected NAR tensors in the mmproj");
|
||||
}
|
||||
src.f = open_ifstream_binary(fname);
|
||||
if (!src.f) {
|
||||
throw std::runtime_error(mtmd_format("yue2: failed to open %s", fname));
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
llama_model_params mparams = llama_model_default_params();
|
||||
std::vector<ggml_backend_dev_t> devs;
|
||||
if (device && ggml_backend_dev_type(device) != GGML_BACKEND_DEVICE_TYPE_CPU) {
|
||||
devs = { device, nullptr };
|
||||
mparams.devices = devs.data();
|
||||
mparams.n_gpu_layers = -1;
|
||||
} else {
|
||||
mparams.n_gpu_layers = 0;
|
||||
}
|
||||
llama_model * model = llama_model_init_from_user(gdst.get(), yue2_nar_set_tensor_data, &src, mparams);
|
||||
if (!model) {
|
||||
throw std::runtime_error("yue2: failed to load the NAR layers");
|
||||
// tiny-voca: the prosody and acoustic stacks, same arch as the text model
|
||||
static llama_model * mtmd_tiny_voca_stack_load(const char * fname, ggml_backend_dev_t device, const mtmd_hparams & hparams, const char * prefix, int n_layer) {
|
||||
const llm_arch arch = LLM_ARCH_TINY_VOCA;
|
||||
gguf_context_ptr gdst(gguf_init_empty());
|
||||
auto key = [&](llm_kv kv) { return llama_arch_kv_name(arch, kv); };
|
||||
gguf_set_val_str(gdst.get(), key(LLM_KV_GENERAL_ARCHITECTURE).c_str(), llama_arch_name(arch));
|
||||
gguf_set_val_str(gdst.get(), key(LLM_KV_TOKENIZER_MODEL).c_str(), "none");
|
||||
gguf_set_val_u32(gdst.get(), key(LLM_KV_VOCAB_SIZE).c_str(), 1);
|
||||
gguf_set_val_u32(gdst.get(), key(LLM_KV_CONTEXT_LENGTH).c_str(), mtmd_graph_tiny_voca::n_max_frames);
|
||||
gguf_set_val_u32(gdst.get(), key(LLM_KV_EMBEDDING_LENGTH).c_str(), hparams.n_embd);
|
||||
gguf_set_val_u32(gdst.get(), key(LLM_KV_FEED_FORWARD_LENGTH).c_str(), hparams.n_ff);
|
||||
gguf_set_val_u32(gdst.get(), key(LLM_KV_BLOCK_COUNT).c_str(), n_layer);
|
||||
gguf_set_val_u32(gdst.get(), key(LLM_KV_ATTENTION_HEAD_COUNT).c_str(), hparams.n_head);
|
||||
gguf_set_val_u32(gdst.get(), key(LLM_KV_ATTENTION_HEAD_COUNT_KV).c_str(), hparams.n_head);
|
||||
gguf_set_val_f32(gdst.get(), key(LLM_KV_ATTENTION_LAYERNORM_EPS).c_str(), hparams.eps);
|
||||
gguf_set_val_f32(gdst.get(), key(LLM_KV_ROPE_FREQ_BASE).c_str(), mtmd_graph_tiny_voca::rope_theta);
|
||||
gguf_set_val_bool(gdst.get(), key(LLM_KV_ATTENTION_CAUSAL).c_str(), false);
|
||||
|
||||
size_t n_tensors = 0;
|
||||
llama_model * model = mtmd_owned_llama_load(fname, device, gdst.get(), prefix, n_tensors);
|
||||
if (n_tensors != (size_t) n_layer * 18 + 2) {
|
||||
llama_model_free(model);
|
||||
throw std::runtime_error(mtmd_format("tiny_voca: unexpected tensors under %s in the mmproj", prefix));
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
|
@ -731,6 +777,11 @@ struct mtmd_context {
|
|||
llama_model_ptr yue2_nar;
|
||||
llama_flash_attn_type yue2_flash_attn = LLAMA_FLASH_ATTN_TYPE_AUTO;
|
||||
|
||||
// tiny-voca: the frame stacks, run on llama_contexts of their own, see mtmd_gen_wav_tiny_voca()
|
||||
llama_model_ptr tiny_voca_prosody;
|
||||
llama_model_ptr tiny_voca_acoustic;
|
||||
llama_flash_attn_type tiny_voca_flash_attn = LLAMA_FLASH_ATTN_TYPE_AUTO;
|
||||
|
||||
// gen-side reference data of the last encoded chunk (chatterbox), see mtmd_gen_state_set_ref()
|
||||
mtmd_gen_ref gen_ref;
|
||||
|
||||
|
|
@ -868,6 +919,13 @@ struct mtmd_context {
|
|||
yue2_nar.reset(mtmd_yue2_nar_load(mmproj_fname, device, models.gen_a->hparams));
|
||||
yue2_flash_attn = ctx_params.flash_attn_type;
|
||||
}
|
||||
if (models.gen_a && models.gen_a->proj_type == PROJECTOR_TYPE_TINY_VOCA && !no_alloc) {
|
||||
using g = mtmd_graph_tiny_voca;
|
||||
const auto & hp = models.gen_a->hparams;
|
||||
tiny_voca_prosody .reset(mtmd_tiny_voca_stack_load(mmproj_fname, device, hp, "a.gen.prosody.", g::n_prosody_layer));
|
||||
tiny_voca_acoustic.reset(mtmd_tiny_voca_stack_load(mmproj_fname, device, hp, "a.gen.acoustic.", g::n_acoustic_layer));
|
||||
tiny_voca_flash_attn = ctx_params.flash_attn_type;
|
||||
}
|
||||
for (size_t i = 0; i < backends->ptrs.size(); ++i) {
|
||||
const size_t size = ggml_backend_sched_get_buffer_size(backends->sched.get(), backends->ptrs[i]);
|
||||
if (size > 1) {
|
||||
|
|
@ -2680,6 +2738,8 @@ mtmd_gen_audio_info mtmd_gen_audio_get_info(const mtmd_context * ctx) {
|
|||
info.type = MTMD_GEN_AUDIO_TYPE_ZONOS3;
|
||||
info.sample_rate = 44100;
|
||||
break;
|
||||
info.sample_rate = 24000;
|
||||
break;
|
||||
case PROJECTOR_TYPE_YUE2_GEN:
|
||||
info.type = MTMD_GEN_AUDIO_TYPE_YUE2;
|
||||
info.sample_rate = 48000;
|
||||
|
|
@ -2698,6 +2758,10 @@ mtmd_gen_audio_info mtmd_gen_audio_get_info(const mtmd_context * ctx) {
|
|||
info.type = MTMD_GEN_AUDIO_TYPE_KOKORO;
|
||||
info.sample_rate = 24000;
|
||||
break;
|
||||
case PROJECTOR_TYPE_TINY_VOCA:
|
||||
info.type = MTMD_GEN_AUDIO_TYPE_TINY_VOCA;
|
||||
info.sample_rate = 24000;
|
||||
break;
|
||||
default:
|
||||
info.type = MTMD_GEN_AUDIO_TYPE_NONE;
|
||||
break;
|
||||
|
|
@ -3054,6 +3118,21 @@ static int32_t cbx_ref_encode(mtmd_context * ctx, const mtmd_audio_tokens * audi
|
|||
return 0;
|
||||
}
|
||||
|
||||
int32_t mtmd_gen_audio_g2p(const mtmd_context * ctx, const char * word, char * buf, size_t buf_size) {
|
||||
if (!ctx || !ctx->ctx_gen_a || !word || !buf || buf_size == 0) {
|
||||
return 0;
|
||||
}
|
||||
std::string out;
|
||||
if (ctx->ctx_gen_a->model.proj_type == PROJECTOR_TYPE_TINY_VOCA) {
|
||||
out = mtmd_graph_tiny_voca::g2p(ctx->ctx_gen_a->model.tiny_voca, word);
|
||||
}
|
||||
if (out.size() + 1 > buf_size) {
|
||||
return -1;
|
||||
}
|
||||
memcpy(buf, out.c_str(), out.size() + 1);
|
||||
return (int32_t) out.size();
|
||||
}
|
||||
|
||||
const char * mtmd_gen_audio_voice_name(const mtmd_context * ctx, int32_t idx) {
|
||||
if (!ctx->ctx_gen_a || idx < 0) {
|
||||
return nullptr;
|
||||
|
|
@ -3116,6 +3195,7 @@ mtmd_gen_inp mtmd_gen_inp_default(const mtmd_context * ctx) {
|
|||
break;
|
||||
case PROJECTOR_TYPE_SOPRANO:
|
||||
case PROJECTOR_TYPE_KOKORO:
|
||||
case PROJECTOR_TYPE_TINY_VOCA:
|
||||
inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
|
||||
break;
|
||||
case PROJECTOR_TYPE_MINIMAX_MUSIC3_GEN:
|
||||
|
|
@ -3338,8 +3418,8 @@ static int32_t mtmd_gen_wav_lfm3a(mtmd_context * ctx, mtmd_gen_state * state, co
|
|||
return 0;
|
||||
}
|
||||
|
||||
// yue2: one pass of an mtmd graph, rows in -> rows out (PCM for GEN_WAV)
|
||||
static bool yue2_encode(mtmd_context * ctx, mtmd_gen_state * state, mtmd_subctx_gen_process proc, const std::vector<float> & in, std::vector<float> & out) {
|
||||
// one pass of an mtmd graph, rows in -> rows out (PCM for GEN_WAV), used by yue2 and tiny-voca
|
||||
static bool gen_encode_rows(mtmd_context * ctx, mtmd_gen_state * state, mtmd_subctx_gen_process proc, const std::vector<float> & in, std::vector<float> & out) {
|
||||
mtmd_image_f32 dummy;
|
||||
dummy.set_size({1, 1}, false, true);
|
||||
dummy.cpy_buf(std::vector<float>(1, 0.0f));
|
||||
|
|
@ -3464,7 +3544,7 @@ static int32_t mtmd_gen_flow_yue2(mtmd_context * ctx, mtmd_gen_state * state, co
|
|||
std::vector<float> embd, hidden, vel;
|
||||
auto velocity = [&](const std::vector<float> & x, double t, std::vector<float> & v) -> bool {
|
||||
std::copy(x.begin(), x.end(), x_rows.begin() + g::n_latent); // the start and end rows stay 0
|
||||
if (!yue2_encode(ctx, state, MTMD_SUBCTX_GEN_PROCESS_LATENT_IN, x_rows, embd)) {
|
||||
if (!gen_encode_rows(ctx, state, MTMD_SUBCTX_GEN_PROCESS_LATENT_IN, x_rows, embd)) {
|
||||
return false;
|
||||
}
|
||||
const std::vector<float> temb = time_embd(t);
|
||||
|
|
@ -3490,7 +3570,7 @@ static int32_t mtmd_gen_flow_yue2(mtmd_context * ctx, mtmd_gen_state * state, co
|
|||
const float * h = llama_get_embeddings(lctx.get());
|
||||
hidden.assign(h, h + n_rows * n_embd);
|
||||
llama_memory_seq_rm(mem, 0, (llama_pos) n_past, -1);
|
||||
if (!yue2_encode(ctx, state, MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT, hidden, vel)) {
|
||||
if (!gen_encode_rows(ctx, state, MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT, hidden, vel)) {
|
||||
return false;
|
||||
}
|
||||
v.assign(vel.begin() + g::n_latent, vel.end() - g::n_latent);
|
||||
|
|
@ -3529,6 +3609,160 @@ static int32_t mtmd_gen_flow_yue2(mtmd_context * ctx, mtmd_gen_state * state, co
|
|||
return 0;
|
||||
}
|
||||
|
||||
// tiny-voca: one pass of a frame stack, embedding rows in -> hidden rows out
|
||||
static bool tiny_voca_stack(mtmd_context * ctx, llama_model * model, const std::vector<float> & in, std::vector<float> & out) {
|
||||
const int64_t n_embd = llama_model_n_embd(model);
|
||||
const int32_t n_rows = (int32_t) (in.size() / n_embd);
|
||||
|
||||
llama_context_params cparams = llama_context_default_params();
|
||||
cparams.n_ctx = (uint32_t) n_rows;
|
||||
cparams.n_batch = (uint32_t) n_rows;
|
||||
cparams.n_ubatch = (uint32_t) n_rows; // non-causal, all rows must be in one ubatch
|
||||
cparams.n_seq_max = 1;
|
||||
cparams.n_threads = ctx->n_threads;
|
||||
cparams.n_threads_batch = ctx->n_threads;
|
||||
cparams.embeddings = true;
|
||||
cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
|
||||
cparams.attention_type = LLAMA_ATTENTION_TYPE_NON_CAUSAL;
|
||||
cparams.flash_attn_type = ctx->tiny_voca_flash_attn;
|
||||
cparams.no_perf = true;
|
||||
llama_context_ptr lctx(llama_init_from_model(model, cparams));
|
||||
if (!lctx) {
|
||||
LOG_ERR("%s: failed to create the context of a frame stack\n", __func__);
|
||||
return false;
|
||||
}
|
||||
|
||||
llama_batch_ext_ptr batch(llama_batch_ext_init(lctx.get()));
|
||||
for (int32_t i = 0; i < n_rows; i++) {
|
||||
const llama_embd row = { in.data() + (size_t) i * n_embd, 1, (size_t) n_embd };
|
||||
const llama_pos p = i;
|
||||
const int32_t idx = llama_batch_ext_add_embd(batch.get(), 0, row);
|
||||
if (idx < 0) {
|
||||
LOG_ERR("%s: failed to add a row to the batch (error %d)\n", __func__, idx);
|
||||
return false;
|
||||
}
|
||||
llama_batch_ext_set_pos(batch.get(), idx, &p);
|
||||
llama_batch_ext_set_output_embd(batch.get(), idx, true);
|
||||
}
|
||||
if (llama_process(lctx.get(), LLAMA_PROCESS_TYPE_DECODE, batch.get()) != 0) {
|
||||
LOG_ERR("%s: frame stack decode failed\n", __func__);
|
||||
return false;
|
||||
}
|
||||
const float * h = llama_get_embeddings(lctx.get());
|
||||
out.assign(h, h + (size_t) n_rows * n_embd);
|
||||
return true;
|
||||
}
|
||||
|
||||
// tiny-voca GEN_WAV: phoneme tokens + encoder states -> waveform, see TinyVoca.synthesize() in the reference (model.py)
|
||||
// codes: the tokens; feats: the voice row (encoder half, frame half), then the encoder state of each token
|
||||
static int32_t mtmd_gen_wav_tiny_voca(mtmd_context * ctx, mtmd_gen_state * state, const mtmd_gen_inp * inp, mtmd_gen_out * out) {
|
||||
using g = mtmd_graph_tiny_voca;
|
||||
const auto & tv = ctx->ctx_gen_a->model.tiny_voca;
|
||||
const int64_t n_embd = ctx->ctx_gen_a->model.hparams.n_embd;
|
||||
const int64_t n_tok = (int64_t) inp->n_codes;
|
||||
|
||||
if (inp->type != MTMD_GEN_PROCESS_TYPE_GEN_WAV || !inp->codes || n_tok == 0 || !inp->feats ||
|
||||
inp->n_feats != (size_t) ((2 + n_tok) * n_embd)) {
|
||||
LOG_ERR("%s: tiny_voca requires the phoneme tokens, the voice row and the encoder state of each token\n", __func__);
|
||||
return 1;
|
||||
}
|
||||
if (!std::isfinite(inp->speed) || inp->speed < 0.25f || inp->speed > 4.0f) {
|
||||
LOG_ERR("%s: speed must be between 0.25 and 4\n", __func__);
|
||||
return 1;
|
||||
}
|
||||
for (int64_t i = 0; i < n_tok; i++) {
|
||||
if (inp->codes[i] < 0 || inp->codes[i] >= (int32_t) tv.token_class.size()) {
|
||||
LOG_ERR("%s: token out of range (%d)\n", __func__, inp->codes[i]);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
const float * frame_voice = inp->feats + n_embd;
|
||||
const std::vector<float> hidden(inp->feats + 2 * n_embd, inp->feats + inp->n_feats);
|
||||
|
||||
std::vector<float> dur_out;
|
||||
if (!gen_encode_rows(ctx, state, MTMD_SUBCTX_GEN_PROCESS_LATENT_IN, hidden, dur_out) || dur_out.size() != (size_t) (2 * n_tok)) {
|
||||
LOG_ERR("%s: duration predictor failed\n", __func__);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// frames per token: a phone lasts at least one frame, a pause token only when its presence logit is > 0
|
||||
std::vector<int64_t> dur(n_tok);
|
||||
int64_t n_frames = 0;
|
||||
for (int64_t i = 0; i < n_tok; i++) {
|
||||
const float o0 = std::clamp(dur_out[2 * i], 0.0f, std::log1p(g::max_dur));
|
||||
const double frames = std::max(1.0, std::nearbyint((double) std::expm1(o0) / inp->speed));
|
||||
const bool phone = tv.token_class[inp->codes[i]] > 0.0f;
|
||||
dur[i] = phone || dur_out[2 * i + 1] > 0.0f ? (int64_t) frames : 0;
|
||||
n_frames += dur[i];
|
||||
}
|
||||
if (n_frames < 1 || n_frames > g::n_max_frames) {
|
||||
LOG_ERR("%s: the utterance has %lld frames, it must have 1 to %d, split the text\n", __func__, (long long) n_frames, g::n_max_frames);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// token states repeated by their duration, plus the position inside the token and the frame voice
|
||||
std::vector<float> x((size_t) (n_frames * n_embd));
|
||||
std::vector<int64_t> owner(n_frames);
|
||||
for (int64_t i = 0, f = 0; i < n_tok; i++) {
|
||||
for (int64_t o = 0; o < dur[i]; o++, f++) {
|
||||
const float rel = ((float) o + 0.5f) / (float) dur[i];
|
||||
const float feat[3] = { rel, 1.0f - rel, std::log1p((float) dur[i]) / 4.0f };
|
||||
float * row = x.data() + f * n_embd;
|
||||
for (int64_t c = 0; c < n_embd; c++) {
|
||||
const float * w = tv.frame_pos_w.data() + c * 3;
|
||||
row[c] = hidden[i * n_embd + c] + tv.frame_pos_b[c] + w[0] * feat[0] + w[1] * feat[1] + w[2] * feat[2] + frame_voice[c];
|
||||
}
|
||||
owner[f] = i;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<float> h_pro;
|
||||
if (!tiny_voca_stack(ctx, ctx->tiny_voca_prosody.get(), x, h_pro)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// pitch, voicing and energy; the frames of a vowel are always voiced
|
||||
std::vector<float> f0(n_frames);
|
||||
for (int64_t f = 0; f < n_frames; f++) {
|
||||
float p[3];
|
||||
const float * h = h_pro.data() + f * n_embd;
|
||||
for (int k = 0; k < 3; k++) {
|
||||
const float * w = tv.prosody_head_w.data() + k * n_embd;
|
||||
float acc = tv.prosody_head_b[k];
|
||||
for (int64_t c = 0; c < n_embd; c++) {
|
||||
acc += w[c] * h[c];
|
||||
}
|
||||
p[k] = acc;
|
||||
}
|
||||
if (tv.token_class[inp->codes[owner[f]]] == 2.0f) {
|
||||
p[1] = std::max(p[1], 2.0f);
|
||||
}
|
||||
f0[f] = std::clamp(g::f0_ref * std::exp(p[0]), g::f0_min, g::f0_max);
|
||||
|
||||
// the acoustic stack is conditioned on the clamped pitch and energy and the hard voicing decision
|
||||
const float cond[3] = { std::clamp(p[0], -2.0f, 1.5f), p[1] > 0.0f ? 1.0f : 0.0f, std::clamp(p[2], -4.5f, 3.0f) };
|
||||
float * row = x.data() + f * n_embd;
|
||||
for (int64_t c = 0; c < n_embd; c++) {
|
||||
const float * w = tv.prosody_proj_w.data() + c * 3;
|
||||
row[c] = h[c] + tv.prosody_proj_b[c] + w[0] * cond[0] + w[1] * cond[1] + w[2] * cond[2];
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<float> h_ac, voc;
|
||||
if (!tiny_voca_stack(ctx, ctx->tiny_voca_acoustic.get(), x, h_ac)) {
|
||||
return 1;
|
||||
}
|
||||
if (!gen_encode_rows(ctx, state, MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT, h_ac, voc) || voc.size() != (size_t) (n_frames * g::n_voc)) {
|
||||
LOG_ERR("%s: source-filter heads failed\n", __func__);
|
||||
return 1;
|
||||
}
|
||||
|
||||
g::synth(voc, f0, state->gen_state->rng, state->out_audio);
|
||||
out->audio = state->out_audio.data();
|
||||
out->n_samples = state->out_audio.size();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// yue2 GEN_WAV: latents -> interleaved stereo PCM in one VAE pass, the caller splits a long song into tiles
|
||||
static int32_t mtmd_gen_wav_yue2(mtmd_context * ctx, mtmd_gen_state * state, const mtmd_gen_inp * inp, mtmd_gen_out * out) {
|
||||
using g = mtmd_graph_yue2_gen;
|
||||
|
|
@ -3538,7 +3772,7 @@ static int32_t mtmd_gen_wav_yue2(mtmd_context * ctx, mtmd_gen_state * state, con
|
|||
}
|
||||
const std::vector<float> feats(inp->feats, inp->feats + inp->n_feats);
|
||||
auto & audio = state->out_audio;
|
||||
if (!yue2_encode(ctx, state, MTMD_SUBCTX_GEN_PROCESS_GEN_WAV, feats, audio)) {
|
||||
if (!gen_encode_rows(ctx, state, MTMD_SUBCTX_GEN_PROCESS_GEN_WAV, feats, audio)) {
|
||||
LOG_ERR("%s: encode failed (vae)\n", __func__);
|
||||
return 1;
|
||||
}
|
||||
|
|
@ -3736,6 +3970,10 @@ static int32_t mtmd_gen_audio_process_impl(mtmd_context * ctx, mtmd_gen_state *
|
|||
: mtmd_gen_wav_music3(ctx, state, inp, out);
|
||||
}
|
||||
|
||||
if (sctx->model.proj_type == PROJECTOR_TYPE_TINY_VOCA) {
|
||||
return mtmd_gen_wav_tiny_voca(ctx, state, inp, out);
|
||||
}
|
||||
|
||||
if (sctx->model.proj_type == PROJECTOR_TYPE_SOPRANO) {
|
||||
const size_t n_embd = (size_t) sctx->model.n_mmproj_embd();
|
||||
if (inp->type != MTMD_GEN_PROCESS_TYPE_GEN_WAV || !inp->feats || inp->n_feats < 2 * n_embd || inp->n_feats % n_embd != 0 || inp->codes) {
|
||||
|
|
|
|||
|
|
@ -479,6 +479,7 @@ enum mtmd_gen_audio_type {
|
|||
MTMD_GEN_AUDIO_TYPE_MINIMAX_MUSIC3,
|
||||
MTMD_GEN_AUDIO_TYPE_FISH_S2,
|
||||
MTMD_GEN_AUDIO_TYPE_KOKORO,
|
||||
MTMD_GEN_AUDIO_TYPE_TINY_VOCA,
|
||||
};
|
||||
|
||||
struct mtmd_gen_audio_info {
|
||||
|
|
@ -496,6 +497,12 @@ MTMD_API size_t mtmd_gen_audio_read_tensor(mtmd_context * ctx, const char * name
|
|||
// name of the idx-th predefined voice, nullptr when idx is out of range; idx 0 is the default voice
|
||||
MTMD_API const char * mtmd_gen_audio_voice_name(const mtmd_context * ctx, int32_t idx);
|
||||
|
||||
// pronunciation of a word by the letter-to-sound model of the mmproj, for the tts_g2p() of the "tts" chat template
|
||||
// (see common_chat_get_tts_prompt()); the phonemes are separated by spaces, in the notation of the model (tiny-voca: CMUdict)
|
||||
// returns the length written to buf (NUL terminated), 0 if the model has no letter-to-sound model or no pronunciation,
|
||||
// -1 if buf is too small; does not run a graph, can be called from any thread
|
||||
MTMD_API int32_t mtmd_gen_audio_g2p(const mtmd_context * ctx, const char * word, char * buf, size_t buf_size);
|
||||
|
||||
// predefined voice with this name as a voice bitmap, to pass as speaker reference
|
||||
// returns nullptr if there is no such voice, the caller must free it
|
||||
MTMD_API mtmd_bitmap * mtmd_gen_audio_get_voice(const mtmd_context * ctx, const char * name);
|
||||
|
|
|
|||
|
|
@ -6986,7 +6986,11 @@ std::unique_ptr<server_res_generator> server_routes::handle_tts_impl(const serve
|
|||
const std::string voice = json_value(body, "voice", has_speaker_ref ? std::string() : params.tts_voice);
|
||||
// raw_prompt: the input goes to the model as is (e.g. phonemes), the "tts" chat template is skipped
|
||||
const bool raw_prompt = json_value(body, "raw_prompt", false);
|
||||
const std::string tts_prompt = raw_prompt ? std::string() : common_chat_get_tts_prompt(meta->chat_params.tmpls.get(), prompt, lang, voice);
|
||||
const auto g2p = [this](const std::string & word) {
|
||||
char buf[512];
|
||||
return mtmd_gen_audio_g2p(ctx_server.mctx, word.c_str(), buf, sizeof(buf)) > 0 ? std::string(buf) : std::string();
|
||||
};
|
||||
const std::string tts_prompt = raw_prompt ? std::string() : common_chat_get_tts_prompt(meta->chat_params.tmpls.get(), prompt, lang, voice, g2p);
|
||||
// a model with predefined voices only speaks with one of them
|
||||
mtmd::bitmap_ptr voice_ref;
|
||||
if (!voice.empty() && info.n_voices > 0) {
|
||||
|
|
|
|||
|
|
@ -137,7 +137,10 @@ int main(int argc, char ** argv) {
|
|||
auto tmpls = common_chat_templates_init(model, "");
|
||||
std::string prompt;
|
||||
try {
|
||||
prompt = common_chat_get_tts_prompt(tmpls.get(), params.prompt, params.tts_lang, params.tts_voice);
|
||||
prompt = common_chat_get_tts_prompt(tmpls.get(), params.prompt, params.tts_lang, params.tts_voice, [&](const std::string & word) {
|
||||
char buf[512];
|
||||
return mtmd_gen_audio_g2p(mctx.get(), word.c_str(), buf, sizeof(buf)) > 0 ? std::string(buf) : std::string();
|
||||
});
|
||||
} catch (const std::exception & e) {
|
||||
LOG_ERR("failed to prepare the text to speak: %s\n", e.what());
|
||||
return 1;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue