Repository navigation
Description
Hi, and thanks for audio.cpp. We run Pocket TTS in French and found two defects in the Pocket TTS path, plus a small UTF-8 one. All three are fixed below, on top of v0.8.2 (f774098), and validated against the Python reference (pocket-tts 2.1.0 and 3.2.0). Happy to turn this into a PR if you prefer: say which shape you want.
1. *_24l models fail to load: the flow net is built with the transformer depth
Packaging any languages/*_24l checkpoint of kyutai/pocket-tts (French, German, Italian, Portuguese, Spanish) and loading it fails with:
missing tensor: flow_lm.flow_net.res_blocks.6
The flow network (SimpleMLPAdaLN) is instantiated with the transformer's layer count, while the reference config sets the two separately:
flow_lm:
flow:
depth: 6 # flow net residual blocks
transformer:
num_layers: 24The 6-layer models hide the bug because both values are 6. The fix reads flow_lm.flow.depth into PocketTTSModelConfig::flow_depth (default 6) and uses it where the flow net is loaded and built.
Validation. french_24l with voice estelle, float32 on CPU. We compared it to the reference float32 run, with both engines fed the same noise schedule (your noise_file option; on the Python side torch.nn.init.normal_ was patched to serve the same vectors):
| check | result |
|---|---|
| text tokens | identical (25/25) |
| EOS logit, all 42 steps | largest difference 4.2e-5 |
| generated latents, all 42 steps | largest relative error 8.0e-6 |
| waveform, offline session | relative error 1.25e-4 (the int16 rounding floor) |
One trap for anyone repeating this: the reference draws one noise vector during the text prompt and discards the latent. Offset the schedule by one on the Python side.
2. Streaming cuts every sentence longer than 50 characters
PocketTTSSession::start_stream passes max_tokens (default 50) to engine::text::split_text_chunks, which counts codepoints. The reference's max_tokens=50 counts sentencepiece tokens and splits on sentence boundaries first (split_into_best_sentences). As a result, almost every sentence is cut in two, and each half is synthesized as a separate utterance with a fresh prompt. That breaks the prosody, and the short halves are exactly where the model is weakest. The offline path uses a 256-codepoint budget instead, so the two modes also disagree.
The fix ports split_into_best_sentences from pocket-tts 3.2.0 into TextConditioner:
- sentence boundaries are found on the model's own end-of-sentence tokens;
- a period between two digits ("8.1") does not end a sentence;
- a sentence over budget is split again on
,;:; - segments are then regrouped into chunks of at most
max_tokenstokens.
Streaming, run() and prepare_generation all go through it. An explicit text_chunk_size keeps its codepoint meaning, so no existing option changes behavior.
Chunking parity. We checked 16 texts built to hit every branch: . ! ? ..., decimals, a sentence over 50 tokens with the ; → , fallback, short words, accented first and last letters, and several short sentences grouped into one chunk. The patched server's chunks, as prepared for the model (read from the trace log), are identical to the reference's in 16/16 cases. The reference here is the 3.2.0 splitter fed the same tokenizer.model, with the 2.1.0 prompt preparation that prepare_pocket_tts_text mirrors.
Intelligibility. french_24l, estelle, float32 on CPU, 8 sentences of 60 to 76 characters, 4 draws each (32 samples per arm). Each sample was transcribed by an ASR (Cohere Transcribe) and scored by word error rate against its input, with numbers spelled out on both sides:
| engine | mean WER | exact sentences | pieces per sentence |
|---|---|---|---|
| reference, Python, CPU | 8.9 % | 17/32 | 1 |
| audio.cpp, default, before the fix | 17.6 % | 11/32 | 2 |
| audio.cpp, default, with the fix | 9.6 % | 20/32 | 1 |
One of the 32 patched samples was unintelligible (the ASR returned an unrelated caption); it accounts for about 3 points of the 9.6 %. The reference had none in this run. The "before" row was measured at 639de86, whose Pocket TTS code is identical to v0.8.2's. The piece counts come from the trace key pocket_tts.streaming.text_chunk_count.
3. Text preparation tests bytes, not characters
prepare_pocket_tts_text uses std::isalnum, std::islower and std::toupper on single bytes of a UTF-8 string. Two effects:
- A sentence ending in an accented letter ("C'est réglé") gets no final period. The reference appends one, since
"é".isalnum()is true in Python. - An accented first letter ("état", "à demain") is not capitalized.
The fix decodes the first and last code points. Letters are ASCII plus Latin-1 Supplement and Latin Extended-A/B; the uppercase mapping covers Latin-1 and Latin Extended-A. That is every letter used by the current Pocket TTS languages. Other scripts keep the byte rule.
Heads-up: pocket-tts 3.2.0 changes the French tokenizer
The new French models published today (languages/french, a 6-layer model, and a new french_24l) ship tokenizer: tokenizers with a tokenizer.json, instead of a sentencepiece tokenizer.model. Their ids are not those of the previous sentencepiece model: for example, " merci" is ▁merci in the old model and ▁ + merci in the new one. Supporting these models will need a HuggingFace-tokenizers path in the Pocket TTS loader. We have not done that part.
Side note
Without stream_format, POST /v1/audio/speech with response_format: "pcm" answers Content-Type: audio/wav, with a 44-byte RIFF header in front of the samples. OpenAI's pcm is raw 24 kHz s16le, so a client that trusts the format name gets a 22-sample click.
Patch 1: flow depth (101 lines)
diff --git a/include/engine/models/pocket_tts/assets.h b/include/engine/models/pocket_tts/assets.h
index 8db8b72..5971005 100644
--- a/include/engine/models/pocket_tts/assets.h
+++ b/include/engine/models/pocket_tts/assets.h
@@ -19,6 +19,7 @@ struct PocketTTSModelConfig {
float frame_rate = 12.5F;
float mimi_frame_rate = 12.5F;
int64_t flow_layers = 6;
+ int64_t flow_depth = 6;
int64_t flow_dim = 1024;
int64_t flow_heads = 16;
int64_t flow_hidden_size = 512;
diff --git a/include/engine/models/pocket_tts/flow_lm.h b/include/engine/models/pocket_tts/flow_lm.h
index 3fc0159..02b9cb2 100644
--- a/include/engine/models/pocket_tts/flow_lm.h
+++ b/include/engine/models/pocket_tts/flow_lm.h
@@ -24,6 +24,7 @@ struct FlowLMConfig {
int64_t layers = 6;
float norm_eps = 1.0e-5F;
float flow_eps = 1.0e-6F;
+ int64_t flow_depth = 6; // flow-net residual blocks, see PocketTTSModelConfig::flow_depth
};
using FlowLMCacheState = runtime::KVLayerState;
diff --git a/src/models/pocket_tts/assets.cpp b/src/models/pocket_tts/assets.cpp
index 6851346..c15b536 100644
--- a/src/models/pocket_tts/assets.cpp
+++ b/src/models/pocket_tts/assets.cpp
@@ -21,6 +21,9 @@ struct PocketTTSDescriptor {
int sample_rate = 24000;
float frame_rate = 12.5F;
int flow_layers = 6;
+ // Residual blocks of the flow net (upstream `flow_lm.flow.depth`). Distinct from the
+ // transformer depth: the *_24l models have 24 transformer layers but a 6-block flow net.
+ int flow_depth = 6;
int flow_dim = 1024;
int flow_heads = 16;
int flow_hidden_size = 512;
@@ -50,6 +53,7 @@ PocketTTSDescriptor descriptor_from_yaml(const io::yaml::FlattenedDocument & par
descriptor.sample_rate = io::yaml::require_int(parsed, "mimi.sample_rate");
descriptor.frame_rate = io::yaml::require_float(parsed, "mimi.frame_rate");
descriptor.flow_layers = io::yaml::require_int(parsed, "flow_lm.transformer.num_layers");
+ descriptor.flow_depth = io::yaml::optional_int(parsed, "flow_lm.flow.depth").value_or(descriptor.flow_depth);
descriptor.flow_dim = io::yaml::require_int(parsed, "flow_lm.transformer.d_model");
descriptor.flow_heads = io::yaml::require_int(parsed, "flow_lm.transformer.num_heads");
descriptor.flow_hidden_size = io::yaml::require_int(parsed, "flow_lm.flow.dim");
@@ -109,6 +113,7 @@ PocketTTSModelConfig make_model_config(const PocketTTSDescriptor & descriptor) {
config.frame_rate = descriptor.frame_rate;
config.mimi_frame_rate = descriptor.frame_rate;
config.flow_layers = descriptor.flow_layers;
+ config.flow_depth = descriptor.flow_depth;
config.flow_dim = descriptor.flow_dim;
config.flow_heads = descriptor.flow_heads;
config.flow_hidden_size = descriptor.flow_hidden_size;
diff --git a/src/models/pocket_tts/backend_weights.cpp b/src/models/pocket_tts/backend_weights.cpp
index 852730c..94b7319 100644
--- a/src/models/pocket_tts/backend_weights.cpp
+++ b/src/models/pocket_tts/backend_weights.cpp
@@ -156,7 +156,7 @@ PocketTTSBackendFlowWeights load_backend_flow_weights(
const std::string prefix = "flow_lm.transformer.layers." + std::to_string(layer) + ".";
weights.transformer_layers.push_back(load_backend_transformer_layer(store, source, prefix, storage_type));
}
- weights.flow_net = load_backend_flow_net_weights(store, source, config.flow_layers, storage_type);
+ weights.flow_net = load_backend_flow_net_weights(store, source, config.flow_depth, storage_type);
weights.out_norm = binding::norm_from_named_source(store, source, "flow_lm.out_norm.weight", "flow_lm.out_norm.bias");
weights.out_eos = binding::linear_from_named_source(store, source, "flow_lm.out_eos.weight", "flow_lm.out_eos.bias", storage_type);
weights.speaker_proj_weight =
diff --git a/src/models/pocket_tts/flow_lm.cpp b/src/models/pocket_tts/flow_lm.cpp
index bddb6fe..98a4c10 100644
--- a/src/models/pocket_tts/flow_lm.cpp
+++ b/src/models/pocket_tts/flow_lm.cpp
@@ -31,7 +31,7 @@ modules::TransformerEncoderBlockWeights make_transformer_layer_weights(
modules::TimedConditionedFlowMLPWeights make_flow_net_weights(
const models::pocket_tts::PocketTTSBackendWeights & weights,
const FlowLMConfig & config) {
- if (static_cast<int64_t>(weights.flow.flow_net.residual_layers.size()) != config.layers) {
+ if (static_cast<int64_t>(weights.flow.flow_net.residual_layers.size()) != config.flow_depth) {
throw std::runtime_error("PocketTTS FlowNet residual layer count does not match config");
}
return weights.flow.flow_net;
@@ -372,7 +372,7 @@ public:
config_.flow_hidden_size,
config_.hidden_size,
config_.latent_size,
- config_.layers,
+ config_.flow_depth,
config_.flow_eps,
true,
}).build(ctx, condition_, start_time_, end_time_, noise_, weights.flow_net);
diff --git a/src/models/pocket_tts/session.cpp b/src/models/pocket_tts/session.cpp
index 5f4fe48..36959f6 100644
--- a/src/models/pocket_tts/session.cpp
+++ b/src/models/pocket_tts/session.cpp
@@ -74,6 +74,7 @@ FlowLMConfig make_flow_config(const PocketTTSAssets & manifest) {
manifest.model_config.flow_layers,
1.0e-5F,
1.0e-6F,
+ manifest.model_config.flow_depth,
};
}
Patch 2: sentence chunking and UTF-8 preparation (applies after patch 1)
diff --git a/include/engine/models/pocket_tts/text_conditioner.h b/include/engine/models/pocket_tts/text_conditioner.h
index a7d2482..ee9acbc 100644
--- a/include/engine/models/pocket_tts/text_conditioner.h
+++ b/include/engine/models/pocket_tts/text_conditioner.h
@@ -28,6 +28,15 @@ public:
const PocketTTSHostWeights & weights,
const std::string & text) const;
+ // Splits a prompt the way the reference implementation does (pocket_tts
+ // split_into_best_sentences): sentence boundaries found on the model's own
+ // end-of-sentence tokens, sentences longer than max_tokens split again on
+ // ",;:", then regrouped into chunks of at most max_tokens tokens.
+ std::vector<std::string> split_into_sentence_chunks(
+ const PocketTTSAssets & manifest,
+ const std::string & text,
+ int64_t max_tokens) const;
+
private:
TextConditionerConfig config_;
};
diff --git a/src/models/pocket_tts/session.cpp b/src/models/pocket_tts/session.cpp
index 36959f6..dfb4311 100644
--- a/src/models/pocket_tts/session.cpp
+++ b/src/models/pocket_tts/session.cpp
@@ -27,7 +27,6 @@ namespace {
constexpr int64_t kCpuPromptCapacityFloor = 32;
constexpr int64_t kCpuGenerationCapacityFloor = 160;
constexpr int64_t kGenerationCapacityQuantum = 16;
-constexpr int64_t kDefaultTextChunkSize = 256;
constexpr int64_t kDefaultVoiceStateCacheSlots = 4;
int64_t next_power_of_two(int64_t value) {
@@ -145,8 +144,7 @@ void apply_session_generation_options(
{"max_tokens", "pocket_tts.max_tokens"})) {
generation_request.max_tokens = *max_tokens;
}
- generation_request.text_chunk_size =
- engine::text::parse_text_chunk_size_override(options).value_or(kDefaultTextChunkSize);
+ generation_request.text_chunk_size = engine::text::parse_text_chunk_size_override(options);
if (const auto temperature = runtime::parse_float_option(options, {"temperature", "pocket_tts.temperature"})) {
generation_request.temperature = *temperature;
}
@@ -176,8 +174,7 @@ void apply_request_generation_options(
{"max_tokens", "pocket_tts.max_tokens"})) {
generation_request.max_tokens = *max_tokens;
}
- generation_request.text_chunk_size =
- engine::text::parse_text_chunk_size_override(options).value_or(kDefaultTextChunkSize);
+ generation_request.text_chunk_size = engine::text::parse_text_chunk_size_override(options);
}
GenerationRequest build_generation_request(const runtime::TaskRequest & request, float default_temperature) {
@@ -251,6 +248,29 @@ void validate_generation_request(const GenerationRequest & request) {
}
}
+// An explicit text_chunk_size keeps the character budget it always meant. Otherwise the text
+// is cut like the reference cuts it: on sentence boundaries, at most max_tokens tokens per
+// chunk. The streaming path used to pass max_tokens (50) as a CHARACTER budget, which cut
+// nearly every sentence in two, and the offline path used 256 characters.
+std::vector<std::string> split_generation_text(
+ const TextConditioner & text_conditioner,
+ const PocketTTSAssets & manifest,
+ const GenerationRequest & request) {
+ if (request.text_chunk_size.has_value()) {
+ return engine::text::split_text_chunks(request.text, *request.text_chunk_size);
+ }
+ return text_conditioner.split_into_sentence_chunks(manifest, request.text, request.max_tokens);
+}
+
+void trace_text_chunking(const char * prefix, const GenerationRequest & request, size_t chunk_count) {
+ const std::string key = std::string(prefix) +
+ (request.text_chunk_size.has_value() ? "text_chunk_size" : "max_tokens");
+ engine::debug::trace_log_scalar(
+ key,
+ request.text_chunk_size.has_value() ? *request.text_chunk_size : static_cast<int64_t>(request.max_tokens));
+ engine::debug::trace_log_scalar(std::string(prefix) + "text_chunk_count", static_cast<int64_t>(chunk_count));
+}
+
int estimate_max_steps(const PocketTTSAssets & manifest, int64_t token_count) {
constexpr double kTokensPerSecondEstimate = 3.0;
constexpr double kGenerationSecondsPadding = 2.0;
@@ -788,9 +808,7 @@ void PocketTTSSession::start_stream(const runtime::TaskRequest & request) {
reset();
stream_request_ = effective_request_for_run(request);
validate_generation_request(stream_request_);
- const int64_t streaming_chunk_size =
- engine::text::parse_text_chunk_size_override(request.options).value_or(stream_request_.max_tokens);
- stream_text_chunks_ = engine::text::split_text_chunks(stream_request_.text, streaming_chunk_size);
+ stream_text_chunks_ = split_generation_text(text_conditioner_, *manifest_, stream_request_);
if (stream_text_chunks_.empty()) {
throw std::runtime_error("PocketTTS streaming text chunking produced no segments");
}
@@ -800,8 +818,7 @@ void PocketTTSSession::start_stream(const runtime::TaskRequest & request) {
audio_decoder_.reset_streaming_state();
stream_started_at_ = std::chrono::steady_clock::now();
stream_started_ = true;
- engine::debug::trace_log_scalar("pocket_tts.streaming.text_chunk_size", streaming_chunk_size);
- engine::debug::trace_log_scalar("pocket_tts.streaming.text_chunk_count", static_cast<int64_t>(stream_text_chunks_.size()));
+ trace_text_chunking("pocket_tts.streaming.", stream_request_, stream_text_chunks_.size());
}
std::optional<runtime::StreamEvent> PocketTTSSession::next_stream_event() {
@@ -947,8 +964,7 @@ void PocketTTSSession::prepare_generation(const GenerationRequest & request) {
return;
}
const auto & manifest = *manifest_;
- const int64_t text_chunk_size = request.text_chunk_size.value_or(kDefaultTextChunkSize);
- const auto chunks = engine::text::split_text_chunks(request.text, text_chunk_size);
+ const auto chunks = split_generation_text(text_conditioner_, manifest, request);
for (const auto & chunk : chunks) {
const TextConditioningResult text_state = text_conditioner_.prepare(manifest, weights_->host, chunk);
const AcousticGenerationConfig acoustic_config = resolve_acoustic_generation_config(
@@ -983,10 +999,8 @@ GenerationResult PocketTTSSession::generate(const GenerationRequest & request) {
const auto & manifest = *manifest_;
const auto started_inference = std::chrono::steady_clock::now();
- const int64_t text_chunk_size = request.text_chunk_size.value_or(kDefaultTextChunkSize);
- const auto chunks = engine::text::split_text_chunks(request.text, text_chunk_size);
- engine::debug::trace_log_scalar("pocket_tts.text_chunk_size", text_chunk_size);
- engine::debug::trace_log_scalar("pocket_tts.text_chunk_count", static_cast<int64_t>(chunks.size()));
+ const auto chunks = split_generation_text(text_conditioner_, manifest, request);
+ trace_text_chunking("pocket_tts.", request, chunks.size());
const auto voice_plan = resolve_voice_conditioning_plan(model_dir_, request);
VoiceConditioningResult voice_state;
diff --git a/src/models/pocket_tts/text_conditioner.cpp b/src/models/pocket_tts/text_conditioner.cpp
index 1032738..106c7f8 100644
--- a/src/models/pocket_tts/text_conditioner.cpp
+++ b/src/models/pocket_tts/text_conditioner.cpp
@@ -7,10 +7,119 @@
#include <algorithm>
#include <cctype>
#include <stdexcept>
+#include <unordered_set>
namespace engine::models::pocket_tts {
namespace {
+struct CodePoint {
+ uint32_t value = 0;
+ size_t length = 0;
+};
+
+// Decodes the UTF-8 sequence starting at `start`. A malformed sequence is returned as a
+// single opaque byte, so callers never read past it and never treat it as a letter.
+CodePoint decode_utf8_at(const std::string & text, size_t start) {
+ const auto lead = static_cast<unsigned char>(text[start]);
+ if (lead < 0x80) {
+ return {lead, 1};
+ }
+ size_t length = 0;
+ uint32_t value = 0;
+ if ((lead & 0xE0) == 0xC0) {
+ length = 2;
+ value = lead & 0x1F;
+ } else if ((lead & 0xF0) == 0xE0) {
+ length = 3;
+ value = lead & 0x0F;
+ } else if ((lead & 0xF8) == 0xF0) {
+ length = 4;
+ value = lead & 0x07;
+ } else {
+ return {0xFFFFFFFFU, 1};
+ }
+ if (start + length > text.size()) {
+ return {0xFFFFFFFFU, 1};
+ }
+ for (size_t i = 1; i < length; ++i) {
+ const auto next = static_cast<unsigned char>(text[start + i]);
+ if ((next & 0xC0) != 0x80) {
+ return {0xFFFFFFFFU, 1};
+ }
+ value = (value << 6) | (next & 0x3F);
+ }
+ return {value, length};
+}
+
+std::string encode_utf8(uint32_t value) {
+ std::string out;
+ if (value < 0x80) {
+ out.push_back(static_cast<char>(value));
+ } else if (value < 0x800) {
+ out.push_back(static_cast<char>(0xC0 | (value >> 6)));
+ out.push_back(static_cast<char>(0x80 | (value & 0x3F)));
+ } else if (value < 0x10000) {
+ out.push_back(static_cast<char>(0xE0 | (value >> 12)));
+ out.push_back(static_cast<char>(0x80 | ((value >> 6) & 0x3F)));
+ out.push_back(static_cast<char>(0x80 | (value & 0x3F)));
+ } else {
+ out.push_back(static_cast<char>(0xF0 | (value >> 18)));
+ out.push_back(static_cast<char>(0x80 | ((value >> 12) & 0x3F)));
+ out.push_back(static_cast<char>(0x80 | ((value >> 6) & 0x3F)));
+ out.push_back(static_cast<char>(0x80 | (value & 0x3F)));
+ }
+ return out;
+}
+
+// The reference works on Python str, where "é".isalnum() is true. Testing the last BYTE of
+// a UTF-8 string instead left every sentence ending in an accented letter without its
+// final period ("C'est réglé"). Covers ASCII plus the Latin-1 Supplement and Latin
+// Extended-A/B letters used by every Pocket TTS language; other scripts keep the byte rule.
+bool is_letter_or_digit(uint32_t value) {
+ if (value < 0x80) {
+ return std::isalnum(static_cast<int>(value)) != 0;
+ }
+ return value >= 0x00C0 && value <= 0x024F && value != 0x00D7 && value != 0x00F7;
+}
+
+// Uppercase of a lowercase Latin letter, or 0 when it has no single-code-point uppercase:
+// the reference capitalizes the first letter with str.upper(), which turns "état" into
+// "État" where a byte-wise toupper() left it lowercase.
+uint32_t latin_uppercase(uint32_t value) {
+ if (value >= 'a' && value <= 'z') {
+ return value - 0x20;
+ }
+ if (value >= 0x00E0 && value <= 0x00FE && value != 0x00F7) {
+ return value - 0x20;
+ }
+ if (value == 0x00FF) {
+ return 0x0178;
+ }
+ if (value == 0x0131) {
+ return 'I';
+ }
+ const bool even_upper = (value >= 0x0100 && value <= 0x012F) || (value >= 0x0132 && value <= 0x0137) ||
+ (value >= 0x014A && value <= 0x0177);
+ if (even_upper && (value & 1U) == 1U) {
+ return value - 1;
+ }
+ const bool odd_upper = (value >= 0x0139 && value <= 0x0148) || (value >= 0x0179 && value <= 0x017E);
+ if (odd_upper && (value & 1U) == 0U) {
+ return value - 1;
+ }
+ return 0;
+}
+
+std::string strip_ascii_whitespace(std::string text) {
+ while (!text.empty() && std::isspace(static_cast<unsigned char>(text.front()))) {
+ text.erase(text.begin());
+ }
+ while (!text.empty() && std::isspace(static_cast<unsigned char>(text.back()))) {
+ text.pop_back();
+ }
+ return text;
+}
+
std::string prepare_pocket_tts_text(
std::string text,
bool pad_with_spaces_for_short_inputs,
@@ -40,10 +149,16 @@ std::string prepare_pocket_tts_text(
if (remove_semicolons) {
std::replace(text.begin(), text.end(), ';', ',');
}
- if (!text.empty() && std::islower(static_cast<unsigned char>(text.front()))) {
- text.front() = static_cast<char>(std::toupper(static_cast<unsigned char>(text.front())));
+ const CodePoint first = decode_utf8_at(text, 0);
+ if (const uint32_t upper = latin_uppercase(first.value); upper != 0) {
+ text.replace(0, first.length, encode_utf8(upper));
+ }
+ size_t last_start = text.size() - 1;
+ while (last_start > 0 && (static_cast<unsigned char>(text[last_start]) & 0xC0) == 0x80) {
+ --last_start;
}
- if (std::isalnum(static_cast<unsigned char>(text.back()))) {
+ const CodePoint last = decode_utf8_at(text, last_start);
+ if (last_start + last.length == text.size() && is_letter_or_digit(last.value)) {
text.push_back('.');
}
if (pad_with_spaces_for_short_inputs) {
@@ -95,6 +210,87 @@ std::vector<float> gather_token_embeddings(
return output;
}
+// Token ids of `symbols` minus the first one, exactly as the reference builds its boundary
+// sets: SentencePiece prefixes the string with its word marker, and only the ids that
+// follow it stand for the punctuation.
+std::unordered_set<int32_t> boundary_token_ids(
+ const std::vector<tokenizers::SentencePiecePiece> & pieces,
+ const std::string & symbols) {
+ const std::vector<int32_t> ids = tokenizers::tokenize_sentencepiece(pieces, symbols);
+ std::unordered_set<int32_t> out;
+ for (size_t i = 1; i < ids.size(); ++i) {
+ out.insert(ids[i]);
+ }
+ return out;
+}
+
+std::string decode_range(
+ const std::vector<tokenizers::SentencePiecePiece> & pieces,
+ const std::vector<int32_t> & tokens,
+ size_t begin,
+ size_t end) {
+ return tokenizers::decode_sentencepiece(
+ pieces,
+ std::vector<int32_t>(
+ tokens.begin() + static_cast<ptrdiff_t>(begin),
+ tokens.begin() + static_cast<ptrdiff_t>(end)));
+}
+
+// "3.5": a period between two digits does not end a sentence.
+bool is_decimal_period_boundary(
+ const std::vector<tokenizers::SentencePiecePiece> & pieces,
+ const std::vector<int32_t> & tokens,
+ size_t segment_start) {
+ const std::string prefix = decode_range(pieces, tokens, 0, segment_start);
+ const std::string suffix = decode_range(pieces, tokens, segment_start, tokens.size());
+ return prefix.size() >= 2 && prefix.back() == '.' &&
+ std::isdigit(static_cast<unsigned char>(prefix[prefix.size() - 2])) != 0 && !suffix.empty() &&
+ std::isdigit(static_cast<unsigned char>(suffix.front())) != 0;
+}
+
+// A segment starts at the first token that is not a boundary token after a run of boundary
+// tokens. Returns [0, starts..., size], so consecutive pairs are the segments.
+std::vector<size_t> find_boundary_indices(
+ const std::vector<int32_t> & tokens,
+ const std::unordered_set<int32_t> & boundary_ids,
+ const std::vector<tokenizers::SentencePiecePiece> * pieces_for_decimal_check) {
+ std::vector<size_t> indices{0};
+ bool previous_was_boundary = false;
+ for (size_t index = 0; index < tokens.size(); ++index) {
+ if (boundary_ids.count(tokens[index]) != 0) {
+ previous_was_boundary = true;
+ continue;
+ }
+ if (previous_was_boundary &&
+ !(pieces_for_decimal_check != nullptr &&
+ is_decimal_period_boundary(*pieces_for_decimal_check, tokens, index))) {
+ indices.push_back(index);
+ }
+ previous_was_boundary = false;
+ }
+ indices.push_back(tokens.size());
+ return indices;
+}
+
+struct TextSegment {
+ int64_t token_count = 0;
+ std::string text;
+};
+
+std::vector<TextSegment> segments_from_boundaries(
+ const std::vector<tokenizers::SentencePiecePiece> & pieces,
+ const std::vector<int32_t> & tokens,
+ const std::vector<size_t> & boundaries) {
+ std::vector<TextSegment> segments;
+ for (size_t i = 0; i + 1 < boundaries.size(); ++i) {
+ segments.push_back(TextSegment{
+ static_cast<int64_t>(boundaries[i + 1] - boundaries[i]),
+ decode_range(pieces, tokens, boundaries[i], boundaries[i + 1]),
+ });
+ }
+ return segments;
+}
+
} // namespace
TextConditioner::TextConditioner(TextConditionerConfig config) : config_(config) {}
@@ -120,4 +316,73 @@ TextConditioningResult TextConditioner::prepare(
return result;
}
+std::vector<std::string> TextConditioner::split_into_sentence_chunks(
+ const models::pocket_tts::PocketTTSAssets & manifest,
+ const std::string & text,
+ int64_t max_tokens) const {
+ if (manifest.tokenizer_pieces.empty()) {
+ throw std::runtime_error("PocketTTS tokenizer pieces are not loaded");
+ }
+ if (max_tokens <= 0) {
+ throw std::runtime_error("PocketTTS max_tokens must be positive");
+ }
+ const auto & pieces = manifest.tokenizer_pieces;
+ // Same normalization as the prompt the model will see, then stripped: the reference drops
+ // the short-input padding here and adds it back chunk by chunk in prepare().
+ const std::string prepared = strip_ascii_whitespace(prepare_pocket_tts_text(
+ text,
+ manifest.model_config.pad_with_spaces_for_short_inputs,
+ manifest.model_config.remove_semicolons));
+ const std::vector<int32_t> tokens = tokenizers::tokenize_sentencepiece(pieces, prepared);
+ const std::vector<TextSegment> sentences = segments_from_boundaries(
+ pieces,
+ tokens,
+ find_boundary_indices(tokens, boundary_token_ids(pieces, ".!...?"), &pieces));
+
+ // A sentence longer than the budget is split again on commas, semicolons and colons,
+ // which keeps the model from skipping words at the end of an overlong chunk.
+ const std::unordered_set<int32_t> fallback_ids = boundary_token_ids(pieces, ",;:");
+ std::vector<TextSegment> refined;
+ for (const TextSegment & sentence : sentences) {
+ if (sentence.token_count <= max_tokens) {
+ refined.push_back(sentence);
+ continue;
+ }
+ const std::vector<int32_t> sub_tokens =
+ tokenizers::tokenize_sentencepiece(pieces, strip_ascii_whitespace(sentence.text));
+ std::vector<TextSegment> parts = segments_from_boundaries(
+ pieces,
+ sub_tokens,
+ find_boundary_indices(sub_tokens, fallback_ids, nullptr));
+ if (parts.size() > 1) {
+ refined.insert(refined.end(), parts.begin(), parts.end());
+ } else {
+ refined.push_back(sentence);
+ }
+ }
+
+ std::vector<std::string> chunks;
+ std::string current;
+ int64_t current_tokens = 0;
+ for (const TextSegment & segment : refined) {
+ if (current.empty()) {
+ current = segment.text;
+ current_tokens = segment.token_count;
+ continue;
+ }
+ if (current_tokens + segment.token_count > max_tokens) {
+ chunks.push_back(strip_ascii_whitespace(current));
+ current = segment.text;
+ current_tokens = segment.token_count;
+ } else {
+ current += " " + segment.text;
+ current_tokens += segment.token_count;
+ }
+ }
+ if (!current.empty()) {
+ chunks.push_back(strip_ascii_whitespace(current));
+ }
+ return chunks;
+}
+
} // namespace engine::models::pocket_tts
Activity
0xShug0 commentedon Sep 23, 2026
@bvisible Thanks for reporting the issues! Appreciate it if you could open PRs for your fixes, and we can iterate on them from there.
bvisible commentedon Sep 23, 2026
Thanks! Opened #670 (flow depth) and #671 (text chunking + UTF-8). They apply on main independently.
0xShug0 commentedon Sep 24, 2026
@bvisible Both merged! Thanks!
handpickencounter commentedon Nov 15, 2026
response_format: "pcm" still responds with WAV header (offline mode)
streaming mode doesn't even appear to be usable as audio comes back both slower and slightly garbled. with pocket tts it should be the same as offline (stream the PCM samples as they come from the mimi decoder).
0xShug0 commentedon Nov 15, 2026
@handpickencounter The streaming path has been fixed in #1289
handpickencounter commentedon Nov 15, 2026
looks like it just missed the release yesterday by a single commit, unfortunate.