Skip to content

Commit cc9e4cb

Browse files
hans00claude
andcommitted
feat(tts): use llama.cpp common_sampler for backbone logits + prompt-derived GBNF grammar
Backbone-logits sampling (the cb0-from-backbone token in run_codebook_ar — MOSS-TTSD's merged text+speech vocab) now goes through llama.cpp's `common` sampling layer (common_sampler) instead of a hand-rolled llama_sampler chain, so chain assembly, grammar apply/resample, and penalty bookkeeping are reused rather than reimplemented. codec_lm audio-codebook heads (residual depth decoder, Chatterbox speech_head) and the LFM2 recomputed text logits stay on the raw SamplerChain — they are arbitrary float arrays not tied to a llama_context, so common_sampler (which reads llama_get_logits_ith) can't drive them and grammar never applies there. The split is documented in tts_runner.cpp. Grammar support: * tts_runner_params.grammar — user-supplied GBNF passthrough (attached to the backbone sampler when non-empty). * codec_common::tts_auto_grammar(pi, text) — metadata-driven GBNF generator (ported concept from llama.rn rn-tts build_dynamic_grammar). First application: MOSS-TTSD cb0 — constrains decode-phase cb0 to the speech-token range [cb0_speech_range_start, cb0_speech_range_end) ∪ {eos_code_c0} so the backbone can't drift into arbitrary text tokens mid-utterance. The speech range detokenizes as the pieces "<0>".."<1023>" + "<|end_of_speech|>"; the HF reference (modeling_moss_ttsd) treats a non-speech cb0 as its natural stop trigger, so eos stays permitted (a hard speech-only constraint would be wrong). User grammar overrides auto. Build plumbing (cmake/SetupTtsBackbone.cmake): enable LLAMA_BUILD_COMMON and export the mangled common_sampler_* C++ symbols through libttsbackbone.so via an unquoted `extern "C++" { common_sampler*; }` version-script glob; the three common archives (llama-common, llama-common-base, cpp-httplib) go inside the --whole-archive group so the symbols survive to the version script. Verified: 19 common_sampler symbols exported, 233 llama_ symbols, 0 ggml_ symbols — the ggml 0.15 isolation is preserved (common references ggml only as undefined symbols resolved internally against the bundled ggml). Metadata: moss_ttsd.py converter now also writes codec.lm.cb0_speech_range_end (scalar mirror of speech_token_range[1]); audio_lm surfaces both range bounds on audio_lm_prompt_info. tts-cli: --grammar FILE|STRING flag (loads file contents or literal GBNF). Verify: cold ExternalProject rebuild links clean; common_sampler_* resolves at runtime. ttscli_synthesize_smoke 8/8 with matching stop reasons; CSM greedy byte-identical (cb0_from_backbone=0, never touches common_sampler; CER 0.000); MOSS-TTSD CER 0.143 unchanged (auto-grammar, greedy) — no regression, drift guard active under sampling. Bogus --grammar → clean "failed to parse grammar" error, no crash. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 92e9884 commit cc9e4cb

7 files changed

Lines changed: 338 additions & 23 deletions

File tree

‎cmake/SetupTtsBackbone.cmake‎

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,32 @@
1818

1919
include(ExternalProject)
2020

21-
set(_ll_dir "${CMAKE_CURRENT_SOURCE_DIR}/common/third-party/llama.cpp")
22-
set(_ll_prefix "${CMAKE_BINARY_DIR}/llama-static")
23-
set(_ll_libdir "${_ll_prefix}/src/llama-build/src")
24-
set(_ll_ggmldir "${_ll_prefix}/src/llama-build/ggml/src")
21+
set(_ll_dir "${CMAKE_CURRENT_SOURCE_DIR}/common/third-party/llama.cpp")
22+
set(_ll_prefix "${CMAKE_BINARY_DIR}/llama-static")
23+
set(_ll_libdir "${_ll_prefix}/src/llama-build/src")
24+
set(_ll_ggmldir "${_ll_prefix}/src/llama-build/ggml/src")
25+
set(_ll_commondir "${_ll_prefix}/src/llama-build/common")
26+
set(_ll_vendordir "${_ll_prefix}/src/llama-build/vendor")
2527

2628
# Static archives ExternalProject will produce.
29+
#
30+
# The `common` layer (LLAMA_BUILD_COMMON=ON below) gives us the shared
31+
# sampling API (common_sampler_*, common_params_sampling, common_grammar
32+
# GBNF integration) instead of hand-rolled llama_sampler chains. Its
33+
# CMake target is `llama-common` → libllama-common.a, which drags in
34+
# libllama-common-base.a (build-info) and vendor/cpp-httplib (a PRIVATE
35+
# header-lib TU). All three MUST sit inside the --whole-archive group at
36+
# wrapper-link time (below): nothing in llama/ggml references common's
37+
# symbols, so outside --whole-archive the linker would drop the objects
38+
# before the version script could export common_sampler_*. Verified: none
39+
# of these archives DEFINE bare ggml_* symbols (they reference them as
40+
# undefined, resolved internally against the bundled ggml 0.15) so the
41+
# `local: *` catch-all still hides every ggml_* — no ABI leak.
2742
set(_ll_archives
2843
"${_ll_libdir}/libllama.a"
44+
"${_ll_commondir}/libllama-common.a"
45+
"${_ll_commondir}/libllama-common-base.a"
46+
"${_ll_vendordir}/cpp-httplib/libcpp-httplib.a"
2947
"${_ll_ggmldir}/libggml.a"
3048
"${_ll_ggmldir}/libggml-cpu.a"
3149
"${_ll_ggmldir}/libggml-base.a")
@@ -43,21 +61,29 @@ ExternalProject_Add(llama_static
4361
-DLLAMA_BUILD_TOOLS=OFF
4462
-DLLAMA_BUILD_SERVER=OFF
4563
-DLLAMA_BUILD_APP=OFF
46-
-DLLAMA_BUILD_COMMON=OFF
64+
-DLLAMA_BUILD_COMMON=ON
4765
-DLLAMA_CURL=OFF
4866
-DLLAMA_OPENSSL=OFF
4967
-DGGML_NATIVE=ON
5068
-DGGML_VULKAN=OFF
5169
-DGGML_BACKEND_DL=OFF
52-
BUILD_COMMAND ${CMAKE_COMMAND} --build <BINARY_DIR> --target llama --config Release
70+
BUILD_COMMAND ${CMAKE_COMMAND} --build <BINARY_DIR> --target llama-common --config Release
5371
BUILD_BYPRODUCTS ${_ll_archives}
5472
INSTALL_COMMAND ""
5573
UPDATE_COMMAND ""
5674
)
5775

58-
# Version script: export only llama_* on the wrapper's dynamic table.
76+
# Version script: export llama_* (C ABI) + the common_sampler_* C++ API on
77+
# the wrapper's dynamic table; hide everything else (ggml_* included) as
78+
# local. The `extern "C++"` block matches the DEMANGLED name, and the glob
79+
# MUST be unquoted for `*` to act as a wildcard (a quoted "common_sampler*"
80+
# is a literal and matches nothing). This exports common_sampler_init /
81+
# _free / _accept / _reset / _sample / _get and friends. common_grammar
82+
# and common_params_sampling need no exported symbols (plain struct; its
83+
# ctor/dtor are emitted inline in the codec_tts_runner TU).
5984
set(_ll_vscript "${CMAKE_BINARY_DIR}/ttsbackbone.map")
60-
file(WRITE "${_ll_vscript}" "{\n global:\n llama_*;\n local:\n *;\n};\n")
85+
file(WRITE "${_ll_vscript}"
86+
"{\n global:\n llama_*;\n extern \"C++\" {\n common_sampler*;\n };\n local:\n *;\n};\n")
6187

6288
set(TTS_BACKBONE_SO "${CMAKE_BINARY_DIR}/ttsbackbone/libttsbackbone.so")
6389
add_custom_command(
@@ -72,8 +98,10 @@ add_custom_command(
7298
VERBATIM)
7399
add_custom_target(ttsbackbone DEPENDS "${TTS_BACKBONE_SO}")
74100

75-
# Exported for the tts-cli target.
101+
# Exported for the tts-cli target. `common` is added so the runner can
102+
# include common.h / sampling.h (the common_sampler API).
76103
set(TTS_BACKBONE_INCLUDE_DIRS
77104
"${_ll_dir}/include"
78105
"${_ll_dir}/ggml/include"
106+
"${_ll_dir}/common"
79107
CACHE INTERNAL "llama backbone include dirs")

‎common/audio_lm.cpp‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -881,6 +881,11 @@ bool audio_lm_get_prompt_info(const audio_lm_context * ctx,
881881
out->eos_code_c0 = info->eos_code_c0;
882882
out->eos_min_step = info->eos_min_step;
883883
}
884+
// Merged-cb0 speech sub-range (MOSS-TTSD) — surfaced for the host's
885+
// auto-grammar. cb0_speech_offset is speech_token_range[0] (start);
886+
// cb0_speech_range_end mirrors speech_token_range[1] (exclusive end).
887+
out->cb0_speech_range_start = meta_i32_or(ctx, "codec.lm.cb0_speech_offset", -1);
888+
out->cb0_speech_range_end = meta_i32_or(ctx, "codec.lm.cb0_speech_range_end", -1);
884889
// rn-tts sampling defaults.
885890
out->default_temperature = 0.9f;
886891
out->default_top_p = 0.95f;
@@ -1051,6 +1056,98 @@ bool audio_lm_get_prompt_info(const audio_lm_context * ctx,
10511056
return true;
10521057
}
10531058

1059+
// Emit a GBNF alternation matching the decimal literals [lo, hi] (inclusive),
1060+
// as `"<" ( ... ) ">"`-style terminals are assembled by the caller. Rather
1061+
// than a full digit-range decomposition we lean on the fact that GBNF can
1062+
// enumerate a bounded set compactly via nested digit ranges; for a 0..N-1
1063+
// speech vocab this stays small. We build the classic "0..max" numeric rule
1064+
// used by the rn-tts NeuTTS/Soprano grammars (decade/hundred/thousand digit
1065+
// bands) generalised to `max`.
1066+
static std::string gbnf_uint_range_rule(int32_t max_inclusive) {
1067+
// Produce alternatives for [0, max_inclusive]. We special-case up to
1068+
// 9999 (covers MOSS-TTSD's 0..1023); larger vocabs fall back to a loose
1069+
// "[0-9]+" (still correct membership-wise for the model's own emissions,
1070+
// just not a tight upper bound).
1071+
if (max_inclusive < 0) return "[0-9]+";
1072+
if (max_inclusive > 9999) return "[0-9]+";
1073+
// NOTE: keep the whole alternation on ONE line — llama.cpp's GBNF parser
1074+
// treats a bare newline as the end of a rule, so `\n | ...` continuations
1075+
// fail with "expecting name at |".
1076+
std::string out;
1077+
auto add = [&](const std::string & alt) {
1078+
if (!out.empty()) out += " | ";
1079+
out += alt;
1080+
};
1081+
// single digit 0..9 (bounded by max)
1082+
{
1083+
int hi = max_inclusive < 9 ? max_inclusive : 9;
1084+
add("[0-" + std::to_string(hi) + "]");
1085+
}
1086+
// two digits 10..99
1087+
if (max_inclusive >= 10) add("[1-9] [0-9]");
1088+
// three digits 100..999
1089+
if (max_inclusive >= 100) add("[1-9] [0-9] [0-9]");
1090+
// four digits 1000..max (tight upper bound on the leading digit band)
1091+
if (max_inclusive >= 1000) {
1092+
// Enumerate 1000..max_inclusive by leading-digit bands so we don't
1093+
// over-admit (e.g. max=1023 must not accept 1099). Keep it simple:
1094+
// a loose "[1-9] [0-9] [0-9] [0-9]" would over-admit up to 9999; for
1095+
// the common 0..1023 case emit an exact band for the thousands.
1096+
const int thousands = max_inclusive / 1000; // e.g. 1
1097+
const int rem = max_inclusive % 1000; // e.g. 23
1098+
// full lower thousands: [1 .. thousands-1] followed by any 3 digits
1099+
if (thousands >= 2) {
1100+
add("[1-" + std::to_string(thousands - 1) + "] [0-9] [0-9] [0-9]");
1101+
}
1102+
// the top thousand band, capped at rem
1103+
// thousands digit is fixed; the trailing 3 digits are 000..rem
1104+
std::string band = "\"" + std::to_string(thousands) + "\" ";
1105+
const int h = rem / 100, t = (rem / 10) % 10, o = rem % 10;
1106+
// 000..(h-1)99 | h(0..t-1)9? ... approximate tight bound
1107+
std::string sub;
1108+
auto addsub = [&](const std::string & a) {
1109+
if (!sub.empty()) sub += " | ";
1110+
sub += a;
1111+
};
1112+
if (h >= 1) addsub("[0-" + std::to_string(h - 1) + "] [0-9] [0-9]");
1113+
if (t >= 1) addsub("\"" + std::to_string(h) + "\" [0-" + std::to_string(t - 1) + "] [0-9]");
1114+
addsub("\"" + std::to_string(h) + "\" \"" + std::to_string(t) + "\" [0-" + std::to_string(o) + "]");
1115+
add(band + "( " + sub + " )");
1116+
}
1117+
return out;
1118+
}
1119+
1120+
std::string tts_auto_grammar(const audio_lm_prompt_info & pi,
1121+
const std::string & text) {
1122+
(void) text; // reserved for future prompt-dependent grammars
1123+
1124+
// MOSS-TTSD (and any merged-cb0 parallel-heads-delay model): constrain
1125+
// decode-phase cb0 to the speech-token range ∪ {eos_code_c0}. The
1126+
// backbone tokens for the speech sub-range detokenize as the decimal
1127+
// pieces "<0>".."<N-1>" (N = range_end - range_start); the end sentinel
1128+
// detokenizes to a fixed control string. We match those piece strings.
1129+
if (pi.model_kind == audio_lm_prompt_info::KIND_PARALLEL_HEADS_DELAY &&
1130+
pi.cb0_from_backbone &&
1131+
pi.cb0_speech_range_start >= 0 &&
1132+
pi.cb0_speech_range_end > pi.cb0_speech_range_start) {
1133+
const int32_t n_speech = pi.cb0_speech_range_end - pi.cb0_speech_range_start;
1134+
const std::string num_rule = gbnf_uint_range_rule(n_speech - 1);
1135+
// A speech frame's cb0 is one "<CODE>" piece; audio ends with the
1136+
// end-of-speech sentinel. The delay-pattern tail frames (cb0 forced
1137+
// to eos while cb1..N flush) are handled by the runtime, not the
1138+
// grammar, so `end` may appear once and then trailing eos repeats are
1139+
// allowed too (end+ ) to cover the flush window.
1140+
std::string g;
1141+
g += "root ::= speech* end+\n";
1142+
g += "speech ::= \"<\" SPEECHID \">\"\n";
1143+
g += "end ::= \"<|end_of_speech|>\"\n";
1144+
g += "SPEECHID ::= " + num_rule + "\n";
1145+
return g;
1146+
}
1147+
1148+
return "";
1149+
}
1150+
10541151
// ─── Codebook step machine passthroughs ─────────────────────────────
10551152

10561153
bool audio_lm_step_set_text_context(audio_lm_context * ctx, int32_t text_token) {

‎common/codec_common.h‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,13 +456,48 @@ struct audio_lm_prompt_info {
456456
int32_t audio_start_id = -1; // text token → switch to AUDIO_OUT
457457
int32_t text_end_id = -1; // text token → end turn / stop
458458
int32_t max_text_tokens = 64; // safety cap on the text warmup phase
459+
460+
// ── Merged-cb0 speech sub-range (MOSS-TTSD) ─────────────────────────
461+
// For parallel-heads-delay models whose cb0 is a merged text+speech
462+
// vocab, speech codes occupy [cb0_speech_range_start, cb0_speech_range_end)
463+
// of the backbone vocab (from codec.lm.speech_token_range) and end-of-
464+
// audio is signalled by cb0 == eos_code_c0. The host's auto-grammar
465+
// (tts_auto_grammar) uses these to constrain decode-phase cb0 sampling
466+
// to speech tokens ∪ {eos_code_c0}, keeping the model from drifting into
467+
// arbitrary text tokens (babble) mid-utterance. Both -1 when absent.
468+
int32_t cb0_speech_range_start = -1; // codec.lm.cb0_speech_offset
469+
int32_t cb0_speech_range_end = -1; // codec.lm.cb0_speech_range_end (exclusive)
459470
};
460471

461472
// Fill `*out` from the loaded model's metadata. Returns false + sets
462473
// last_error when the model has no codec_lm (no AR profile to describe).
463474
bool audio_lm_get_prompt_info(const audio_lm_context * ctx,
464475
audio_lm_prompt_info * out);
465476

477+
// ─────────────────────────────────────────────────────────────────────
478+
// Auto-grammar (prompt/metadata-derived GBNF for the backbone sampler)
479+
//
480+
// Returns a GBNF grammar string derived from the model's metadata (the
481+
// `pi` filled by audio_lm_get_prompt_info) + the synthesis text, or "" for
482+
// models that don't benefit from one. The grammar constrains the
483+
// BACKBONE-logits sampler only (cb0-from-backbone / text-warmup tokens);
484+
// it is meaningless for codec_lm audio-codebook heads (arbitrary float
485+
// arrays, no vocab).
486+
//
487+
// Precedent: llama.rn's rn-tts build_dynamic_grammar (OuteTTS/Soprano/
488+
// NeuTTS families). The concept is ported; the first real application
489+
// here is MOSS-TTSD cb0 (merged text+speech vocab): the grammar allows
490+
// only the speech-token range [cb0_speech_range_start, cb0_speech_range_end)
491+
// plus the end-of-audio sentinel eos_code_c0, so the backbone can't drift
492+
// into arbitrary text tokens mid-utterance. A non-speech cb0 token is the
493+
// reference's natural stop trigger, so eos_code_c0 stays permitted.
494+
//
495+
// `text` is unused today (MOSS-TTSD's grammar is text-independent) but is
496+
// threaded through for future prompt-dependent grammars (OuteTTS-style
497+
// word-sequence constraints).
498+
std::string tts_auto_grammar(const audio_lm_prompt_info & pi,
499+
const std::string & text);
500+
466501
// ─── Codebook step machine passthroughs (Type C/D) ──────────────────
467502
//
468503
// Drive the internal codec_lm_state per AR step. Sequence per frame:

0 commit comments

Comments
 (0)