From 4a55ffa80b1c066389d1293452ecf621ad444a83 Mon Sep 17 00:00:00 2001 From: Hans Date: Sat, 14 Nov 2026 19:24:47 +0800 Subject: [PATCH 01/11] feat(moss-tts-nano): backbone converter writes the global transformer as starcoder2 MOSS-TTS-Nano's global transformer is a GPT-2 with RoPE: pre-LN LayerNorm with bias, biased q/k/v/o and gelu_new FFN, final LayerNorm, no position table. That is llama.cpp's stock starcoder2, so no arch patch: c_attn splits into q/k/v, and q/k rows and biases are reordered per head from the interleaved rotation to NEOX. The SentencePiece BPE tokenizer goes in as the SPM vocab; its nmt_nfkc normalizer is applied by the family. Hidden state vs PyTorch on a 331-row voice-clone prompt: rel 4e-4 (F32 weights), 4e-3 (BF16, the checkpoint's precision). Sampling: the reference's audio settings (temp 1.7, top_k 25, top_p 0.8, temperature first). Co-Authored-By: Claude Opus 5.5 --- scripts/convert-backbone-to-gguf.py | 137 ++++++++++++++++++++++++++++ scripts/utils/sampling.py | 5 + 2 files changed, 142 insertions(+) diff --git a/scripts/convert-backbone-to-gguf.py b/scripts/convert-backbone-to-gguf.py index 1db7351..06de310 100644 --- a/scripts/convert-backbone-to-gguf.py +++ b/scripts/convert-backbone-to-gguf.py @@ -5,6 +5,7 @@ sesame/csm-1b (CSM, Llama-3.2-1B) Qwen/Qwen3-TTS-12Hz-* (Qwen3 talker) fnlp/MOSS-TTSD-v0.5 (Qwen3 language_model) + OpenMOSS-Team/MOSS-TTS-Nano-100M (GPT-2 + RoPE → starcoder2, written directly) LiquidAI/LFM2-Audio-1.5B (Lfm2 hybrid conv+attn) kmhf/hf-moshiko, kmhf/hf-moshika (Helium = Llama-style) @@ -889,6 +890,135 @@ def add(name: str, arr, keep_f32: bool = False): w.close() +def _write_spm_bpe_vocab(w, tok_path: Path, n_vocab: int) -> None: + """A SentencePiece BPE model as llama.cpp's SPM ("llama") vocab: merges by + piece score, byte fallback through the <0xXX> pieces, a space prefix per + tokenize call (add_dummy_prefix). llama.cpp's SPM path has no normalizer, + so a model with a non-identity normalizer needs its text normalized before + tokenizing (MOSS-TTS-Nano: the codec_audio_lm family applies nmt_nfkc).""" + import gguf + from sentencepiece import sentencepiece_model_pb2 as spm_pb2 + if not tok_path.is_file(): + raise SystemExit(f"missing {tok_path}") + m = spm_pb2.ModelProto() + m.ParseFromString(tok_path.read_bytes()) + if m.trainer_spec.model_type != spm_pb2.TrainerSpec.BPE: + raise SystemExit(f"{tok_path}: expected a SentencePiece BPE model") + if len(m.pieces) != n_vocab: + raise SystemExit(f"tokenizer has {len(m.pieces)} pieces, the embedding {n_vocab} rows") + ttype = {1: gguf.TokenType.NORMAL, 2: gguf.TokenType.UNKNOWN, 3: gguf.TokenType.CONTROL, + 4: gguf.TokenType.USER_DEFINED, 5: gguf.TokenType.UNUSED, 6: gguf.TokenType.BYTE} + w.add_tokenizer_model("llama") + w.add_tokenizer_pre("default") + w.add_token_list([p.piece for p in m.pieces]) + w.add_token_scores([p.score for p in m.pieces]) + w.add_token_types([ttype.get(p.type, gguf.TokenType.NORMAL) for p in m.pieces]) + w.add_add_space_prefix(m.normalizer_spec.add_dummy_prefix) + w.add_remove_extra_whitespaces(m.normalizer_spec.remove_extra_whitespaces) + for setter, idx in ((w.add_unk_token_id, m.trainer_spec.unk_id), (w.add_bos_token_id, m.trainer_spec.bos_id), + (w.add_eos_token_id, m.trainer_spec.eos_id), (w.add_pad_token_id, m.trainer_spec.pad_id)): + if idx >= 0: + setter(idx) + w.add_add_bos_token(False) + w.add_add_eos_token(False) + + +def moss_tts_nano_checkpoint(src: Path) -> bool: + cfg = src / "config.json" + return cfg.is_file() and "MossTTSNanoForCausalLM" in (json.loads(cfg.read_text()).get("architectures") or []) + + +def write_moss_tts_nano_backbone(src: Path, output: Path, outtype: str) -> None: + """MOSS-TTS-Nano global transformer (`transformer.*`, a GPT-2 with RoPE) + → stock GGUF arch `starcoder2`: pre-LN affine LayerNorm, q/k/v/o with + biases, non-gated gelu_new (ggml_gelu, the tanh form) FFN with biases, + final LayerNorm, full-width RoPE (base `rope_base`) and no position table. + The fused `c_attn` (nn.Linear, [3 * n_embd, n_embd]) splits into q/k/v. + MOSS rotates interleaved pairs (2i, 2i+1); starcoder2 is NEOX (i, i + d/2), + so each head's q/k rows AND biases are reordered to [even, odd]: the same + permutation on q and k leaves q·k unchanged. `wte` is `token_embd` + (text positions go in as `b.token`, audio rows as `b.embd`); the output + head is tied to it, as in the checkpoint. The checkpoint is BF16, so + F32 is capped at BF16.""" + import gguf + cfg = json.loads((src / "config.json").read_text()) + g = cfg["gpt2_config"] + if str(g.get("position_embedding_type", "absolute")).lower() != "rope": + raise SystemExit("MOSS-TTS-Nano: only the RoPE global transformer is supported") + if g.get("activation_function") != "gelu_new": + raise SystemExit(f"MOSS-TTS-Nano: activation {g.get('activation_function')!r} is not gelu_new") + if g.get("scale_attn_by_inverse_layer_idx") or not g.get("scale_attn_weights", True): + raise SystemExit("MOSS-TTS-Nano: unsupported attention scaling") + sd_t = torch.load(str(src / "pytorch_model.bin"), map_location="cpu", weights_only=True) + sd = {k[len("transformer."):]: v.float().numpy() for k, v in sd_t.items() if k.startswith("transformer.")} + if "text_lm_head.weight" in sd_t and not torch.equal(sd_t["text_lm_head.weight"], sd_t["transformer.wte.weight"]): + raise SystemExit("MOSS-TTS-Nano: text_lm_head is not tied to transformer.wte") + src_bf16 = sd_t["transformer.wte.weight"].dtype == torch.bfloat16 + del sd_t + + n_embd, n_head, n_layer = int(g["n_embd"]), int(g["n_head"]), int(g["n_layer"]) + n_ff = int(g.get("n_inner") or 4 * n_embd) + n_vocab = sd["wte.weight"].shape[0] + head_dim = n_embd // n_head + qtype = {"f16": gguf.GGMLQuantizationType.F16, "bf16": gguf.GGMLQuantizationType.BF16, + "f32": gguf.GGMLQuantizationType.BF16 if src_bf16 else gguf.GGMLQuantizationType.F32}[outtype.lower()] + + w = gguf.GGUFWriter(str(output), "starcoder2") + w.add_name("MOSS-TTS-Nano global transformer") + w.add_context_length(int(g.get("n_positions", 32768))) + w.add_embedding_length(n_embd) + w.add_block_count(n_layer) + w.add_feed_forward_length(n_ff) + w.add_head_count(n_head) + w.add_head_count_kv(n_head) + w.add_rope_freq_base(float(g.get("rope_base", 10000.0))) + w.add_layer_norm_eps(float(g.get("layer_norm_epsilon", 1e-5))) + w.add_vocab_size(n_vocab) + w.add_file_type({gguf.GGMLQuantizationType.BF16: gguf.LlamaFileType.MOSTLY_BF16, + gguf.GGMLQuantizationType.F16: gguf.LlamaFileType.MOSTLY_F16, + gguf.GGMLQuantizationType.F32: gguf.LlamaFileType.ALL_F32}[qtype]) + _write_spm_bpe_vocab(w, src / "tokenizer.model", n_vocab) + + def add(name: str, arr) -> None: + arr = np.ascontiguousarray(arr, dtype=np.float32) + if arr.ndim >= 2 and qtype != gguf.GGMLQuantizationType.F32: + w.add_tensor(name, gguf.quants.quantize(arr, qtype), raw_dtype=qtype) + else: + w.add_tensor(name, arr) + + def neox(m: np.ndarray) -> np.ndarray: # rows (or bias entries) of q / k, per head [even, odd] + tail = m.shape[1:] + return m.reshape(n_head, head_dim // 2, 2, *tail).swapaxes(1, 2).reshape(n_embd, *tail) + + add("token_embd.weight", sd["wte.weight"]) + add("output_norm.weight", sd["ln_f.weight"]) + add("output_norm.bias", sd["ln_f.bias"]) + for i in range(n_layer): + p, d = f"h.{i}.", f"blk.{i}." + qw, kw, vw = np.split(sd[p + "attn.c_attn.weight"], 3, axis=0) + qb, kb, vb = np.split(sd[p + "attn.c_attn.bias"], 3, axis=0) + add(d + "attn_norm.weight", sd[p + "ln_1.weight"]) + add(d + "attn_norm.bias", sd[p + "ln_1.bias"]) + add(d + "attn_q.weight", neox(qw)) + add(d + "attn_q.bias", neox(qb)) + add(d + "attn_k.weight", neox(kw)) + add(d + "attn_k.bias", neox(kb)) + add(d + "attn_v.weight", vw) + add(d + "attn_v.bias", vb) + add(d + "attn_output.weight", sd[p + "attn.c_proj.weight"]) + add(d + "attn_output.bias", sd[p + "attn.c_proj.bias"]) + add(d + "ffn_norm.weight", sd[p + "ln_2.weight"]) + add(d + "ffn_norm.bias", sd[p + "ln_2.bias"]) + add(d + "ffn_up.weight", sd[p + "mlp.fc_in.weight"]) + add(d + "ffn_up.bias", sd[p + "mlp.fc_in.bias"]) + add(d + "ffn_down.weight", sd[p + "mlp.fc_out.weight"]) + add(d + "ffn_down.bias", sd[p + "mlp.fc_out.bias"]) + w.write_header_to_file() + w.write_kv_data_to_file() + w.write_tensors_to_file() + w.close() + + def pocket_tts_checkpoint(src: Path) -> Path | None: """kyutai/pocket-tts `model.safetensors` (local dir, or the HF repo's languages/english/), or None when `src` is not a Pocket-TTS checkpoint.""" @@ -1128,6 +1258,7 @@ def run_llama_cpp_converter( "MossTTSDForCausalLM": "moss_ttsd", "AsteroidTTSModel": "moss_ttsd", "MossTTSRealtime": "moss_tts_realtime", + "MossTTSNanoForCausalLM": "moss_tts_nano", "Lfm2AudioForConditionalGeneration": "lfm2_audio", "KittenTTS2": "kitten_tts2", "CosyVoice": "cosyvoice", @@ -1192,6 +1323,12 @@ def main() -> int: write_sampling(args.output, sampling_model("CosyVoice1", src, args.model_id)) print(f"[bb] wrote {args.output}", flush=True) return 0 + if moss_tts_nano_checkpoint(src): # MOSS-TTS-Nano: stock starcoder2, written directly + args.output.parent.mkdir(parents=True, exist_ok=True) + write_moss_tts_nano_backbone(src, args.output, args.outtype) + write_sampling(args.output, sampling_model("MossTTSNanoForCausalLM", src, args.model_id)) + print(f"[bb] wrote {args.output}", flush=True) + return 0 pocket = pocket_tts_checkpoint(src) if pocket is not None: # Pocket-TTS: stock starcoder2, written directly args.output.parent.mkdir(parents=True, exist_ok=True) diff --git a/scripts/utils/sampling.py b/scripts/utils/sampling.py index 03aff28..dc3cfe2 100644 --- a/scripts/utils/sampling.py +++ b/scripts/utils/sampling.py @@ -30,6 +30,11 @@ "moss_tts_realtime": dict(temp=0.8, top_k=30, top_p=0.6, min_p=0.0, penalty_repeat=1.1, penalty_last_n=50, samplers=_HF), "lfm2_audio": dict(temp=0.0, top_k=0, top_p=1.0, min_p=0.0), + # modeling_moss_tts_nano.py inference(do_sample=True): the audio codebooks' + # settings (audio_temperature / top_k / top_p, no repetition penalty). Its + # text slot (assistant slot vs audio end) uses temperature 1.5 / top_p 1.0; + # every head here takes the backbone's settings (docs/models/moss_tts_nano.md). + "moss_tts_nano": dict(temp=1.7, top_k=25, top_p=0.8, min_p=0.0, samplers="temperature;top_k;top_p"), # tts.py::generate. mtl_tts.py uses repetition_penalty 2.0, but only with # its AlignmentStreamAnalyzer (attention-driven EOS forcing), which this # runtime does not have; without it 2.0 runs to max length on half the From 4b531f78b0ee760453eca308361684eaa701b818 Mon Sep 17 00:00:00 2001 From: Hans Date: Sat, 14 Nov 2026 19:29:47 +0800 Subject: [PATCH 02/11] feat(moss-tts-nano): LM adaptor + GPT-2 depth block in residual_depth_ar The local transformer (1 GPT-2 layer over 17 positions per frame) is a residual_depth_ar depth decoder that emits codebook 0: the text slot (assistant slot / audio end, from the tied wte head), then the 16 RVQ codes. New metadata, generic to the kind: - codec.lm.depth.arch = "gpt2": LayerNorm with shift, biased q/k/v/o, gelu_new FFN; one block helper for the KV and prefix-recompute paths. - codec.lm.residual.heads_tied_to_embd: head i is input table i. - codec.lm.cb0_allowed: the only codebook-0 ids ever sampled. - codec.lm.audio_cb_offset: leading text codebooks dropped before decode. The converter keeps wte's 16 control rows as the text table (the depth decoder reads and picks only control tokens), bakes the prompt template as token ids (the reference encodes each piece on its own) and the tokenizer's nmt_nfkc charsmap; it now reads pytorch_model.bin LM sources. The GGUF writer gains UINT8 arrays. Teacher-forced frame 0 vs PyTorch (BF16 weights): all 17 argmaxes match, logits max |d| <= 0.05 on |logit| ~10. Co-Authored-By: Claude Opus 5.5 --- scripts/converters/lm_adaptor/__init__.py | 10 +- .../converters/lm_adaptor/moss_tts_local.py | 184 +++++++++++++++--- scripts/utils/gguf_writer.py | 9 +- src/lm/residual_depth_ar.cpp | 139 +++++++++++-- 4 files changed, 297 insertions(+), 45 deletions(-) diff --git a/scripts/converters/lm_adaptor/__init__.py b/scripts/converters/lm_adaptor/__init__.py index 00dd585..2592c6d 100644 --- a/scripts/converters/lm_adaptor/__init__.py +++ b/scripts/converters/lm_adaptor/__init__.py @@ -49,9 +49,6 @@ def dump_lm_into(writer, lm_source, *, verbose: bool = False) -> None: moss_tts_local.dump(writer, sd, cfg, verbose=verbose) return if arch == "MossTTSNanoForCausalLM": - # Stub: GGUF emission is shaped, but the GPT-2 depth-block - # runtime (LayerNorm + GELU + fused c_attn split + abs wpe) is - # still pending — the dump() will raise until that lands. from . import moss_tts_local moss_tts_local.dump(writer, sd, cfg, verbose=verbose) return @@ -114,6 +111,7 @@ def _load_lm_source(lm_source, *, verbose: bool = False) -> Tuple[Dict[str, np.n pass sd = _load_state_dict(local) + cfg["_source_dir"] = str(local if local.is_dir() else local.parent) if verbose: print(f"[lm_adaptor] loaded {len(sd)} tensors from {local}") return sd, cfg @@ -216,6 +214,12 @@ def _shard_to_numpy(shard_path: Path) -> Dict[str, np.ndarray]: return sd if single.is_file(): return _shard_to_numpy(single) + bin_path = path / "pytorch_model.bin" # MOSS-TTS-Nano + if bin_path.is_file(): + out: Dict[str, np.ndarray] = {} + for k, v in torch.load(str(bin_path), map_location="cpu", weights_only=True).items(): + out[k] = (v.to(torch.float32) if v.dtype == torch.bfloat16 else v).detach().cpu().numpy() + return out raise FileNotFoundError( f"could not find safetensors at {path}; expected model.safetensors " diff --git a/scripts/converters/lm_adaptor/moss_tts_local.py b/scripts/converters/lm_adaptor/moss_tts_local.py index 8f55a09..e30308e 100644 --- a/scripts/converters/lm_adaptor/moss_tts_local.py +++ b/scripts/converters/lm_adaptor/moss_tts_local.py @@ -13,28 +13,24 @@ (text embed added externally by the driver) - `MossTTSNanoForCausalLM` (OpenMOSS-Team/MOSS-TTS-Nano-100M, ~100M): - backbone = GPT-2 12L (`transformer`) - depth = 4-layer GPT-2-style local_transformer - per-step = 17 channels (cb-0 = text via text_lm_head, cb-1..16 = audio) - cb-0 input = backbone hidden (no embed at depth pos 0) - cb-0 head = text_lm_head(depth_pos_0_hidden) (text vocab) - cb-i head (i≥1) = audio_lm_heads.{i-1}(depth_pos_i_hidden) - compose = transformer.wte(text_token) + sum_i audio_embeddings.{i}(c_i) + backbone = GPT-2 + RoPE 12L (`transformer`, llama.cpp starcoder2) + depth = 1-layer GPT-2 local_transformer over 17 positions + per-step = 17 channels (cb-0 = text slot via the tied wte head, + cb-1..16 = audio) + cb-0 input = backbone hidden + cb-i input (i≥1) = wte(text slot) for i = 1, audio_embeddings.{i-2} after + heads = tied to the input tables (wte, audio_embeddings.*) + compose = wte(text slot) + sum_i audio_embeddings.{i}(c_i) + (the sum over all 17 tables) Both fit the `residual_depth_ar` kind with `depth_emits_c0 = true` -(`c0_input_modality = "none"`). The differences land in metadata -(`codec.lm.depth.arch ∈ {"qwen3", "gpt2"}`, `codec.lm.residual.cb0_vocab`) -and in two extra Nano-only tensors (`lm.depth.heads_0` = text head, -`lm.depth.cb0_input_embd.weight` = wte for compose). - -NOT yet covered: GPT-2 depth-block runtime support (Nano) — landing -in a follow-up commit. This file already emits the GGUF in a shape -the runtime can consume once the gpt2 depth block ships; until then, -only `MossTTSRealtime` is exposed via the dispatcher. +(`c0_input_modality = "none"`); `codec.lm.depth.arch` picks the block +("qwen3" / "gpt2"). """ from __future__ import annotations +from pathlib import Path from typing import Any, Dict, List, Tuple import numpy as np @@ -273,12 +269,156 @@ def _dump_realtime(writer, sd: Dict[str, np.ndarray], # --------------------------------------------------------------------- -# MOSS-TTS-Nano-100M (stub for now — GPT-2 depth-block runtime pending) +# MOSS-TTS-Nano-100M # --------------------------------------------------------------------- +# prompting.py (MOSS-TTS-Nano-100M @ 44502f80). Each piece is SentencePiece- +# encoded on its own (add_dummy_prefix every time), so joint tokenization of +# the template differs; the GGUF carries the token ids. +_NANO_USER_ROLE_PREFIX = "user\n" +_NANO_REFERENCE_PREFIX = "\n- Reference(s):\n" +_NANO_AFTER_REFERENCE = ("\n- Instruction:\nNone\n" + "- Tokens:\nNone\n" + "- Quality:\nNone\n" + "- Sound Event:\nNone\n" + "- Ambient Sound:\nNone\n" + "- Language:\nNone\n" + "- Text:\n") +_NANO_USER_SUFFIX = "\n" +_NANO_ASSISTANT_TURN_PREFIX = "\n" +_NANO_ASSISTANT_ROLE_PREFIX = "assistant\n" +# The text slot keeps the control-token rows of wte: the depth decoder only +# ever reads the assistant slot (and the backbone the user slot) and only +# chooses between the assistant slot and the audio end. +_NANO_TEXT_ROWS = 16 + + def _dump_nano(writer, sd, cfg, *, verbose: bool) -> None: - raise NotImplementedError( - "MOSS-TTS-Nano dump: pending `codec.lm.depth.arch=gpt2` runtime " - "(LayerNorm + GELU + fused c_attn split + absolute wpe). Will " - "land in a follow-up commit." - ) + """MossTTSNanoForCausalLM: GPT-2 global transformer (the llama.cpp backbone, + convert-backbone-to-gguf.py) + a 1-layer GPT-2 local transformer over 17 + positions per 12.5 Hz frame: + + pos 0 input = backbone hidden → text_lm_head (wte, tied) + pos 1 input = wte[text token] → audio_lm_heads.0 (= audio_embeddings.0) + pos k+1 input = audio_embeddings.{k-1} → audio_lm_heads.k (= audio_embeddings.k) + + As residual_depth_ar with depth_emits_c0: n_codebook = 17, codebook 0 the + text slot (only the assistant slot / audio end may be sampled), 1..16 the + RVQ codes. Heads are tied to the depth input tables, which are also the + compose tables: the backbone input of a frame is wte[text] + Σ audio rows, + i.e. the sum over all 17 tables.""" + from sentencepiece import SentencePieceProcessor + from sentencepiece import sentencepiece_model_pb2 as spm_pb2 + + g = cfg["gpt2_config"] + n_vq = int(cfg["n_vq"]) + sizes = [int(x) for x in cfg["audio_codebook_sizes"]] + hidden = int(cfg.get("hidden_size", g["n_embd"])) + n_head = int(g["n_head"]) + head_dim = hidden // n_head + inter = int(g.get("n_inner") or 4 * hidden) + n_layers = int(cfg.get("local_transformer_layers", 1)) + eps = float(g.get("layer_norm_epsilon", 1e-5)) + if str(g.get("position_embedding_type", "absolute")).lower() != "rope": + raise NotImplementedError("MOSS-TTS-Nano local transformer without RoPE") + if g.get("activation_function") != "gelu_new": + raise NotImplementedError(f"MOSS-TTS-Nano activation {g.get('activation_function')!r}") + pad = int(cfg["audio_pad_token_id"]) + ids = {k: int(cfg[k + "_token_id"]) for k in ("audio_start", "audio_end", "audio_user_slot", + "audio_assistant_slot", "im_start", "im_end")} + if max(ids.values()) >= _NANO_TEXT_ROWS: + raise RuntimeError(f"control token ids {ids} beyond the {_NANO_TEXT_ROWS} kept wte rows") + wte = sd["transformer.wte.weight"] + for i in range(n_vq): + if not np.array_equal(sd.get(f"audio_lm_heads.{i}.weight", sd[f"audio_embeddings.{i}.weight"]), + sd[f"audio_embeddings.{i}.weight"]): + raise RuntimeError(f"audio_lm_heads.{i} is not tied to audio_embeddings.{i}") + + n_codebook = 1 + n_vq + writer.add_bool ("codec.lm.has_adaptor", True) + writer.add_string ("codec.lm.kind", "residual_depth_ar") + writer.add_string ("codec.lm.host_arch", "starcoder2") + writer.add_uint32 ("codec.lm.hidden_dim", hidden) + writer.add_uint32 ("codec.lm.audio_embed_dim", hidden) + writer.add_uint32 ("codec.lm.n_codebook", n_codebook) + writer.add_array ("codec.lm.codebook_sizes", [_NANO_TEXT_ROWS] + sizes) + writer.add_array ("codec.lm.delay_pattern", [0] * n_codebook) + writer.add_int32 ("codec.lm.eos_code_c0", ids["audio_end"]) + writer.add_int32 ("codec.lm.eos_min_step", 0) + writer.add_array ("codec.lm.cb0_allowed", [ids["audio_assistant_slot"], ids["audio_end"]]) + writer.add_uint32 ("codec.lm.audio_cb_offset", 1) # codebook 0 is text, dropped before decode + writer.add_bool ("codec.lm.modality.input_text", True) + writer.add_bool ("codec.lm.modality.input_audio", True) + writer.add_bool ("codec.lm.modality.output_audio", True) + + writer.add_uint32 ("codec.lm.residual.depth_layers", n_layers) + writer.add_uint32 ("codec.lm.residual.depth_hidden", hidden) + writer.add_uint32 ("codec.lm.residual.depth_n_heads", n_head) + writer.add_uint32 ("codec.lm.residual.depth_n_kv_heads", n_head) + writer.add_uint32 ("codec.lm.residual.depth_head_dim", head_dim) + writer.add_uint32 ("codec.lm.residual.depth_intermediate", inter) + writer.add_uint32 ("codec.lm.residual.depth_max_position", n_codebook) + writer.add_float32("codec.lm.residual.depth_rms_norm_eps", eps) # the LayerNorm eps + writer.add_float32("codec.lm.residual.depth_rope_theta", float(g.get("rope_base", 10000.0))) + writer.add_bool ("codec.lm.residual.depth_has_in_proj", False) + writer.add_bool ("codec.lm.residual.depth_has_qk_norm", False) + writer.add_bool ("codec.lm.residual.depth_use_rope", True) + writer.add_bool ("codec.lm.residual.depth_rope_interleaved", True) # rotate_half on (2i, 2i+1) + writer.add_bool ("codec.lm.residual.depth_emits_c0", True) + writer.add_bool ("codec.lm.residual.heads_tied_to_embd", True) + writer.add_string ("codec.lm.residual.weight_layout", "shared") + writer.add_string ("codec.lm.residual.c0_input_modality", "none") + writer.add_string ("codec.lm.depth.arch", "gpt2") + + # Depth input / head / compose tables: wte's control rows, then the codebooks. + writer.add_tensor("lm.depth.audio_embd_0.weight", wte[:_NANO_TEXT_ROWS].astype(np.float32), st_dtype="F16") + for i in range(n_vq): + arr = sd[f"audio_embeddings.{i}.weight"] + if arr.shape != (sizes[i], hidden): + raise RuntimeError(f"audio_embeddings.{i} shape {arr.shape} != ({sizes[i]}, {hidden})") + writer.add_tensor(f"lm.depth.audio_embd_{i + 1}.weight", arr.astype(np.float32), st_dtype="F16") + + for l in range(n_layers): + p, o = f"local_transformer.h.{l}.", f"lm.depth.blk_{l}." + qkv_w = sd[p + "attn.c_attn.weight"] + qkv_b = sd[p + "attn.c_attn.bias"] + if qkv_w.shape != (3 * hidden, hidden): + raise RuntimeError(f"{p}attn.c_attn.weight shape {qkv_w.shape}") + for name, w, b in zip(("q", "k", "v"), np.split(qkv_w, 3, axis=0), np.split(qkv_b, 3, axis=0)): + writer.add_tensor(o + name + ".weight", w.astype(np.float32), st_dtype="F16") + writer.add_tensor(o + name + ".bias", b.astype(np.float32), st_dtype="F32") + for src, dst in (("attn.c_proj", "o"), ("mlp.fc_in", "ffn_up"), ("mlp.fc_out", "ffn_down")): + writer.add_tensor(o + dst + ".weight", sd[p + src + ".weight"].astype(np.float32), st_dtype="F16") + writer.add_tensor(o + dst + ".bias", sd[p + src + ".bias"].astype(np.float32), st_dtype="F32") + for src, dst in (("ln_1", "attn_norm"), ("ln_2", "ffn_norm")): + writer.add_tensor(o + dst + ".weight", sd[p + src + ".weight"].astype(np.float32), st_dtype="F32") + writer.add_tensor(o + dst + ".bias", sd[p + src + ".bias"].astype(np.float32), st_dtype="F32") + writer.add_tensor("lm.depth.output_norm.weight", sd["local_transformer.ln_f.weight"].astype(np.float32), + st_dtype="F32") + writer.add_tensor("lm.depth.output_norm.bias", sd["local_transformer.ln_f.bias"].astype(np.float32), + st_dtype="F32") + + # Prompt template (token ids) + the tokenizer's normalizer for the host. + tok_path = Path(cfg["_source_dir"]) / "tokenizer.model" + sp = SentencePieceProcessor(model_file=str(tok_path)) + enc = lambda t: [int(x) for x in sp.encode(t)] + pre = "codec.lm.moss_tts_nano." + writer.add_array(pre + "user_prefix", [ids["im_start"]] + enc(_NANO_USER_ROLE_PREFIX) + enc(_NANO_REFERENCE_PREFIX)) + writer.add_array(pre + "no_reference", enc("None")) + writer.add_array(pre + "after_reference", enc(_NANO_AFTER_REFERENCE)) + writer.add_array(pre + "assistant_prefix", enc(_NANO_USER_SUFFIX) + [ids["im_end"]] + + enc(_NANO_ASSISTANT_TURN_PREFIX) + [ids["im_start"]] + enc(_NANO_ASSISTANT_ROLE_PREFIX)) + for k in ("audio_start", "audio_end", "audio_user_slot", "audio_assistant_slot"): + writer.add_uint32(pre + k, ids[k]) + writer.add_uint32(pre + "audio_pad", pad) + m = spm_pb2.ModelProto() + m.ParseFromString(tok_path.read_bytes()) + ns = m.normalizer_spec + if not (ns.add_dummy_prefix and ns.remove_extra_whitespaces and ns.escape_whitespaces): + raise NotImplementedError("MOSS-TTS-Nano tokenizer normalizer flags changed") + writer.add_string(pre + "text_norm", ns.name) + writer.add_uint8_array(pre + "text_norm_charsmap", ns.precompiled_charsmap) + + if verbose: + print(f"[lm_adaptor:moss_tts_local:nano] residual_depth_ar gpt2: n_codebook={n_codebook} " + f"hidden={hidden} depth={n_layers}L heads={n_head} ffn={inter}") diff --git a/scripts/utils/gguf_writer.py b/scripts/utils/gguf_writer.py index a12106f..e80020d 100644 --- a/scripts/utils/gguf_writer.py +++ b/scripts/utils/gguf_writer.py @@ -12,6 +12,7 @@ # GGUF constants MAX_TENSOR_NAME = 63 +KV_UINT8 = 0 KV_UINT32 = 4 KV_INT32 = 5 KV_FLOAT32 = 6 @@ -119,6 +120,10 @@ def add_array(self, key: str, values): payload = [int(x) for x in arr.tolist()] self.kv.append((key, KV_ARRAY, (elem_type, payload))) + def add_uint8_array(self, key: str, data: bytes): + """Add a byte-array metadata value (GGUF UINT8 array), e.g. a binary blob.""" + self.kv.append((key, KV_ARRAY, (KV_UINT8, bytes(data)))) + def add_tensor(self, name: str, arr: np.ndarray, st_dtype: str = None): """ Add a tensor to the GGUF file. @@ -275,7 +280,9 @@ def _encode_kv(self, key: str, t: int, v) -> bytes: elem_type, payload = v out += _i32(int(elem_type)) out += _u64(len(payload)) - if elem_type == KV_UINT32: + if elem_type == KV_UINT8: + out += bytes(payload) + elif elem_type == KV_UINT32: for item in payload: out += _u32(int(item)) elif elem_type == KV_INT32: diff --git a/src/lm/residual_depth_ar.cpp b/src/lm/residual_depth_ar.cpp index 7f52cef..080218e 100644 --- a/src/lm/residual_depth_ar.cpp +++ b/src/lm/residual_depth_ar.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include // ===================================================================== @@ -62,6 +63,16 @@ struct rda_layer_w { ggml_tensor * ffn_down; ggml_tensor * q_norm; // optional (Qwen3 family) ggml_tensor * k_norm; // optional + // GPT-2 depth blocks (`codec.lm.depth.arch = "gpt2"`, MOSS-TTS-Nano): LayerNorm + // shifts and linear biases; ffn_gate is absent (non-gated gelu_new FFN). + ggml_tensor * attn_norm_b = nullptr; + ggml_tensor * q_b = nullptr; + ggml_tensor * k_b = nullptr; + ggml_tensor * v_b = nullptr; + ggml_tensor * o_b = nullptr; + ggml_tensor * ffn_norm_b = nullptr; + ggml_tensor * ffn_up_b = nullptr; + ggml_tensor * ffn_down_b = nullptr; }; struct rda_impl { @@ -101,6 +112,11 @@ struct rda_impl { int32_t cb0_suppress_from = -1; // cb0 ids >= this (bar eos_code_c0) are // never sampled; -1 = none. Qwen3-TTS: // vocab - 1024 (its control tags). + std::vector cb0_allowed; // when set, the only cb0 ids ever sampled + // (MOSS-TTS-Nano: assistant slot / audio end) + bool depth_gpt2 = false; // `codec.lm.depth.arch = "gpt2"`: LayerNorm (+bias), + // biased q/k/v/o, gelu_new FFN (MOSS-TTS-Nano) + bool heads_tied = false; // depth head i = audio_embds[i] (tied embeddings) // Tensor handles (live in codec->weights). One uniform layout — // the per-pos linear inside `codec_op_lm_per_pos_linear` handles @@ -138,6 +154,7 @@ struct rda_impl { ggml_tensor * in_proj = nullptr; // 2D (shared) or 3D (per-pos) ggml_tensor * in_proj_bias = nullptr; // 1D (Qwen3-TTS) or 2D (LFM2) ggml_tensor * depth_output_norm = nullptr; // present except Moshi/LFM2 + ggml_tensor * depth_output_norm_b = nullptr; // gpt2: the final LayerNorm's shift ggml_tensor * rope_freq_factors = nullptr; // llama3 RoPE scaling std::vector layers; // per-layer weights (2D or 3D) @@ -385,6 +402,14 @@ bool rda_build_c0(ggml_context * ctx_eval, void * ud, ggml_tensor ** out) { // RMSNorm before the logits matmul. Head storage picks one of: // - 3D `lm.depth.heads.weight` slice (Moshi) — `flex_heads != nullptr` // - 2D `lm.depth.heads_{i}.weight` — `depth_heads[head_idx]` +ggml_tensor * rda_depth_layer_kv( + ggml_context * ctx, ggml_tensor * x_ht, const rda_layer_w & w, + ggml_tensor * t_pos, ggml_tensor * freq_factors, + int32_t head_dim, int32_t n_heads, int32_t n_kv_heads, + float rope_theta, float rms_eps, bool has_qk_norm, int32_t rope_mode, bool use_rope, + ggml_tensor * k_cache_l, ggml_tensor * v_cache_l, int32_t kv_pos_start, int32_t kv_total, + bool gpt2 = false); + struct rda_depth_build { rda_impl * impl; int32_t T; // prefix length (= current_k + 1) @@ -473,17 +498,27 @@ bool rda_build_depth_step(ggml_context * ctx_eval, void * ud, ggml_tensor ** out std::vector & layers = impl->layers; for (int32_t l = 0; l < impl->depth_layers; ++l) { - x = rda_depth_layer( - ctx_eval, x, layers[(size_t) l], t_pos, freqs, - impl->depth_head_dim, impl->depth_n_heads, impl->depth_n_kv_heads, - impl->depth_rope_theta, impl->depth_rms_eps, - impl->has_qk_norm, rope_mode, impl->use_rope); + x = impl->depth_gpt2 + // The KV path's block without a cache: causal attention over the T rows. + ? rda_depth_layer_kv( + ctx_eval, x, layers[(size_t) l], t_pos, freqs, + impl->depth_head_dim, impl->depth_n_heads, impl->depth_n_kv_heads, + impl->depth_rope_theta, impl->depth_rms_eps, + impl->has_qk_norm, rope_mode, impl->use_rope, + nullptr, nullptr, 0, T, /*gpt2=*/true) + : rda_depth_layer( + ctx_eval, x, layers[(size_t) l], t_pos, freqs, + impl->depth_head_dim, impl->depth_n_heads, impl->depth_n_kv_heads, + impl->depth_rope_theta, impl->depth_rms_eps, + impl->has_qk_norm, rope_mode, impl->use_rope); } // ---- Optional output norm ------------------------------------------ if (impl->has_output_norm && impl->depth_output_norm != nullptr) { ggml_tensor * onorm = codec_graph_cast_f32(ctx_eval, impl->depth_output_norm); - x = codec_op_rms_norm_ct(ctx_eval, x, impl->depth_rms_eps, onorm); + x = impl->depth_gpt2 + ? codec_op_layer_norm_ct(ctx_eval, x, impl->depth_rms_eps, onorm, impl->depth_output_norm_b) + : codec_op_rms_norm_ct(ctx_eval, x, impl->depth_rms_eps, onorm); } // ---- Per-cb head at the last position ------------------------------ @@ -564,18 +599,29 @@ ggml_tensor * rda_depth_layer_kv( ggml_tensor * k_cache_l, ggml_tensor * v_cache_l, int32_t kv_pos_start, - int32_t kv_total) { + int32_t kv_total, + bool gpt2) { const int64_t T_new = x_ht->ne[1]; const int32_t q_dim = n_heads * head_dim; const int32_t kv_dim = n_kv_heads * head_dim; + // Llama: RMSNorm, bias-free linears, SwiGLU. GPT-2 (gpt2 = true): LayerNorm + // with shift, linears with biases, gelu_new. `rms_eps` is the norm's eps. + auto norm = [&](ggml_tensor * x, ggml_tensor * g, ggml_tensor * b) { + return gpt2 ? codec_op_layer_norm_ct(ctx, x, rms_eps, g, b) : codec_op_rms_norm_ct(ctx, x, rms_eps, g); + }; + auto linear = [&](ggml_tensor * wt, ggml_tensor * b, ggml_tensor * x, int32_t out_dim) { + ggml_tensor * y = codec_op_lm_per_pos_linear(ctx, wt, x, out_dim, (int32_t) T_new); + return b != nullptr ? ggml_add(ctx, y, codec_graph_cast_f32(ctx, b)) : y; + }; + // ── Attention pre-norm + projections (T_new positions) ───────── - ggml_tensor * h = codec_op_rms_norm_ct(ctx, x_ht, rms_eps, w.attn_norm); + ggml_tensor * h = norm(x_ht, w.attn_norm, w.attn_norm_b); - ggml_tensor * q = codec_op_lm_per_pos_linear(ctx, w.q, h, q_dim, (int32_t) T_new); - ggml_tensor * k_new = codec_op_lm_per_pos_linear(ctx, w.k, h, kv_dim, (int32_t) T_new); - ggml_tensor * v_new = codec_op_lm_per_pos_linear(ctx, w.v, h, kv_dim, (int32_t) T_new); + ggml_tensor * q = linear(w.q, w.q_b, h, q_dim); + ggml_tensor * k_new = linear(w.k, w.k_b, h, kv_dim); + ggml_tensor * v_new = linear(w.v, w.v_b, h, kv_dim); q = ggml_reshape_3d(ctx, q, head_dim, n_heads, T_new); k_new = ggml_reshape_3d(ctx, k_new, head_dim, n_kv_heads, T_new); @@ -601,7 +647,7 @@ ggml_tensor * rda_depth_layer_kv( // ── Build the full K/V for attention via concat with cache ───── ggml_tensor * k_all; ggml_tensor * v_all; - if (kv_pos_start > 0) { + if (kv_pos_start > 0 && k_cache_l != nullptr) { // Cache view (positions 0 .. kv_pos_start) → concat with new. ggml_tensor * k_old = ggml_view_3d(ctx, k_cache_l, head_dim, n_kv_heads, (int64_t) kv_pos_start, @@ -637,13 +683,15 @@ ggml_tensor * rda_depth_layer_kv( attn = ggml_reshape_2d(ctx, attn, (int64_t) q_dim, T_new); const int32_t hidden = (int32_t) x_ht->ne[0]; - ggml_tensor * o = codec_op_lm_per_pos_linear(ctx, w.o, attn, hidden, (int32_t) T_new); + ggml_tensor * o = linear(w.o, w.o_b, attn, hidden); x_ht = ggml_add(ctx, x_ht, o); // ── Cache writes (side-effect roots) ──────────────────────────── // ggml_cpy(src, dst) returns a view of dst; flag both with // ggml_set_output so the codec.cpp graph framework expands them as // separate roots, guaranteeing they're executed in this compute. + // No cache (the prefix-recompute path): attention over the new rows only. + if (k_cache_l != nullptr && v_cache_l != nullptr) { ggml_tensor * k_dst = ggml_view_3d(ctx, k_cache_l, head_dim, n_kv_heads, T_new, k_cache_l->nb[1], k_cache_l->nb[2], @@ -656,9 +704,15 @@ ggml_tensor * rda_depth_layer_kv( ggml_tensor * v_cpy = ggml_cpy(ctx, v_new, v_dst); ggml_set_output(k_cpy); ggml_set_output(v_cpy); + } - // ── FFN (SwiGLU) ──────────────────────────────────────────────── - h = codec_op_rms_norm_ct(ctx, x_ht, rms_eps, w.ffn_norm); + // ── FFN (SwiGLU, or GPT-2's gelu_new MLP) ─────────────────────── + h = norm(x_ht, w.ffn_norm, w.ffn_norm_b); + if (gpt2) { + const int32_t inter = (int32_t) w.ffn_up->ne[1]; + ggml_tensor * up = ggml_gelu(ctx, linear(w.ffn_up, w.ffn_up_b, h, inter)); // tanh form = gelu_new + return ggml_add(ctx, x_ht, linear(w.ffn_down, w.ffn_down_b, up, hidden)); + } const int32_t inter = (int32_t) w.ffn_gate->ne[1]; ggml_tensor * gate = codec_op_lm_per_pos_linear(ctx, w.ffn_gate, h, inter, (int32_t) T_new); ggml_tensor * up = codec_op_lm_per_pos_linear(ctx, w.ffn_up, h, inter, (int32_t) T_new); @@ -729,11 +783,13 @@ bool rda_build_depth_step_kv(ggml_context * ctx_eval, void * ud, ggml_tensor ** impl->depth_rope_theta, impl->depth_rms_eps, impl->has_qk_norm, rope_mode, impl->use_rope, b->k_cache[(size_t) l], b->v_cache[(size_t) l], - kv_pos_start, kv_total); + kv_pos_start, kv_total, impl->depth_gpt2); } if (impl->has_output_norm && impl->depth_output_norm != nullptr) { - x = codec_op_rms_norm_ct(ctx_eval, x, impl->depth_rms_eps, impl->depth_output_norm); + x = impl->depth_gpt2 + ? codec_op_layer_norm_ct(ctx_eval, x, impl->depth_rms_eps, impl->depth_output_norm, impl->depth_output_norm_b) + : codec_op_rms_norm_ct(ctx_eval, x, impl->depth_rms_eps, impl->depth_output_norm); } // Pick last position. @@ -837,6 +893,16 @@ bool init(codec_lm * lm) { impl->has_pre_head_norm = codec_read_bool_kv(gf, "codec.lm.residual.depth_has_pre_head_norm", false); impl->depth_emits_c0 = codec_read_bool_kv(gf, "codec.lm.residual.depth_emits_c0", false); impl->rope_interleaved = codec_read_bool_kv(gf, "codec.lm.residual.depth_rope_interleaved", false); + impl->heads_tied = codec_read_bool_kv(gf, "codec.lm.residual.heads_tied_to_embd", false); + impl->depth_gpt2 = codec_lm_read_string_kv(lm->codec, "codec.lm.depth.arch") == "gpt2"; + codec_read_i32_array_kv_vec(gf, "codec.lm.cb0_allowed", &impl->cb0_allowed); + for (int32_t id : impl->cb0_allowed) { + if (lm->codebook_sizes_buf.empty() || id < 0 || id >= lm->codebook_sizes_buf[0]) { + lm->last_error = "codec.lm.cb0_allowed holds an id outside codebook 0"; + delete impl; + return false; + } + } { std::string m = codec_lm_read_string_kv( @@ -915,6 +981,14 @@ bool init(codec_lm * lm) { if (t == nullptr) break; impl->depth_heads.push_back(t); } + // Tied heads: head i is embedding table i (same (dim, vocab) layout). + if (impl->depth_heads.empty() && impl->heads_tied) { + if ((int32_t) impl->audio_embds.size() != impl->n_codebook) { + lm->last_error = "heads_tied_to_embd needs one lm.depth.audio_embd_{i} per codebook"; + delete impl; return false; + } + impl->depth_heads = impl->audio_embds; + } } if (impl->flex_heads == nullptr && impl->depth_heads.empty()) { lm->last_error = "no depth heads found " @@ -958,6 +1032,10 @@ bool init(codec_lm * lm) { if (impl->has_output_norm) { impl->depth_output_norm = find_required(lm, "lm.depth.output_norm.weight"); if (!impl->depth_output_norm) { delete impl; return false; } + if (impl->depth_gpt2) { + impl->depth_output_norm_b = find_required(lm, "lm.depth.output_norm.bias"); + if (!impl->depth_output_norm_b) { delete impl; return false; } + } } // Optional llama3 RoPE freq factors. @@ -999,8 +1077,23 @@ bool init(codec_lm * lm) { w.o = find_required(lm, buf); if (!w.o) { delete impl; return false; } std::snprintf(buf, sizeof(buf), "lm.depth.blk_%d.ffn_norm.weight", l); w.ffn_norm = find_required(lm, buf); if (!w.ffn_norm) { delete impl; return false; } - std::snprintf(buf, sizeof(buf), "lm.depth.blk_%d.ffn_gate.weight", l); - w.ffn_gate = find_required(lm, buf); if (!w.ffn_gate) { delete impl; return false; } + if (!impl->depth_gpt2) { + std::snprintf(buf, sizeof(buf), "lm.depth.blk_%d.ffn_gate.weight", l); + w.ffn_gate = find_required(lm, buf); if (!w.ffn_gate) { delete impl; return false; } + } else { + w.ffn_gate = nullptr; + // GPT-2: every norm has a shift and every linear a bias. + const std::pair biases[] = { + {"attn_norm.bias", &w.attn_norm_b}, {"q.bias", &w.q_b}, {"k.bias", &w.k_b}, {"v.bias", &w.v_b}, + {"o.bias", &w.o_b}, {"ffn_norm.bias", &w.ffn_norm_b}, {"ffn_up.bias", &w.ffn_up_b}, + {"ffn_down.bias", &w.ffn_down_b}, + }; + for (const auto & b : biases) { + std::snprintf(buf, sizeof(buf), "lm.depth.blk_%d.%s", l, b.first); + *b.second = find_required(lm, buf); + if (*b.second == nullptr) { delete impl; return false; } + } + } std::snprintf(buf, sizeof(buf), "lm.depth.blk_%d.ffn_up.weight", l); w.ffn_up = find_required(lm, buf); if (!w.ffn_up) { delete impl; return false; } std::snprintf(buf, sizeof(buf), "lm.depth.blk_%d.ffn_down.weight", l); @@ -1552,6 +1645,14 @@ const float * step_logits(codec_lm_state * st, int32_t * out_cb_idx, int32_t * o return nullptr; } } + if (k == 0 && !impl->cb0_allowed.empty()) { + // Only these ids are candidates (the reference samples from their logits alone). + std::vector & lg = sst->logits_buf[0]; + std::vector keep(impl->cb0_allowed.size()); + for (size_t i = 0; i < keep.size(); ++i) keep[i] = lg[(size_t) impl->cb0_allowed[i]]; + std::fill(lg.begin(), lg.end(), -INFINITY); + for (size_t i = 0; i < keep.size(); ++i) lg[(size_t) impl->cb0_allowed[i]] = keep[i]; + } if (out_cb_idx) *out_cb_idx = k; if (out_n) *out_n = st->lm->info.codebook_sizes[k]; return sst->logits_buf[(size_t) k].data(); From af5e74cb16672f54cddbea05f8fdfc43fb940925 Mon Sep 17 00:00:00 2001 From: Hans Date: Sat, 14 Nov 2026 19:32:46 +0800 Subject: [PATCH 03/11] feat(moss-tts-nano): MOSS-Audio voices from reference audio (ref_codes) A MOSS-TTS-Nano voice is the reference clip's codes, which the LM prompt embeds. codec_speaker_from_audio on a MOSS-Audio-Tokenizer GGUF runs one graph: torchaudio-style sinc resample to the codec rate, mono copied to every interleaved channel, zero pad to the hop, encoder + quantizer, and keeps floor(n / hop) frames as the reference does. The slot is `ref_codes` I32 [n_q, T]. Only GGUFs converted with a MOSS-TTS-Nano LM source carry `moss_audio_tokenizer.spk.encoder_hash` (encoder + quantizer weights and the preprocessing) and offer it. Codes vs the reference's batch_encode on the zh / ja / en eval clips: 96% (F32 codec), the same as plain codec_encode on the reference's own resampled audio; the misses are deep RVQ levels. Co-Authored-By: Claude Opus 5.5 --- scripts/converters/moss_audio.py | 19 ++++ src/models/moss_audio.cpp | 176 ++++++++++++++++++++++++++----- src/runtime/graph.h | 1 + 3 files changed, 172 insertions(+), 24 deletions(-) diff --git a/scripts/converters/moss_audio.py b/scripts/converters/moss_audio.py index 7b11e0f..673c09d 100644 --- a/scripts/converters/moss_audio.py +++ b/scripts/converters/moss_audio.py @@ -81,6 +81,15 @@ def _load_state_dict(path: Path) -> Dict[str, np.ndarray]: return OrderedDict((k, _to_numpy(v)) for k, v in state.items()) +def _lm_source_arch(lm_source) -> str: + p = Path(str(lm_source)) + cfg = p / "config.json" if p.is_dir() else p.parent / "config.json" + if not cfg.is_file(): + return "" + archs = json.loads(cfg.read_text()).get("architectures") or [] + return archs[0] if archs else "" + + class MossAudioConverter(BaseConverter): """MOSS-Audio-Tokenizer (Nano + full) converter. @@ -355,6 +364,16 @@ def add_transformer_layer(prefix: str, out_name: str) -> None: if self.lm_source is not None: from .lm_adaptor import dump_lm_into dump_lm_into(writer, self.lm_source, verbose=self.verbose) + if _lm_source_arch(self.lm_source) == "MossTTSNanoForCausalLM": + # Voices of MOSS-TTS-Nano are the reference clip's codes (`ref_codes`, + # codec_speaker_from_audio: resample to the codec rate, mono copied to + # every channel, encode). The hash covers the encoder + quantizer. + from .speaker import encoder_hash + enc = [(k, np.asarray(v, dtype=np.float32)) for k, v in sd.items() + if k.startswith(("encoder.", "quantizer."))] + params = (f"moss_audio ref_codes: sinc_hann resample to {sr} Hz, mono x{n_channels} channels, " + f"whole clip, floor(n / {downsample}) frames, {n_q} codebooks") + writer.add_string(f"{self.architecture}.spk.encoder_hash", encoder_hash(enc, params)) self._warn_if_no_quantized() writer.write() diff --git a/src/models/moss_audio.cpp b/src/models/moss_audio.cpp index 3038eef..7edc7ac 100644 --- a/src/models/moss_audio.cpp +++ b/src/models/moss_audio.cpp @@ -1,5 +1,6 @@ #include "moss_audio.h" +#include "../ops/audio_frontend.h" #include "../ops/conv1d.h" #include "../ops/ggml_ops.h" #include "../ops/lm_attn.h" @@ -259,29 +260,19 @@ struct moss_encode_build { const codec_model * model = nullptr; }; -static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, ggml_tensor ** out) { - moss_encode_build * p = static_cast(user_data); - if (ctx_eval == nullptr || p == nullptr || out == nullptr || p->model == nullptr || p->cfg == nullptr) return false; +// The encoder + quantizer on `x_tc` [n_in * n_channels (interleaved), 1]; +// returns codes [t, n_q] I32. +static ggml_tensor * codec_moss_encode_from(ggml_context * ctx_eval, const moss_encode_build * p, ggml_tensor * x_tc) { const codec_moss_audio & cfg = *p->cfg; auto W = [&](const std::string & name) -> ggml_tensor * { return codec_graph_weight(ctx_eval, p->model, name); }; - // Input PCM laid out as a single mono-equivalent stream. When - // interleaving is on the prep step has already woven channels together, - // so the graph sees a length-`n_in * n_channels` flat tensor. - const int32_t n_total = p->n_in * (p->interleave ? p->n_channels : 1); - ggml_tensor * t_pcm = ggml_new_tensor_2d(ctx_eval, GGML_TYPE_F32, n_total, 1); - ggml_set_name(t_pcm, codec_moss_name_pcm()); - - // The encoder works in TC layout (ne[0]=t, ne[1]=c=1). - ggml_tensor * x_tc = t_pcm; - // Walk the encoder modules. for (int32_t mi = 0; mi < cfg.enc_n_modules; ++mi) { if (cfg.enc_module_type[mi] == 0) { x_tc = codec_moss_patch_encode(ctx_eval, x_tc, cfg.enc_patch_size[mi]); - if (x_tc == nullptr) return false; + if (x_tc == nullptr) return nullptr; } else { const std::string base = "moss.enc.b" + std::to_string(mi); ggml_tensor * x_ct = ggml_cont(ctx_eval, ggml_transpose(ctx_eval, x_tc)); @@ -313,7 +304,7 @@ static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, g cfg.enc_in_dim[mi], cfg.enc_out_dim[mi], cfg.enc_d_model[mi], cfg.enc_n_heads[mi], cfg.enc_n_layers[mi], win_tokens, cfg.enc_max_period[mi], n_valid_block); - if (x_ct == nullptr) return false; + if (x_ct == nullptr) return nullptr; x_tc = ggml_cont(ctx_eval, ggml_transpose(ctx_eval, x_ct)); } } @@ -324,7 +315,7 @@ static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, g W("moss.q.input_proj.w"), W("moss.q.input_proj.b"), /*stride=*/1, /*dilation=*/1, /*padding=*/0); - if (x_tc == nullptr) return false; + if (x_tc == nullptr) return nullptr; const int32_t cb_dim = p->cb_dim; // Residual LFQ: each level @@ -335,7 +326,7 @@ static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, g // residual -= z_q_e ggml_tensor * residual = x_tc; ggml_tensor * codes_per_level[64] = { nullptr }; - if (p->n_q > 64) return false; + if (p->n_q > 64) return nullptr; for (int32_t qi = 0; qi < p->n_q; ++qi) { const std::string base = "moss.q." + std::to_string(qi); @@ -344,7 +335,7 @@ static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, g W(base + ".in_proj.w"), W(base + ".in_proj.b"), 1, 1, 0); - if (z_e == nullptr) return false; + if (z_e == nullptr) return nullptr; // L2-normalize per t-step (shared helper), then move to CT for the // upcoming mul_mat against the codebook. @@ -354,7 +345,7 @@ static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, g // Cosine sims: (cb_size, cb_dim) @ (cb_dim, t) → (cb_size, t). Use // mul_mat which contracts ne[0]=cb_dim. ggml_tensor * cb_norm = W(base + ".codebook_norm"); - if (cb_norm == nullptr) return false; + if (cb_norm == nullptr) return nullptr; cb_norm = codec_graph_stored_weight(ctx_eval, cb_norm); // search at the stored type ggml_tensor * sims = ggml_mul_mat(ctx_eval, cb_norm, z_n_ct); // [cb_size, t] ggml_tensor * idx = ggml_argmax(ctx_eval, sims); // ne=(t,) i32 @@ -362,14 +353,14 @@ static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, g // Reconstruction: gather codebook (raw, not normalised) + out_proj. ggml_tensor * cb = W(base + ".codebook"); - if (cb == nullptr) return false; + if (cb == nullptr) return nullptr; ggml_tensor * z_q_ct = ggml_get_rows(ctx_eval, codec_graph_stored_weight(ctx_eval, cb), idx); // [cb_dim, t] ggml_tensor * z_q_tc = ggml_cont(ctx_eval, ggml_transpose(ctx_eval, z_q_ct)); ggml_tensor * z_q_proj = codec_conv1d(ctx_eval, z_q_tc, W(base + ".out_proj.w"), W(base + ".out_proj.b"), 1, 1, 0); - if (z_q_proj == nullptr) return false; + if (z_q_proj == nullptr) return nullptr; residual = ggml_sub(ctx_eval, residual, z_q_proj); (void) cb_dim; } @@ -381,12 +372,143 @@ static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, g ggml_tensor * idx_2d = ggml_reshape_2d(ctx_eval, codes_per_level[qi], (int) codes_per_level[qi]->ne[0], 1); codes_2d = (codes_2d == nullptr) ? idx_2d : ggml_concat(ctx_eval, codes_2d, idx_2d, /*dim=*/1); } - codes_2d = ggml_cont(ctx_eval, codes_2d); - ggml_set_name(codes_2d, codec_moss_name_codes()); - *out = codes_2d; + return ggml_cont(ctx_eval, codes_2d); +} + +static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, ggml_tensor ** out) { + moss_encode_build * p = static_cast(user_data); + if (ctx_eval == nullptr || p == nullptr || out == nullptr || p->model == nullptr || p->cfg == nullptr) return false; + // Input PCM laid out as a single mono-equivalent stream. When + // interleaving is on the prep step has already woven channels together, + // so the graph sees a length-`n_in * n_channels` flat tensor (TC layout, + // ne[0]=t, ne[1]=c=1). + const int32_t n_total = p->n_in * (p->interleave ? p->n_channels : 1); + ggml_tensor * t_pcm = ggml_new_tensor_2d(ctx_eval, GGML_TYPE_F32, n_total, 1); + ggml_set_name(t_pcm, codec_moss_name_pcm()); + ggml_tensor * codes = codec_moss_encode_from(ctx_eval, p, t_pcm); + if (codes == nullptr) return false; + ggml_set_name(codes, codec_moss_name_codes()); + *out = codes; return true; } +// ===================================================================== +// Speaker (reference codes) graph — MOSS-TTS-Nano voice clone +// ===================================================================== +// +// modeling_moss_tts_nano.py `_load_reference_audio` + `_call_audio_encode`: +// the clip resampled to the codec rate (torchaudio sinc_interp_hann), mono +// copied to every channel, encoded whole; `floor(n / hop)` frames are kept +// (the reference's code length). One graph: resample → channel interleave → +// zero pad to the hop → encoder + quantizer. + +struct moss_speaker_build { + int32_t n_samples = 0; // reference PCM (mono, any rate) + int32_t sample_rate = 0; + int32_t n_rs = 0; // samples at the codec rate + moss_encode_build enc; +}; + +static bool codec_moss_build_speaker(ggml_context * ctx_eval, void * user_data, ggml_tensor ** out) { + auto * p = static_cast(user_data); + if (ctx_eval == nullptr || p == nullptr || out == nullptr || p->enc.model == nullptr || p->enc.cfg == nullptr) { + return false; + } + const codec_moss_audio & cfg = *p->enc.cfg; + ggml_tensor * pcm = ggml_new_tensor_1d(ctx_eval, GGML_TYPE_F32, p->n_samples); + ggml_set_name(pcm, "moss.spk.pcm"); + ggml_tensor * wav = codec_op_resample_sinc_hann(ctx_eval, pcm, p->sample_rate, cfg.sample_rate); + if (wav == nullptr || ggml_nelements(wav) != p->n_rs) return false; + const int32_t n_ch = p->enc.interleave ? p->enc.n_channels : 1; + ggml_tensor * x = ggml_reshape_2d(ctx_eval, ggml_cont(ctx_eval, wav), 1, p->n_rs); // [1, t] + ggml_tensor * xi = x; + for (int32_t c = 1; c < n_ch; ++c) xi = ggml_concat(ctx_eval, xi, x, 0); // [ch, t]: s0c0 s0c1 … + xi = ggml_reshape_1d(ctx_eval, ggml_cont(ctx_eval, xi), (int64_t) n_ch * p->n_rs); + const int64_t pad = (int64_t) n_ch * (p->enc.n_in - p->n_rs); + if (pad > 0) xi = ggml_pad(ctx_eval, xi, (int) pad, 0, 0, 0); // trailing zeros + ggml_tensor * codes = codec_moss_encode_from(ctx_eval, &p->enc, ggml_reshape_2d(ctx_eval, xi, ggml_nelements(xi), 1)); + if (codes == nullptr) return false; + ggml_set_name(codes, "moss.spk.ref_codes"); + *out = codes; + return true; +} + +static enum codec_status codec_moss_speaker_from_audio( + codec_context * ctx, const std::vector & pcm, int32_t sample_rate, codec_speaker * out) { + const codec_moss_audio & cfg = *static_cast(ctx->model->impl); + if (pcm.empty() || sample_rate <= 0 || pcm.size() > (size_t) INT32_MAX) { + codec_context_set_error(ctx, "invalid reference audio"); + return CODEC_STATUS_INVALID_ARG; + } + moss_speaker_build b; + b.n_samples = (int32_t) pcm.size(); + b.sample_rate = sample_rate; + b.n_rs = (int32_t) codec_resample_out_len((int64_t) pcm.size(), sample_rate, cfg.sample_rate); + const int32_t hop = std::max(1, cfg.hop_size); + const int32_t n_keep = b.n_rs / hop; + if (n_keep < 1) { + codec_context_set_error(ctx, "reference audio shorter than one MOSS-Audio frame"); + return CODEC_STATUS_INVALID_ARG; + } + const int32_t n_in = ((b.n_rs + hop - 1) / hop) * hop; + b.enc.n_in = n_in; + b.enc.n_in_valid = b.n_rs; + b.enc.n_channels = cfg.number_channels; + b.enc.interleave = cfg.channel_interleave; + b.enc.latent_dim = cfg.latent_dim; + b.enc.rvq_dim = cfg.rvq_dim; + b.enc.cb_dim = cfg.codebook_dim; + b.enc.n_q = cfg.n_q; + b.enc.n_codes = n_in / hop; + b.enc.cfg = &cfg; + b.enc.model = ctx->model; + + codec_graph_eval_guard guard(ctx); + std::string err; + codec_graph_cache_entry * entry = nullptr; + if (!codec_graph_cache_get_or_build(ctx, {CODEC_GRAPH_MOSS_AUDIO_SPEAKER, b.n_samples, cfg.n_q, sample_rate, 0, 0}, + codec_moss_build_speaker, &b, sizeof(b), &entry, &err)) { + codec_context_set_error(ctx, "speaker graph: " + err); + return CODEC_STATUS_INTERNAL_ERROR; + } + ggml_tensor * t_pcm = codec_graph_get_tensor(ctx, entry, "moss.spk.pcm"); + ggml_tensor * t_codes = codec_graph_get_tensor(ctx, entry, "moss.spk.ref_codes"); + std::vector codes_tq; + if (t_pcm == nullptr || t_codes == nullptr || + !codec_graph_prepare_io(ctx, entry, &err) || + !codec_runtime_write_tensor(t_pcm, pcm.data(), pcm.size() * sizeof(float), &err) || + !codec_graph_compute(ctx, entry, ctx->n_threads, &err) || + !codec_runtime_read_tensor_i32_2d_tq(t_codes, &codes_tq, &err)) { + codec_context_set_error(ctx, "speaker graph: " + (err.empty() ? std::string("invalid IO") : err)); + return CODEC_STATUS_INTERNAL_ERROR; + } + const int64_t n_t = t_codes->ne[0], n_q = t_codes->ne[1]; + if (n_q != cfg.n_q || n_t < n_keep) { + codec_context_set_error(ctx, "speaker graph: unexpected code shape"); + return CODEC_STATUS_INTERNAL_ERROR; + } + // ref_codes I32 [n_q, T] (ne[0] = n_q): frame t's codes are contiguous. + std::vector ref((size_t) n_keep * (size_t) n_q); + for (int32_t t = 0; t < n_keep; ++t) { + for (int64_t q = 0; q < n_q; ++q) ref[(size_t) (t * n_q + q)] = codes_tq[(size_t) (t * n_q + q)]; + } + const int64_t ne[2] = {n_q, n_keep}; + codec_speaker_add_slot(out, "ref_codes", GGML_TYPE_I32, ne, 2, ref.data()); + return CODEC_STATUS_SUCCESS; +} + +// A MOSS-TTS-Nano voice: `ref_codes` I32 [n_q, T], the reference clip's codes, +// which the LM prompt embeds (it conditions no decoder). +static bool codec_moss_speaker_validate(const codec_model * model, const codec_speaker * spk, std::string * err) { + const codec_moss_audio & cfg = *static_cast(model->impl); + const codec_speaker_slot * rc = spk->slot("ref_codes"); + bool ok = rc != nullptr && rc->type == GGML_TYPE_I32 && rc->ne[0] == cfg.n_q && rc->ne[1] >= 1 && rc->ne[2] == 1; + const auto * v = ok ? reinterpret_cast(rc->data.data()) : nullptr; + for (int64_t i = 0; ok && i < rc->nelements(); ++i) ok = v[i] >= 0 && v[i] < cfg.codebook_size; + if (!ok) *err = "MOSS-Audio speaker needs an I32 [" + std::to_string(cfg.n_q) + ", T] ref_codes slot"; + return ok; +} + // ===================================================================== // Decode graph // ===================================================================== @@ -815,6 +937,9 @@ enum codec_status codec_moss_audio_init(struct codec_model * model) { model->codebook_size = cfg.codebook_size; model->latent_dim = cfg.latent_dim; model->expected_channels = cfg.number_channels; + // Voices (reference codes) only for GGUFs converted for MOSS-TTS-Nano. + model->can_speaker_from_audio = cfg.has_encoder && + !codec_read_str_kv(model->gguf, "moss_audio_tokenizer.spk.encoder_hash", "").empty(); return CODEC_STATUS_SUCCESS; } @@ -848,6 +973,9 @@ const struct codec_model_vtable * codec_moss_audio_vtable() { codec_graph_size_exact, codec_moss_encode_wrap, codec_moss_decode_wrap, + nullptr, + codec_moss_speaker_validate, + codec_moss_speaker_from_audio, }; return &vtable; } diff --git a/src/runtime/graph.h b/src/runtime/graph.h index 8c2f001..1f34da4 100644 --- a/src/runtime/graph.h +++ b/src/runtime/graph.h @@ -52,6 +52,7 @@ enum codec_graph_kind { CODEC_GRAPH_POCKET_MIMI_ENCODE = 61, // Pocket-TTS Mimi-variant: PCM 24 kHz → latent [32,T] CODEC_GRAPH_POCKET_MIMI_SPEAKER = 68, // Pocket-TTS Mimi-variant: reference PCM (any rate) → voice latent CODEC_GRAPH_QWEN3_TTS_SPEAKER = 69, // Qwen3-TTS: reference PCM → x-vector + ICL reference codes + CODEC_GRAPH_MOSS_AUDIO_SPEAKER = 70, // MOSS-TTS-Nano: reference PCM (any rate) → reference codes CODEC_GRAPH_FLOW_LM_INPROJ = 62, // Pocket-TTS FlowLM: input_linear(bos_emb | teacher latent) CODEC_GRAPH_FLOW_LM_STEP = 63, // Pocket-TTS FlowLM: one AR frame (EOS + LSD flow + next input embd) From ffac80f24950f4a1f755ea58f9d68deb0fd530c9 Mon Sep 17 00:00:00 2001 From: Hans Date: Sat, 14 Nov 2026 19:36:42 +0800 Subject: [PATCH 04/11] feat(moss-tts-nano): codec_audio_lm family (tts-cli synthesize) The moss_tts_nano family builds the reference's voice-clone prompt (prompting.py): baked template token ids, the reference clip's codes as [user_slot, codes] embedding rows, the text normalized with the tokenizer's nmt_nfkc charsmap (src/lm/moss_tts_nano.cpp) and tokenized by the backbone's SPM vocab; without a voice, "None" stands in for the reference section. Per frame the depth decoder samples the text slot (assistant slot / audio end) and the 16 codes; the audio end stops before any code is drawn, as the reference breaks. Text above ~50 tokens is split at clauses (150 bytes) and joined with the reference's 0.24 s pause; max_frames defaults to 300. `codec.lm.audio_cb_offset` drops the text slot before decode. All-F32 greedy run on the zh voice-clone prompt (reference codes, PyTorch input ids): the first 34 frames (17 tokens each) equal PyTorch's greedy generate, then float noise flips a near-tie. The normalizer + llama.cpp tokenization equals SentencePiece on all 18 test texts. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 2 + common/audio_lm.cpp | 5 + common/audio_lm_family.cpp | 1 + common/audio_lm_family.h | 1 + common/audio_lm_family_moss_nano.cpp | 224 +++++++++++++++++++++++++++ src/lm/lm.cpp | 1 + src/lm/lm_internal.h | 4 + src/lm/lm_models.h | 32 ++++ src/lm/moss_tts_nano.cpp | 144 +++++++++++++++++ 9 files changed, 414 insertions(+) create mode 100644 common/audio_lm_family_moss_nano.cpp create mode 100644 src/lm/moss_tts_nano.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 15a4d07..c2452e3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -101,6 +101,7 @@ set(CODEC_SOURCES src/lm/residual_depth_ar.cpp src/lm/chatterbox_t3.cpp src/lm/cosyvoice_lm.cpp + src/lm/moss_tts_nano.cpp src/lm/speaker_chatterbox.cpp src/lm/speaker_qwen3_tts.cpp ) @@ -134,6 +135,7 @@ add_library(codec_audio_lm_objs OBJECT common/audio_lm_family_cosyvoice.cpp common/audio_lm_family_continuous.cpp common/audio_lm_family_flow.cpp + common/audio_lm_family_moss_nano.cpp common/tts_segment.cpp common/kitten_text.cpp ) diff --git a/common/audio_lm.cpp b/common/audio_lm.cpp index 1b5bd81..1228218 100644 --- a/common/audio_lm.cpp +++ b/common/audio_lm.cpp @@ -254,6 +254,11 @@ static void init_decode_transform(audio_lm_context * ctx) { const char * c0mod = meta_str(ctx, "codec.lm.residual.c0_input_modality"); ctx->audio_cb_offset = (c0mod && std::strcmp(c0mod, "text") == 0) ? 1 : 0; } + // Explicit count of leading text codebooks (MOSS-TTS-Nano's text slot, + // emitted by the depth decoder itself). + if (const char * v = meta_str(ctx, "codec.lm.audio_cb_offset")) { + ctx->audio_cb_offset = std::atoi(v); + } // MOSS-TTSD merged-cb0 remap: subtract speech_token_range[0] from cb0 // codes to map the merged text+speech vocab back into raw quantizer diff --git a/common/audio_lm_family.cpp b/common/audio_lm_family.cpp index 6f61a3a..db9e9ea 100644 --- a/common/audio_lm_family.cpp +++ b/common/audio_lm_family.cpp @@ -246,6 +246,7 @@ static std::unique_ptr make_family(audio_lm_context * alm, std::stri if (codec_lm_flow_get_info(lm) != nullptr) return alm_family_flow(alm, lm); if (codec_lm_chatterbox_get_info(lm) != nullptr) return alm_family_chatterbox(alm, lm); if (codec_lm_cosyvoice_get_info(lm) != nullptr) return alm_family_cosyvoice(alm, lm); + if (codec_lm_moss_nano_get_info(lm) != nullptr) return alm_family_moss_nano(alm, lm); audio_lm_prompt_info pi; if (codec_lm_chatterbox_get_info(lm) == nullptr && codec_lm_cosyvoice_get_info(lm) == nullptr && audio_lm_get_prompt_info(alm, &pi)) { diff --git a/common/audio_lm_family.h b/common/audio_lm_family.h index fe97ec9..6469838 100644 --- a/common/audio_lm_family.h +++ b/common/audio_lm_family.h @@ -245,6 +245,7 @@ std::unique_ptr alm_family_chatterbox(audio_lm_context * alm, struct std::unique_ptr alm_family_cosyvoice(audio_lm_context * alm, struct codec_lm * lm); std::unique_ptr alm_family_continuous(audio_lm_context * alm); std::unique_ptr alm_family_flow(audio_lm_context * alm, struct codec_lm * lm); +std::unique_ptr alm_family_moss_nano(audio_lm_context * alm, struct codec_lm * lm); } // namespace codec_common diff --git a/common/audio_lm_family_moss_nano.cpp b/common/audio_lm_family_moss_nano.cpp new file mode 100644 index 0000000..ef7dff3 --- /dev/null +++ b/common/audio_lm_family_moss_nano.cpp @@ -0,0 +1,224 @@ +// MOSS-TTS-Nano (codec_lm residual_depth_ar with a GPT-2 depth decoder): +// the global GPT-2 transformer is the backbone (llama.cpp starcoder2, its +// token_embd = wte), the codec_lm adaptor owns the local transformer, the +// audio embeddings and the 16 codebook heads. Reference: +// modeling_moss_tts_nano.py (build_inference_input_ids, _iter_generation_events) +// and prompting.py. +// +// Backbone sequence (voice clone; without a voice "None" stands in for the +// reference section): +// user_prefix <|audio_start|> [reference rows] <|audio_end|> after_reference +// text assistant_prefix <|audio_start|> +// Template spans are token ids baked by the converter; the text is normalized +// (nmt_nfkc) and tokenized with the backbone vocab. A reference row is the +// composed embedding of [user_slot, codes...]. Per frame the depth decoder +// reads the backbone hidden: codebook 0 (the text slot) is the assistant slot +// or the audio end, which stops the generation before any audio code is +// drawn; otherwise the 16 codes follow and the next backbone row is the +// composed [assistant_slot, codes...]. + +#include "audio_lm_family.h" +#include "lm/lm_models.h" + +#include +#include + +namespace codec_common { +namespace { + +class moss_nano_family : public alm_family { +public: + moss_nano_family(audio_lm_context * alm, codec_lm * lm, const codec_lm_moss_nano_info * mi) + : alm_family(alm), lm_(lm), mi_(mi) {} + const char * name() const override { return "moss_tts_nano"; } + + void caps(codec_audio_lm_caps * out) const override { + alm_family::caps(out); + const char * sr = audio_lm_meta_str(alm_, "codec.sample_rate"); + out->sample_rate = sr ? std::atoi(sr) : 48000; + } + + // voice_clone splits text above 50 tokens into sentence / clause chunks + // (_split_text_into_best_sentences); in bytes that is about 50 CJK + // characters' worth (kana are about one token each), and English packs well + // below 50 tokens at the same size. Chunks are joined with a 0.24 s pause + // (_concat_voice_clone_waveform_chunks, no trimming or fades). + split_params segment_split() const override { return {split_mode::clause, 150, 0}; } + join_params segment_join() const override { return {false, 0, 240}; } + + // Prompt: <__codec:user_prefix__><__codec:audio_start__><__voice__><__codec:audio_end__> + // <__codec:after_reference__><__codec:text__>{normalized text} + // <__codec:assistant_prefix__><__codec:audio_start__> + // (no voice: <__codec:no_reference__> in place of the reference section). + bool tts_format(const alm_tts_request & req, const alm_vocab & vocab, alm_format * out) override { + if (!vocab.valid()) return fail("this model needs the backbone vocabulary"); + std::string text; + if (req.text_known && !normalize(req.text, &text)) return false; + const bool voice = ref_codes(req.voice, nullptr, nullptr); + out->prompt = alm_codec_marker("user_prefix") + + (voice ? alm_codec_marker("audio_start") + CODEC_AUDIO_LM_MARKER_VOICE + alm_codec_marker("audio_end") + : alm_codec_marker("no_reference")) + + alm_codec_marker("after_reference") + alm_codec_marker("text") + text + + alm_codec_marker("assistant_prefix") + alm_codec_marker("audio_start"); + alm_completion & d = out->desc; + d.flow = CODEC_AUDIO_LM_FLOW_CODEC_HEAD; + d.n_embd = mi_->hidden_dim; + // One random stream for the text slot and the codebooks; the reference + // applies no repetition penalty (audio_repetition_penalty = 1). + d.head_groups = {alm_head_group{false, {}, {}}}; + d.needs_embeddings = true; + d.sample_first = false; + d.streamable = true; + d.max_frames = req.max_frames > 0 ? req.max_frames : 300; // inference(max_new_frames) + d.min_frames = std::max(0, req.min_frames); + return true; + } + + bool tts_build(const alm_tts_request & req, alm_prompt & prompt, const alm_vocab & vocab, alm_completion * out) override { + if (!vocab.valid()) return fail("this model needs the backbone vocabulary"); + hidden_ = mi_->hidden_dim; + n_cb_ = audio_lm_n_codebook(alm_); + if (n_cb_ != mi_->n_codebook) return fail("codebook count mismatch"); + frames_ = 0; + min_frames_ = std::max(0, req.min_frames); + stop_reason_ = "max_frames"; + audio_lm_set_uses_embed_override(alm_, true, 1); + + std::vector chunks; + std::vector toks; + auto ids = [&](const int32_t * p, int32_t n) { toks.insert(toks.end(), p, p + n); }; + auto flush = [&]() { + if (!toks.empty()) chunks.push_back(alm_chunk::of_tokens(std::move(toks))); + toks.clear(); + }; + if (!prompt.codec("user_prefix")) return fail("the prompt starts with <__codec:user_prefix__>"); + ids(mi_->user_prefix, mi_->n_user_prefix); + if (prompt.codec("audio_start")) { + toks.push_back(mi_->audio_start); + if (!prompt.voice()) return fail("<__codec:audio_start__> in the user turn must precede <__voice__>"); + const int32_t * codes = nullptr; + int32_t n_frames = 0; + if (!ref_codes(req.voice, &codes, &n_frames)) return fail("<__voice__> needs a voice with reference codes"); + flush(); + std::vector rows((size_t) n_frames * hidden_); + std::vector row((size_t) n_cb_); + for (int32_t t = 0; t < n_frames; ++t) { + row[0] = mi_->user_slot; + std::memcpy(row.data() + 1, codes + (size_t) t * (n_cb_ - 1), (size_t) (n_cb_ - 1) * sizeof(int32_t)); + if (!audio_lm_compose_audio_codes_embd(alm_, row.data(), n_cb_, rows.data() + (size_t) t * hidden_, hidden_)) { + return fail_alm("reference rows"); + } + } + chunks.push_back(alm_chunk::of_embd(std::move(rows), n_frames)); + if (!prompt.codec("audio_end")) return fail("<__voice__> must be followed by <__codec:audio_end__>"); + toks.push_back(mi_->audio_end); + } else if (prompt.codec("no_reference")) { + ids(mi_->no_reference, mi_->n_no_reference); + } else { + return fail("the user turn needs a reference section or <__codec:no_reference__>"); + } + if (!prompt.codec("after_reference")) return fail("missing <__codec:after_reference__>"); + ids(mi_->after_reference, mi_->n_after_reference); + if (!prompt.codec("text")) return fail("missing <__codec:text__>"); + const std::vector text = vocab.tokenize(prompt.text(), false, false); + if (text.empty()) return fail("empty text after tokenize"); + toks.insert(toks.end(), text.begin(), text.end()); + if (!prompt.codec("assistant_prefix") || !prompt.codec("audio_start") || !prompt.done()) { + return fail("the prompt ends with <__codec:assistant_prefix__><__codec:audio_start__>"); + } + ids(mi_->assistant_prefix, mi_->n_assistant_prefix); + toks.push_back(mi_->audio_start); + flush(); + codec_log(CODEC_LOG_LEVEL_INFO, "moss-tts-nano: %zu text tokens, prompt %zu chunks\n", text.size(), chunks.size()); + out->seqs = {std::move(chunks)}; + return true; + } + + bool observe(const int32_t *, const float * hiddens, codec_audio_lm_verdict * v) override { + if (hiddens == nullptr) return fail("observe needs the backbone hidden state"); + if (!audio_lm_step_begin(alm_, hiddens, hidden_)) return fail_alm("step"); + hidden_frame_.assign(hiddens, hiddens + hidden_); + cb_ = 0; + return next_head(v); + } + + const float * head_logits() const override { return logits_.data(); } + + bool head_token(int32_t id, codec_audio_lm_verdict * v) override { + if (id < 0 || id >= (int32_t) logits_.size()) return fail("head token out of range"); + if (cb_ >= n_cb_) return fail("no codebook is waiting for a token"); + if (cb_ == 0 && id == mi_->audio_end) { + // The reference breaks here: no audio codes for this frame. + stop_reason_ = "audio_end"; + codec_log(CODEC_LOG_LEVEL_INFO, "AR loop done: %d frames, stop=audio_end\n", frames_); + *v = {CODEC_AUDIO_LM_STOP, false, false, false, -1, 0, 0}; + return true; + } + if (!audio_lm_step_push_code(alm_, id)) return fail_alm("step"); + ++cb_; + return next_head(v); + } + + const float * next_embd(int32_t) const override { return audio_lm_get_next_embed(alm_, nullptr); } + +private: + bool next_head(codec_audio_lm_verdict * v) { + if (cb_ < n_cb_) { + int32_t idx = 0, n = 0; + const float * lg = audio_lm_step_logits(alm_, &idx, &n); + if (lg == nullptr) return fail_alm("step logits"); + logits_.assign(lg, lg + n); + if (cb_ == 0 && frames_ < min_frames_ && mi_->audio_end < n) { + logits_[(size_t) mi_->audio_end] = -INFINITY; // min_frames not reached + } + *v = {CODEC_AUDIO_LM_SAMPLE_HEAD, false, true, false, -1, 0, n}; + return true; + } + std::vector codes((size_t) n_cb_, 0); + if (!audio_lm_step_finish(alm_, codes.data(), n_cb_)) return fail_alm("step"); + // Accumulates the frame and composes the next backbone row (the sum of + // the 17 tables: wte[assistant_slot] + the codes' audio embeddings). + if (audio_lm_observe_codes(alm_, codes.data(), n_cb_, hidden_frame_.data(), hidden_) != OBSERVE_CONSUMED_EMBED) { + return fail_alm("frame"); + } + ++frames_; + *v = {CODEC_AUDIO_LM_FEED_EMBD, false, true, true, -1, 0, 0}; + return true; + } + + // The voice's reference codes: I32 [n_q, T] with n_q = n_codebook - 1. + bool ref_codes(const codec_speaker * spk, const int32_t ** codes, int32_t * n_frames) const { + codec_speaker_slot_type ty; + int64_t ne[4]; + const void * data = nullptr; + if (spk == nullptr || !codec_speaker_get_slot(spk, "ref_codes", &ty, ne, &data)) return false; + if (ty != CODEC_SPEAKER_SLOT_I32 || ne[0] != mi_->n_codebook - 1 || ne[1] < 1) return false; + if (codes) *codes = static_cast(data); + if (n_frames) *n_frames = (int32_t) ne[1]; + return true; + } + + bool normalize(const std::string & text, std::string * out) { + const int32_t n = codec_lm_moss_nano_normalize_text(lm_, text.c_str(), nullptr, 0); + if (n < 0) return fail("text normalization"); + out->assign((size_t) n + 1, '\0'); + codec_lm_moss_nano_normalize_text(lm_, text.c_str(), out->data(), n + 1); + out->resize((size_t) n); + return true; + } + + codec_lm * lm_; + const codec_lm_moss_nano_info * mi_; + std::vector hidden_frame_, logits_; + int32_t hidden_ = 0, n_cb_ = 0, cb_ = 0, frames_ = 0, min_frames_ = 0; +}; + +} // namespace + +std::unique_ptr alm_family_moss_nano(audio_lm_context * alm, struct codec_lm * lm) { + const codec_lm_moss_nano_info * mi = codec_lm_moss_nano_get_info(lm); + if (mi == nullptr) return nullptr; + return std::make_unique(alm, lm, mi); +} + +} // namespace codec_common diff --git a/src/lm/lm.cpp b/src/lm/lm.cpp index 1cddf0c..b5f9f66 100644 --- a/src/lm/lm.cpp +++ b/src/lm/lm.cpp @@ -396,6 +396,7 @@ void codec_lm_free(struct codec_lm * lm) { speaker_arch_free(lm); codec_lm_chatterbox_free_state(lm); codec_lm_cosyvoice_free_state(lm); + codec_lm_moss_nano_free_state(lm); if (lm->vtable != nullptr && lm->vtable->free != nullptr) { lm->vtable->free(lm); } diff --git a/src/lm/lm_internal.h b/src/lm/lm_internal.h index ec3cda9..87184f6 100644 --- a/src/lm/lm_internal.h +++ b/src/lm/lm_internal.h @@ -20,6 +20,8 @@ struct codec_lm_kind_vtable; void codec_lm_chatterbox_free_state(struct codec_lm * lm); // Free the lazily-created CosyVoice helper state (cosyvoice_lm.cpp). void codec_lm_cosyvoice_free_state(struct codec_lm * lm); +// Free the lazily-created MOSS-TTS-Nano helper state (moss_tts_nano.cpp). +void codec_lm_moss_nano_free_state(struct codec_lm * lm); struct codec_lm { // Borrowed; not freed by codec_lm_free. All weights and the @@ -39,6 +41,8 @@ struct codec_lm { // CosyVoice helper state (codec_lm_cosyvoice_*), created on first use. void * cosyvoice = nullptr; + // MOSS-TTS-Nano helper state (codec_lm_moss_nano_*), created on first use. + void * moss_nano = nullptr; // Speaker-conditioning encoder info, populated from `codec.speaker.*` // GGUF metadata at create time. `has_speaker_encoder = false` when diff --git a/src/lm/lm_models.h b/src/lm/lm_models.h index 04d8d0b..cc35995 100644 --- a/src/lm/lm_models.h +++ b/src/lm/lm_models.h @@ -233,6 +233,38 @@ enum codec_status codec_lm_flow_speaker_rows( int32_t out_cap_rows, int32_t * n_out); +// ─── MOSS-TTS-Nano prompt helpers (residual_depth_ar, gpt2 depth) ─── +// The backbone sequence (prompting.py, voice clone): +// user_prefix <|audio_start|> [reference rows] <|audio_end|> after_reference +// text assistant_prefix <|audio_start|> +// Template spans are token ids (each piece is SentencePiece-encoded on its +// own by the reference); a reference row is the composed embedding of +// [user_slot, codes...]; without a voice "None" (no_reference) stands in for +// <|audio_start|> rows <|audio_end|>. Each generated frame's row is +// [assistant_slot, codes...]; codebook 0 = audio_end stops the generation. +// Returns NULL when the model is not MOSS-TTS-Nano (no codec.lm.moss_tts_nano.*). +struct codec_lm_moss_nano_info { + int32_t hidden_dim; + int32_t n_codebook; // 17: the text slot + 16 RVQ codebooks + int32_t audio_start; + int32_t audio_end; // codebook-0 id that ends the generation + int32_t user_slot; // codebook 0 of reference rows + int32_t assistant_slot; // codebook 0 of generated rows + const int32_t * user_prefix; int32_t n_user_prefix; + const int32_t * no_reference; int32_t n_no_reference; + const int32_t * after_reference; int32_t n_after_reference; + const int32_t * assistant_prefix; int32_t n_assistant_prefix; + int32_t has_text_norm; // 1: codec_lm_moss_nano_normalize_text applies the charsmap +}; + +const struct codec_lm_moss_nano_info * codec_lm_moss_nano_get_info(struct codec_lm * lm); + +// The tokenizer's normalization (nmt_nfkc charsmap + remove_extra_whitespaces) +// of `text`, to tokenize with the backbone's SPM vocab. Writes it NUL-terminated +// to `out` when it fits `cap` bytes; returns its length (bytes, without the +// NUL), or -1 when the model is not MOSS-TTS-Nano. +int32_t codec_lm_moss_nano_normalize_text(struct codec_lm * lm, const char * text, char * out, int32_t cap); + #ifdef __cplusplus } #endif diff --git a/src/lm/moss_tts_nano.cpp b/src/lm/moss_tts_nano.cpp new file mode 100644 index 0000000..c2e7113 --- /dev/null +++ b/src/lm/moss_tts_nano.cpp @@ -0,0 +1,144 @@ +// MOSS-TTS-Nano prompt helpers (lm_models.h): the prompt template's token ids +// and the tokenizer's text normalizer, from `codec.lm.moss_tts_nano.*`. +// +// The reference tokenizer is SentencePiece BPE with the nmt_nfkc normalizer +// (precompiled charsmap) and remove_extra_whitespaces. llama.cpp's SPM vocab +// has no normalizer, so the family normalizes the text first; llama.cpp then +// adds the space prefix and merges like SentencePiece. + +#include "lm_internal.h" + +#include "../runtime/gguf_kv.h" + +#include +#include +#include + +namespace { + +struct moss_nano_state { + codec_lm_moss_nano_info info = {}; + std::vector user_prefix, no_reference, after_reference, assistant_prefix; + std::vector charsmap; + const uint32_t * xcda = nullptr; // XOR-compressed double array (SentencePiece's darts) + size_t n_xcda = 0; + const char * repl = nullptr; // NUL-terminated replacement strings + size_t n_repl = 0; +}; + +// The darts lookup of SentencePiece's precompiled charsmap (as llama.cpp's UGM +// tokenizer reads it): the longest input prefix with a replacement. +struct xcda_view { + const uint32_t * a; size_t n; + uint32_t node(size_t i) const { return i < n ? a[i] : 0; } + uint32_t base(size_t i) const { const uint32_t p = node(i); return (p >> 10) << ((p & (1u << 9)) >> 6); } + uint32_t lcheck(size_t i) const { return node(i) & ((1u << 31) | 0xff); } + bool leaf(size_t i) const { return (node(i) >> 8) & 1; } + uint32_t value(size_t i) const { return node(i) & ((1u << 31) - 1); } +}; + +size_t utf8_len(unsigned char c) { + return c < 0x80 ? 1 : (c >> 5) == 0x6 ? 2 : (c >> 4) == 0xe ? 3 : (c >> 3) == 0x1e ? 4 : 1; +} + +moss_nano_state * get_state(codec_lm * lm) { + if (lm == nullptr || lm->codec == nullptr || lm->codec->gguf == nullptr) return nullptr; + if (lm->moss_nano != nullptr) return static_cast(lm->moss_nano); + gguf_context * gf = lm->codec->gguf; + if (gguf_find_key(gf, "codec.lm.moss_tts_nano.user_prefix") < 0) return nullptr; + auto * s = new moss_nano_state(); + codec_read_i32_array_kv_vec(gf, "codec.lm.moss_tts_nano.user_prefix", &s->user_prefix); + codec_read_i32_array_kv_vec(gf, "codec.lm.moss_tts_nano.no_reference", &s->no_reference); + codec_read_i32_array_kv_vec(gf, "codec.lm.moss_tts_nano.after_reference", &s->after_reference); + codec_read_i32_array_kv_vec(gf, "codec.lm.moss_tts_nano.assistant_prefix", &s->assistant_prefix); + const int64_t kc = gguf_find_key(gf, "codec.lm.moss_tts_nano.text_norm_charsmap"); + if (kc >= 0 && gguf_get_kv_type(gf, kc) == GGUF_TYPE_ARRAY && + (gguf_get_arr_type(gf, kc) == GGUF_TYPE_UINT8 || gguf_get_arr_type(gf, kc) == GGUF_TYPE_INT8)) { + const auto * p = static_cast(gguf_get_arr_data(gf, kc)); + s->charsmap.assign(p, p + gguf_get_arr_n(gf, kc)); + uint32_t blob = 0; + if (s->charsmap.size() > 4) std::memcpy(&blob, s->charsmap.data(), 4); // little-endian, as written + if (blob > 0 && (size_t) blob + 4 < s->charsmap.size()) { + s->xcda = reinterpret_cast(s->charsmap.data() + 4); + s->n_xcda = blob / 4; + s->repl = reinterpret_cast(s->charsmap.data() + 4 + blob); + s->n_repl = s->charsmap.size() - 4 - blob; + } + } + codec_lm_moss_nano_info & i = s->info; + i.hidden_dim = lm->info.hidden_dim; + i.n_codebook = lm->info.n_codebook; + i.audio_start = codec_read_i32_kv(gf, "codec.lm.moss_tts_nano.audio_start", -1); + i.audio_end = codec_read_i32_kv(gf, "codec.lm.moss_tts_nano.audio_end", -1); + i.user_slot = codec_read_i32_kv(gf, "codec.lm.moss_tts_nano.audio_user_slot", -1); + i.assistant_slot = codec_read_i32_kv(gf, "codec.lm.moss_tts_nano.audio_assistant_slot", -1); + i.user_prefix = s->user_prefix.data(); i.n_user_prefix = (int32_t) s->user_prefix.size(); + i.no_reference = s->no_reference.data(); i.n_no_reference = (int32_t) s->no_reference.size(); + i.after_reference = s->after_reference.data(); i.n_after_reference = (int32_t) s->after_reference.size(); + i.assistant_prefix = s->assistant_prefix.data(); i.n_assistant_prefix = (int32_t) s->assistant_prefix.size(); + i.has_text_norm = s->xcda != nullptr ? 1 : 0; + lm->moss_nano = s; + return s; +} + +} // namespace + +void codec_lm_moss_nano_free_state(struct codec_lm * lm) { + if (lm == nullptr || lm->moss_nano == nullptr) return; + delete static_cast(lm->moss_nano); + lm->moss_nano = nullptr; +} + +const struct codec_lm_moss_nano_info * codec_lm_moss_nano_get_info(struct codec_lm * lm) { + moss_nano_state * s = get_state(lm); + return s != nullptr ? &s->info : nullptr; +} + +int32_t codec_lm_moss_nano_normalize_text(struct codec_lm * lm, const char * text, char * out, int32_t cap) { + moss_nano_state * s = get_state(lm); + if (s == nullptr || text == nullptr) return -1; + // 1. charsmap (NFKC + the NMT rules: control characters dropped, every + // whitespace character to ' '), longest match first; other UTF-8 + // characters pass through. + const std::string in(text); + std::string norm; + norm.reserve(in.size()); + const xcda_view xv{s->xcda, s->n_xcda}; + for (size_t off = 0; off < in.size();) { + size_t best_len = 0, best_off = 0; + if (s->xcda != nullptr) { + uint32_t node = xv.base(0); + for (size_t p = off; p < in.size(); ++p) { + const unsigned char c = (unsigned char) in[p]; + if (c == 0) break; + node ^= c; + if (xv.lcheck(node) != c) break; + const bool leaf = xv.leaf(node); + node ^= xv.base(node); + if (leaf) { best_len = p - off + 1; best_off = xv.value(node); } + } + } + if (best_len > 0 && best_off < s->n_repl) { + norm += std::string(s->repl + best_off, strnlen(s->repl + best_off, s->n_repl - best_off)); + off += best_len; + } else { + const size_t n = std::min(utf8_len((unsigned char) in[off]), in.size() - off); + norm.append(in, off, n); + off += n; + } + } + // 2. remove_extra_whitespaces: no leading / trailing spaces, runs to one. + std::string res; + res.reserve(norm.size()); + for (char c : norm) { + if (c == ' ' && (res.empty() || res.back() == ' ')) continue; + res.push_back(c); + } + while (!res.empty() && res.back() == ' ') res.pop_back(); + const int32_t n = (int32_t) res.size(); + if (out != nullptr && cap > n) { + std::memcpy(out, res.data(), (size_t) n); + out[n] = '\0'; + } + return n; +} From 5878ea97ad529392a3d830b3927125a514cca954 Mon Sep 17 00:00:00 2001 From: Hans Date: Sat, 14 Nov 2026 20:00:06 +0800 Subject: [PATCH 05/11] feat(moss-tts-nano): the text slot is drawn model-side, like a stop head The reference samples the text slot (assistant slot vs audio end) at its own temperature 1.5 / top_p 1, the codebooks at 1.7 / top_k 25 / top_p 0.8. A host applies one setting to every codec-side head, and under the codebooks' top_p the audio end cannot be drawn while its probability is below 0.2: generations ran on past the text (ja up to 2.5x the reference's length). The family now draws the slot from its two logits at codec.lm.moss_tts_nano.text_temperature (1.5, written by the converter; <= 0 = argmax) with its own stream seeded by codec_audio_lm_set_seed, and hands the host a one-hot head. Durations now match the reference's. Co-Authored-By: Claude Opus 5.5 --- common/audio_lm_family_moss_nano.cpp | 39 +++++++++++++++++-- .../converters/lm_adaptor/moss_tts_local.py | 3 ++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/common/audio_lm_family_moss_nano.cpp b/common/audio_lm_family_moss_nano.cpp index ef7dff3..fb9efed 100644 --- a/common/audio_lm_family_moss_nano.cpp +++ b/common/audio_lm_family_moss_nano.cpp @@ -21,7 +21,9 @@ #include "lm/lm_models.h" #include +#include #include +#include namespace codec_common { namespace { @@ -81,6 +83,7 @@ class moss_nano_family : public alm_family { if (n_cb_ != mi_->n_codebook) return fail("codebook count mismatch"); frames_ = 0; min_frames_ = std::max(0, req.min_frames); + set_seed(CODEC_AUDIO_LM_DEFAULT_SEED); // random unless the host sets one (codec_audio_lm_set_seed) stop_reason_ = "max_frames"; audio_lm_set_uses_embed_override(alm_, true, 1); @@ -161,6 +164,8 @@ class moss_nano_family : public alm_family { const float * next_embd(int32_t) const override { return audio_lm_get_next_embed(alm_, nullptr); } + void set_seed(uint32_t seed) override { rng_.seed(alm_resolve_seed(seed)); } + private: bool next_head(codec_audio_lm_verdict * v) { if (cb_ < n_cb_) { @@ -168,9 +173,7 @@ class moss_nano_family : public alm_family { const float * lg = audio_lm_step_logits(alm_, &idx, &n); if (lg == nullptr) return fail_alm("step logits"); logits_.assign(lg, lg + n); - if (cb_ == 0 && frames_ < min_frames_ && mi_->audio_end < n) { - logits_[(size_t) mi_->audio_end] = -INFINITY; // min_frames not reached - } + if (cb_ == 0) decide_text_slot(); *v = {CODEC_AUDIO_LM_SAMPLE_HEAD, false, true, false, -1, 0, n}; return true; } @@ -186,6 +189,35 @@ class moss_nano_family : public alm_family { return true; } + // The text slot is the stop decision: the reference samples it between the + // assistant slot and the audio end at its own temperature (1.5, top_p 1), + // apart from the codebooks' settings (1.7 / top_k 25 / top_p 0.8) the host + // applies to every head; under those, the end could not be drawn below + // p = 0.2 and generations ran on. So the model draws it here, like a stop + // head, with its own seeded stream, and hands the host a one-hot head. + // codec.lm.moss_tts_nano.text_temperature <= 0: argmax (greedy). + void decide_text_slot() { + const int32_t n = (int32_t) logits_.size(), end = mi_->audio_end, slot = mi_->assistant_slot; + if (end < 0 || end >= n || slot < 0 || slot >= n) return; + bool stop; + if (frames_ < min_frames_) { + stop = false; // min_frames not reached + } else { + const char * tv = audio_lm_meta_str(alm_, "codec.lm.moss_tts_nano.text_temperature"); + const float temp = tv ? std::strtof(tv, nullptr) : 1.5f; + const float d = logits_[(size_t) end] - logits_[(size_t) slot]; + if (temp <= 0.0f) { + stop = d > 0.0f; + } else { + const double p_end = 1.0 / (1.0 + std::exp(-(double) d / temp)); + stop = std::uniform_real_distribution(0.0, 1.0)(rng_) < p_end; + } + } + for (int32_t i = 0; i < n; ++i) { + if (i != (stop ? end : slot)) logits_[(size_t) i] = -INFINITY; + } + } + // The voice's reference codes: I32 [n_q, T] with n_q = n_codebook - 1. bool ref_codes(const codec_speaker * spk, const int32_t ** codes, int32_t * n_frames) const { codec_speaker_slot_type ty; @@ -210,6 +242,7 @@ class moss_nano_family : public alm_family { codec_lm * lm_; const codec_lm_moss_nano_info * mi_; std::vector hidden_frame_, logits_; + std::mt19937 rng_; int32_t hidden_ = 0, n_cb_ = 0, cb_ = 0, frames_ = 0, min_frames_ = 0; }; diff --git a/scripts/converters/lm_adaptor/moss_tts_local.py b/scripts/converters/lm_adaptor/moss_tts_local.py index e30308e..c251493 100644 --- a/scripts/converters/lm_adaptor/moss_tts_local.py +++ b/scripts/converters/lm_adaptor/moss_tts_local.py @@ -411,6 +411,9 @@ def _dump_nano(writer, sd, cfg, *, verbose: bool) -> None: for k in ("audio_start", "audio_end", "audio_user_slot", "audio_assistant_slot"): writer.add_uint32(pre + k, ids[k]) writer.add_uint32(pre + "audio_pad", pad) + # inference(text_temperature): the text slot (the stop decision) is drawn at + # its own temperature, model-side (the family); <= 0 = argmax. + writer.add_float32(pre + "text_temperature", 1.5) m = spm_pb2.ModelProto() m.ParseFromString(tok_path.read_bytes()) ns = m.normalizer_spec From e2438987e53ac408941660de31a25309481eae2a Mon Sep 17 00:00:00 2001 From: Hans Date: Sat, 14 Nov 2026 20:00:06 +0800 Subject: [PATCH 06/11] test(moss-tts-nano): E2E smoke, tts-cli and Python-host cases tests/e2e/moss_tts_nano_smoke.py drives codec_cpp: the voice's ref_codes shape, voice-clone synthesis of an English and a Chinese sentence (stop on the audio end, 48 kHz, duration, level, Whisper CER), and with MOSS_TTS_NANO_SRC (+ MOSS_AUDIO_TOKENIZER_SRC) the PyTorch parity of the depth decoder's frame 0 (17/17 argmax, max |d| 0.04) and of the voice codes. ttscli_synthesize_smoke and python_tts_smoke gain a moss_tts_nano case (the Python host matches tts-cli to 1 LSB). Co-Authored-By: Claude Opus 5.5 --- tests/e2e/moss_tts_nano_smoke.py | 173 +++++++++++++++++++++++++++ tests/e2e/python_tts_smoke.py | 3 + tests/e2e/ttscli_synthesize_smoke.py | 15 +++ 3 files changed, 191 insertions(+) create mode 100644 tests/e2e/moss_tts_nano_smoke.py diff --git a/tests/e2e/moss_tts_nano_smoke.py b/tests/e2e/moss_tts_nano_smoke.py new file mode 100644 index 0000000..4f30c3e --- /dev/null +++ b/tests/e2e/moss_tts_nano_smoke.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""E2E smoke for MOSS-TTS-Nano-100M: voice-clone synthesis through codec_cpp. + +Assets (missing → skip): + models/moss_tts_nano/moss_tts_nano_codec.gguf codec + LM adaptor + scripts/convert-to-gguf.py --checkpoint-path + --lm-source --quantization Q8_0 --lm-outtype BF16 + models/moss_tts_nano/backbone-bf16.gguf the global transformer (starcoder2) + scripts/convert-backbone-to-gguf.py --model-id --outtype bf16 + +Checks: + 1. The voice: codec_speaker_from_audio gives ref_codes I32 [16, floor(n48 / 3840)]. + 2. Synthesis (codec_cpp.TTS, the bundled llama.cpp backbone, fixed seeds) of + an English and a Chinese sentence in the cloned JFK voice: stops on the + text slot's audio end, 48 kHz, plausible duration, not silent; the Whisper + CER (when transformers + whisper are available) stays under a loose bound. + 3. With MOSS_TTS_NANO_SRC= and torch: teacher-forced + frame 0 of the depth decoder on PyTorch's backbone hidden (all 17 + argmaxes equal, logits close) and the voice codes vs the reference's + batch_encode (MOSS_AUDIO_TOKENIZER_SRC=; >= 90% equal with + models/moss_tts_nano/moss_tts_nano_codec-f32.gguf, reported otherwise). + +Run from the repo root: .venv/bin/python tests/e2e/moss_tts_nano_smoke.py +""" + +import os +import sys +from pathlib import Path + +import numpy as np + +REPO = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(REPO / "python")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import codec_cpp # noqa: E402 +from _common import asr_cer, read_wav_mono_f32 # noqa: E402 + +M = REPO / "models" / "moss_tts_nano" +CODEC = M / "moss_tts_nano_codec.gguf" +BACKBONE = M / "backbone-bf16.gguf" +CODEC_F32 = M / "moss_tts_nano_codec-f32.gguf" # optional: F32 codec part (--outtype F32) for the voice parity +REF_WAV = REPO / "assets" / "refs" / "jfk_en.wav" + +CASES = [ # name, text, lang, seed, CER bound (sampled; the reference varies as much from seed to seed) + ("en", "The birch canoe slid on the smooth planks.", "en", 3, 0.35), + ("zh", "你也可以咨询除贵国以外其他政府的建议。", "zh", 3, 0.35), +] + + +def check_voice(model) -> bool: + x, sr = read_wav_mono_f32(REF_WAV) + spk = codec_cpp.Context(model).speaker_from_audio(x, sr) + rc = spk.slot("ref_codes") + n48 = (len(x) * 48000 + sr - 1) // sr + want_t = n48 // 3840 + ok = rc is not None and rc.dtype == np.int32 and rc.size == 16 * want_t and \ + int(rc.min()) >= 0 and int(rc.max()) < 1024 + print(f"[{'PASS' if ok else 'FAIL'}] voice: ref_codes {None if rc is None else rc.shape} (want 16 x {want_t})") + return ok + + +def check_synth() -> bool: + ok_all = True + with codec_cpp.TTS(BACKBONE, CODEC) as tts: + for name, text, lang, seed, cer_max in CASES: + audio, sr = tts.synthesize(text, ref_audio=REF_WAV, seed=seed) + stop = tts.last_result["stop_reason"] + a = audio if audio.ndim == 1 else audio.mean(axis=1) + dur, rms = len(a) / sr, float(np.sqrt((a ** 2).mean())) + ok = stop == "audio_end" and sr == 48000 and 0.8 <= dur <= 15.0 and rms > 0.005 + msg = f"stop={stop} sr={sr} dur={dur:.2f}s rms={rms:.3f}" + out = Path("/tmp") / f"moss_tts_nano_{name}.wav" + import wave + with wave.open(str(out), "wb") as w: + w.setnchannels(1); w.setsampwidth(2); w.setframerate(sr) + w.writeframes((np.clip(a, -1, 1) * 32767).astype(" bool | None: + if CODEC_F32.exists(): + model = codec_cpp.Model(CODEC_F32, n_threads=8) + src = os.environ.get("MOSS_TTS_NANO_SRC") + if not src: + print("[skip] parity: set MOSS_TTS_NANO_SRC to the HF checkpoint dir") + return None + try: + import torch + import torchaudio + from transformers import AutoConfig, AutoModelForCausalLM + except Exception as e: # noqa: BLE001 + print(f"[skip] parity: {e}") + return None + import soundfile as sf + torchaudio.load = lambda p, *a, **k: (lambda x: (torch.from_numpy(x[0].T.copy()), x[1]))( + sf.read(str(p), dtype="float32", always_2d=True)) + cfg = AutoConfig.from_pretrained(src, trust_remote_code=True) + cfg.attn_implementation = "sdpa" + cfg.local_transformer_attn_implementation = "sdpa" + ref = AutoModelForCausalLM.from_pretrained(src, config=cfg, trust_remote_code=True, dtype=torch.float32).eval() + tok = ref._load_text_tokenizer(text_tokenizer_path=src) + ok = True + codec_src = os.environ.get("MOSS_AUDIO_TOKENIZER_SRC") + x, sr = read_wav_mono_f32(REF_WAV) + if codec_src: + at = ref._load_audio_tokenizer(audio_tokenizer_pretrained_name_or_path=codec_src, device="cpu") + wav, s = ref._load_reference_audio(REF_WAV, ref._resolve_audio_tokenizer_sample_rate(at), + ref._resolve_audio_tokenizer_channels(at)) + with torch.no_grad(): + codes = ref._normalize_audio_codes(ref._call_audio_encode(at, wav, s)).numpy() + got = codec_cpp.Context(model).speaker_from_audio(x, sr).slot("ref_codes").reshape(-1, 16) + n = min(len(got), len(codes)) + frac = float((got[:n] == codes[:n]).mean()) + # Exact up to deep-RVQ near ties with an F32 codec part; a quantized + # encoder (the Q8_0 release GGUF) only reports. + strict = model is not None and CODEC_F32.exists() + good = len(got) == len(codes) and (frac >= 0.90 or not strict) + print(f"[{'PASS' if good else 'FAIL'}] parity_voice: {len(got)} vs {len(codes)} frames, {frac:.1%} codes equal" + f"{'' if strict else ' (quantized encoder: reported only)'}") + ok &= good + else: + codes = np.zeros((20, 16), np.int64) # any reference rows exercise the prompt + ids, mask = ref.build_inference_input_ids(text=CASES[0][1], text_tokenizer=tok, mode="voice_clone", + prompt_audio_codes=torch.from_numpy(codes).long(), device="cpu") + with torch.no_grad(): + h = ref.transformer(inputs_embeds=ref._build_inputs_embeds(ids), attention_mask=mask).last_hidden_state[:, -1] + lt = ref.local_transformer + seq = h.unsqueeze(1) + st = codec_cpp.LM(model).state() + st.step_begin(h[0].numpy()) + worst, agree = 0.0, 0 + for k in range(17): # teacher-forced on PyTorch's picks + out = lt(inputs_embeds=seq, attention_mask=torch.ones(seq.shape[:2], dtype=torch.bool)).last_hidden_state[:, -1] + _, g = st.step_logits() + if k == 0: # the text slot: assistant slot vs audio end + pair = [cfg.audio_assistant_slot_token_id, cfg.audio_end_token_id] + r, g = ref.text_lm_head(out)[0, pair].numpy(), g[pair] + code = cfg.audio_assistant_slot_token_id + nxt = ref.transformer.wte(torch.tensor([code])) + else: + r = ref.audio_lm_heads[k - 1](out)[0].numpy() + code = int(r.argmax()) + nxt = ref.audio_embeddings[k - 1](torch.tensor([code])) + agree += int(np.argmax(g) == np.argmax(r)) + worst = max(worst, float(np.abs(g - r).max())) + st.step_push_code(code) + seq = torch.cat([seq, nxt.unsqueeze(1)], dim=1) + good = agree == 17 and worst < 0.25 + print(f"[{'PASS' if good else 'FAIL'}] parity_depth: {agree}/17 argmax equal, logits max|d| {worst:.3f}") + return ok and good + + +def main() -> int: + if not CODEC.exists() or not BACKBONE.exists(): + print(f"[skip] moss_tts_nano: missing {CODEC.name} / {BACKBONE.name} in {M}") + return 0 + model = codec_cpp.Model(CODEC, n_threads=8) + results = [check_voice(model), check_synth(), check_parity(model)] + ran = [r for r in results if r is not None] + print("OK" if all(ran) else "FAILED") + return 0 if all(ran) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/e2e/python_tts_smoke.py b/tests/e2e/python_tts_smoke.py index e372c6f..33974f3 100644 --- a/tests/e2e/python_tts_smoke.py +++ b/tests/e2e/python_tts_smoke.py @@ -59,6 +59,9 @@ def _case(name, codec, backbone, text, card, seed, cli=(), opts=None, max_frames "The birch canoe slid on the smooth planks.", "outetts_1_0", 1), _case("soprano", M / "soprano/soprano.gguf", M / "soprano/backbone-f16.gguf", "The birch canoe slid on the smooth planks.", "soprano", 42), + _case("moss_tts_nano", M / "moss_tts_nano/moss_tts_nano_codec.gguf", M / "moss_tts_nano/backbone-bf16.gguf", + "The birch canoe slid on the smooth planks.", "moss_tts_nano", 3, + ["--ref-audio", str(REF / "jfk_en.wav")], dict(ref_audio=REF / "jfk_en.wav")), _case("pocket_tts", M / "pocket_tts/pocket_tts_en.gguf", M / "pocket_tts/backbone-f16.gguf", "Hello world. This is a small text to speech model.", "pocket_tts", 11, ["--max-frames", "80", "--min-len", "24", "--ref-audio", str(REF / "jfk_en.wav")], # needs a voice diff --git a/tests/e2e/ttscli_synthesize_smoke.py b/tests/e2e/ttscli_synthesize_smoke.py index 4abc08d..686152f 100644 --- a/tests/e2e/ttscli_synthesize_smoke.py +++ b/tests/e2e/ttscli_synthesize_smoke.py @@ -408,6 +408,21 @@ def main(): greedy=False, stop_line="pocket AR done", )) + # MOSS-TTS-Nano-100M: GPT-2 + RoPE global transformer as stock starcoder2, + # a 1-layer GPT-2 depth decoder (codec_lm residual_depth_ar, gpt2 block) + # for the text slot + 16 RVQ codes, MOSS-Audio-Tokenizer-Nano at 48 kHz. + # Voice clone from the reference clip's codes; the text slot's audio end + # stops it. Sampled (the reference's settings); seed pinned. + results.append(_case( + "moss_tts_nano", + REPO / "models" / "moss_tts_nano" / "moss_tts_nano_codec.gguf", + REPO / "models" / "moss_tts_nano" / "backbone-bf16.gguf", + "The birch canoe slid on the smooth planks.", + "en", want_stop="audio_end", cer_max=0.35, + extra=["--seed", "3", "--ref-audio", str(REPO / "assets" / "refs" / "jfk_en.wav")], + greedy=False, + )) + # Soprano: Qwen3 backbone (tokenizer.ggml.pre = soprano) whose final-norm # hidden states feed the Vocos decoder directly; greedy, stops on [STOP]. results.append(_case( From 8e93ce80472cc06c30d375214e92e81dab03dc7c Mon Sep 17 00:00:00 2001 From: Hans Date: Sat, 14 Nov 2026 20:18:30 +0800 Subject: [PATCH 07/11] =?UTF-8?q?docs(moss-tts-nano):=20model=20notes,=20p?= =?UTF-8?q?arity=20and=20read-back=20results;=20status=20=E2=9C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/models/moss_tts_nano.md: conversion, the backbone / depth decoder / codec split, the prompt and frame loop, the voice, the model-side text slot draw, stage parity vs PyTorch, and the multi-seed read-back (zh / ja / en / zh in an en voice) next to the reference's on the same seeds, with host RTF. codec_lm.md documents the gpt2 depth block and the new residual_depth_ar keys; codec_common_api.md, codec_speaker.md and model_status.md gain the model's rows. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/codec_common_api.md | 2 + docs/codec_lm.md | 18 ++++ docs/codec_speaker.md | 1 + docs/model_status.md | 2 +- docs/models/moss_tts_nano.md | 154 +++++++++++++++++++++++++++++++++++ 6 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 docs/models/moss_tts_nano.md diff --git a/docs/README.md b/docs/README.md index 0535823..6ca3838 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,6 +5,7 @@ - [chatterbox.md](models/chatterbox.md): Chatterbox, Chatterbox Multilingual, Chatterbox Turbo - [cosyvoice.md](models/cosyvoice.md): CosyVoice-300M, BreezyVoice, CosyVoice2, CosyVoice3 - [kitten_tts2.md](models/kitten_tts2.md): KittenTTS 2 + - [moss_tts_nano.md](models/moss_tts_nano.md): MOSS-TTS-Nano-100M - Design and API: - [codec_lm.md](codec_lm.md): the LM adaptor (`codec_lm`) between a llama.cpp backbone and a codec - [codec_common_api.md](codec_common_api.md): `codec_audio_lm`, the audio-LM inference API a llama.cpp host drives, its model families, and the ready-made hosts (tts-cli, tts-server, Python) diff --git a/docs/codec_common_api.md b/docs/codec_common_api.md index a70a897..2652394 100644 --- a/docs/codec_common_api.md +++ b/docs/codec_common_api.md @@ -113,6 +113,7 @@ format only applies the model's deterministic normalization. | CSM, MOSS-TTSD | `[<__voice__>]{prefix}{text}{suffix}` (MOSS-TTSD: `[S1]` → ``) | | Qwen3-TTS | `[<\|im_start\|>user\n{instruct}<\|im_end\|>\n]<\|im_start\|>assistant\n<__voice__>[{reference transcript}]<__codec:text__>{text}` | | MOSS-TTS-Realtime | `{the GGUF's context}<__codec:text__>{text}` | +| MOSS-TTS-Nano | `<__codec:user_prefix__><__codec:audio_start__><__voice__><__codec:audio_end__><__codec:after_reference__><__codec:text__>{nmt_nfkc text}<__codec:assistant_prefix__><__codec:audio_start__>` (no voice: `<__codec:no_reference__>` for the reference section; template spans are baked token ids) | | Chatterbox | `<__voice__>{punc_norm'd text}` (T3: ' ' as `[SPACE]`) | | CosyVoice | `<__codec:sos__>[<__voice__> (v1 x-vector)]{prompt text}<__codec:text__>{text}<__codec:task__>[<__voice__> (zero-shot reference tokens)]` | @@ -251,6 +252,7 @@ A family that needs something else entirely can still override both. |---|---|---|---| | `codebook` | CSM, Qwen3-TTS, MOSS-TTSD | CODEC_HEAD | depth decoder or delayed parallel heads; MOSS-TTSD samples codebook 0 from the backbone under a grammar | | `realtime` | MOSS-TTS-Realtime | CODEC_HEAD | text lane from the backbone's embedding table (`params.backbone_path`) | +| `moss_tts_nano` | MOSS-TTS-Nano | CODEC_HEAD | starcoder2 backbone; reference codes as voice rows; the depth decoder's text slot (drawn model-side) stops it | | `lfm2` | LFM2-Audio | CODEC_HEAD | text warm-up from the tied embedding head (`verdict.token`), then audio frames | | `chatterbox` | Chatterbox T3, Turbo, Multilingual | CODEC_HEAD | guidance pair (`n_seq` 2) for T3 | | `cosyvoice` | CosyVoice 1/2/3, BreezyVoice | CODEC_HEAD | SFT / zero-shot / cross-lingual / instruct modes; v1 disables flash attention | diff --git a/docs/codec_lm.md b/docs/codec_lm.md index a787b39..02e2e59 100644 --- a/docs/codec_lm.md +++ b/docs/codec_lm.md @@ -144,6 +144,15 @@ encoded via `codebook_sizes[0] = text_vocab` and `c0_input_modality = "text"` metadata — and a dual-stream backbone audio embed split (user + model) that the caller composes outside codec_lm. +MOSS-TTS-Realtime and MOSS-TTS-Nano fit with `depth_emits_c0` (no c0_head: +the depth decoder's position 0 reads the backbone hidden and emits codebook 0 +too). Nano's depth decoder is a GPT-2 block (`codec.lm.depth.arch = "gpt2"`: +LayerNorm with shift, biased q/k/v/o, gelu_new FFN, interleaved RoPE) whose +codebook 0 is a text slot: the depth decoder chooses the assistant slot or the +audio end (`codec.lm.cb0_allowed`), with heads tied to the input tables +(`heads_tied_to_embd`); `codec.lm.audio_cb_offset = 1` drops the slot before +the codec decodes. + LFM2-Audio is conjectured to fit `shared` based on the published config (depthformer = 6 layers, dim 1024, tied embeds), but the actual modeling code is not in HF transformers; tensor names are pending a @@ -187,6 +196,11 @@ codec.lm.residual.depth_has_qk_norm: bool # Qwen3-style per-head RMSN codec.lm.residual.depth_has_in_proj: bool # true → lm.depth.in_proj.weight present codec.lm.residual.weight_layout: string # "shared" / "flexible" codec.lm.residual.c0_input_modality: string # "audio" / "text" — Moshi has "text" +codec.lm.residual.depth_emits_c0: bool # no c0_head; depth position 0 emits codebook 0 +codec.lm.residual.heads_tied_to_embd: bool # depth head i = input table i (no lm.depth.heads_*) +codec.lm.depth.arch: string # block: "llama" family (default) / "gpt2" +codec.lm.cb0_allowed: array # the only codebook-0 ids ever sampled (optional) +codec.lm.audio_cb_offset: i32 # leading non-audio codebooks dropped before decode ``` @@ -229,6 +243,10 @@ lm.depth.blk_{l}.ffn_down.weight # mlp.down_proj lm.depth.output_norm.weight # final RMSNorm ``` +`codec.lm.depth.arch = "gpt2"` blocks have no `ffn_gate` (`ffn_up` → gelu_new +→ `ffn_down`) and add a `.bias` to `attn_norm`, `q`, `k`, `v`, `o`, +`ffn_norm`, `ffn_up`, `ffn_down` and `output_norm` (LayerNorms with shift). + For `weight_layout = "flexible"` (Moshi), every `lm.depth.blk_{l}.*` weight gains a leading dimension `[n_codebook, ...]`; the runtime gathers slice `step_idx` per depth step. `ffn_gate` and `ffn_up` may be fused into diff --git a/docs/codec_speaker.md b/docs/codec_speaker.md index 4bd7a91..f0daae6 100644 --- a/docs/codec_speaker.md +++ b/docs/codec_speaker.md @@ -111,6 +111,7 @@ model, so a speaker may hold that backbone's token ids. | Pocket-Mimi | `latents` F32 [T, 32] (Mimi encoder latent of the first 30 s; the FlowLM applies `speaker_proj`) | Pocket-TTS ([pocket_tts.md](models/pocket_tts.md)) | | Qwen3-TTS-Tokenizer | `spk_id` I32 [1] (talker codec-vocab row used as the speaker row) + optional `language_id` I32 [1] (dialect tag) | Qwen3-TTS CustomVoice ([qwen3_tts.md](models/qwen3_tts.md)) | | Qwen3-TTS-Tokenizer + ECAPA-TDNN | `xvector` F32 [hidden] (speaker row) + `ref_codes` I32 [16, T] + `ref_text` (in-context prompt) | Qwen3-TTS Base, cloned | +| MOSS-Audio-Tokenizer-Nano | `ref_codes` I32 [16, T] (the clip's codes: resampled to 48 kHz, mono on both channels, `floor(n / 3840)` frames) | MOSS-TTS-Nano ([moss_tts_nano.md](models/moss_tts_nano.md)) | `scripts/bake-speakers.py` writes them into a copy of a codec GGUF (or a speaker file). OuteTTS speakers cannot be derived from audio; diff --git a/docs/model_status.md b/docs/model_status.md index e12616d..9fb41e7 100644 --- a/docs/model_status.md +++ b/docs/model_status.md @@ -44,7 +44,7 @@ | OuteTTS-1.0 (0.6B / Llama-1B) | 🟡 | Builtin voices in a per-model codec GGUF, no voice clone; see [models/outetts.md](models/outetts.md) | | OuteTTS-0.2 / 0.3 | 🟡 | Same; text reduced to a-z words (numbers / romanization are the caller's job) | | Pocket-TTS | 🟡 | Needs a voice (reference audio / speaker file); a few seeds drop words, as in the reference; see [models/pocket_tts.md](models/pocket_tts.md) | -| MOSS-TTS-Nano-100M | 🟡 | AR loop runs in HF; codec.cpp decode only | +| MOSS-TTS-Nano-100M | ✅ | Voice clone (`--ref-audio`) or no voice; zh / ja / en; see [models/moss_tts_nano.md](models/moss_tts_nano.md) | | Soprano | 🟡 | Text normalization + sentence splitting not ported (pass normalized sentences); see [models/soprano.md](models/soprano.md) | Moshi is out of scope for `synthesize` (full-duplex, no Helium arch in llama.cpp); tts-cli refuses it. diff --git a/docs/models/moss_tts_nano.md b/docs/models/moss_tts_nano.md new file mode 100644 index 0000000..1b961a6 --- /dev/null +++ b/docs/models/moss_tts_nano.md @@ -0,0 +1,154 @@ +# MOSS-TTS-Nano-100M + +[OpenMOSS-Team/MOSS-TTS-Nano-100M](https://huggingface.co/OpenMOSS-Team/MOSS-TTS-Nano-100M): +a 100M multilingual (zh / ja / en and more) voice-cloning TTS over +[MOSS-Audio-Tokenizer-Nano](https://huggingface.co/OpenMOSS-Team/MOSS-Audio-Tokenizer-Nano) +(48 kHz stereo, 16 RVQ codebooks of 1024 at 12.5 Hz). + +| Part | Where | What | +|---|---|---| +| global transformer (GPT-2 + RoPE, 12 × 768) | llama.cpp, stock `starcoder2` | the backbone: embd / tokens in, hidden out | +| local transformer (1 GPT-2 layer, 17 positions) | codec_lm `residual_depth_ar`, `codec.lm.depth.arch = "gpt2"` | per frame: the text slot, then 16 codes | +| audio embeddings / heads (tied) | codec_lm | input tables, heads, backbone rows | +| MOSS-Audio-Tokenizer-Nano | codec.cpp `moss_audio_tokenizer` | voice codes (encode), audio (decode) | + +## Conversion + +```bash +# codec + LM adaptor (local transformer, embeddings, prompt template ids, the +# tokenizer's normalizer). The LM checkpoint is BF16: keep the adaptor BF16. +python scripts/convert-to-gguf.py --checkpoint-path MOSS-Audio-Tokenizer-Nano \ + --lm-source MOSS-TTS-Nano-100M --outtype F16 --lm-outtype BF16 \ + -o moss_tts_nano_codec.gguf # 80 MB; + --quantization Q8_0: 62 MB + +# global transformer → starcoder2 backbone GGUF with the SentencePiece vocab +python scripts/convert-backbone-to-gguf.py --model-id MOSS-TTS-Nano-100M \ + --output backbone-bf16.gguf --outtype bf16 +``` + +The voice is encoded by the codec's encoder, so its precision shows in the +reference codes: equal to the reference's `batch_encode` on 96 % (F32), 95 % +(F16) and 56–72 % (Q8_0) of the codes on the eval clips. Intelligibility did +not differ measurably between F16 and Q8_0 (below), but F16 keeps the voice +prompt closest to the reference's. + +The global transformer is pre-LN LayerNorm with shift, biased q/k/v/o and +gelu_new FFN, final LayerNorm, full-width RoPE (base 10000) and no position +table: llama.cpp's `starcoder2`, no arch patch. `c_attn` splits into q/k/v; +MOSS rotates interleaved pairs, starcoder2 is NEOX, so each head's q/k rows +and biases are reordered to [even, odd]. The output head is tied to `wte` +(`token_embd`). The checkpoint is BF16, so `--outtype f32` stays BF16 and no +F16 variant is published. + +The tokenizer is SentencePiece BPE with the `nmt_nfkc` normalizer. It goes in +as llama.cpp's SPM vocab (score merges, byte fallback, space prefix), which +has no normalizer: the codec GGUF carries the precompiled charsmap +(`codec.lm.moss_tts_nano.text_norm_charsmap`) and the family normalizes the +text (NFKC + NMT rules, whitespace collapsed) before the host tokenizes. The +result equals `SentencePieceProcessor.encode` on every test sentence (zh, ja, +en, full-width punctuation, half-width kana); the one known difference is a +text that starts with a user-defined piece such as `` (no leading +`▁`). The prompt template's pieces are baked as token ids, because the +reference encodes each piece on its own. + +## Runtime + +```bash +tts-cli synthesize --backbone backbone-bf16.gguf --model moss_tts_nano_codec.gguf \ + --text "你也可以咨询除贵国以外其他政府的建议。" --ref-audio voice.wav --output out.wav +``` + +The family (`common/audio_lm_family_moss_nano.cpp`) follows +`modeling_moss_tts_nano.py` `inference(mode="voice_clone")`: + +- prompt (`build_inference_input_ids`): `<|im_start|>user\n\n- + Reference(s):\n` `<|audio_start|>` reference rows `<|audio_end|>` the + instruction block, the text, `\n<|im_end|>\n<|im_start|>assistant\n` + `<|audio_start|>`. A reference row is `wte[user_slot] + Σ audio_embeddings[k][code_k]`. + Without a voice the reference section is `None` (continuation mode with no + prompt audio). +- per frame (`_iter_generation_events`): the backbone's last hidden enters + the local transformer at position 0; its text head picks the assistant + slot or `<|audio_end|>`. The audio end stops the generation before any + code is drawn; otherwise position 1 reads `wte[assistant_slot]` and + positions 2..17 the previous code's embedding, each emitting the next code + (KV cache across the 17 positions, reset per frame). The next backbone row + is `wte[assistant_slot] + Σ audio_embeddings[k][code_k]`, the sum over the + 17 input tables. +- long text: voice clone splits text above 50 tokens at sentence / clause + punctuation and joins the chunks with a 0.24 s pause; the family splits at + 150 UTF-8 bytes (the same chunks as the reference on every test sentence) + and inserts the same pause. `max_frames` defaults to 300 per chunk. +- a voice is the codec speaker `ref_codes` I32 [16, T] + (docs/codec_speaker.md): `codec_speaker_from_audio` resamples the clip to + 48 kHz in-graph (torchaudio's sinc), copies mono to both channels, encodes + the whole clip and keeps `floor(n / 3840)` frames. Stereo references are + downmixed first (the reference encodes both channels as they are). + +### Sampling + +The reference samples the codebooks at temperature 1.7 / top_k 25 / top_p 0.8 +(the backbone GGUF's `general.sampling.*`, temperature first, no repetition +penalty), and the text slot apart at temperature 1.5 / top_p 1. A host +applies one setting to every codec-side head, and with the codebooks' top_p +the audio end could not be drawn while its probability is below 0.2: +generations ran past the end. So the text slot is drawn model-side, like a +stop head: the family samples it from its two logits at +`codec.lm.moss_tts_nano.text_temperature` (1.5; `<= 0` = argmax) with its own +stream seeded by `codec_audio_lm_set_seed`, and hands the host a one-hot +head. `--temp 0` makes the codebooks greedy; for a fully greedy run also pass +`--override-kv codec.lm.moss_tts_nano.text_temperature=float:0`. + +## Parity + +Against `modeling_moss_tts_nano.py` (float32, sdpa) on the zh voice-clone +prompt (331 rows): + +| Stage | Result | +|---|---| +| tokenizer (normalizer + llama.cpp SPM) | equal to SentencePiece on 18 / 18 texts | +| backbone hidden (llama.cpp starcoder2) | rel. error 4e-4 (F32 weights), 4e-3 (BF16) | +| depth decoder, teacher-forced frame 0 (BF16 adaptor) | 17 / 17 argmax equal, logits max abs diff 0.05 | +| greedy generation, all F32 | first 34 frames (17 tokens each) equal, then a float-noise near-tie flips | +| voice codes vs `batch_encode` (F32 codec) | 96 % equal (as plain `codec_encode`; deep RVQ levels) | + +## Evaluation + +Voice-clone read-back of `tts-cli synthesize` (BF16 backbone, F16 or Q8_0 +codec + BF16 adaptor, model-default sampling) against the PyTorch reference +(`inference(mode="voice_clone", do_sample=True)`, float32) on the same texts +and voices: zh = 4 FLEURS cmn sentences in a FLEURS zh voice, ja = 4 FLEURS +ja sentences in a ja voice, en = 4 FLEURS en sentences in an en voice, +zh/en voice = 2 zh sentences in the en voice. ASR: whisper large-v3-turbo +(live-translate `lt-eval`, cascade mode) on the 16 kHz mono mix; CER for zh +(hypothesis to simplified) / ja and WER for en, punctuation and spaces +removed. Both sides use seeds 101 + i, 201 + i, ... 501 + i (20 utterances +per language, 10 for zh/en voice). + +Sampling makes single runs vary a lot, on both sides: the ASR also +hallucinates repetitions on some clips (one en utterance scores WER 17.5), +so the table gives the corpus score per seed, its mean, the mean with each +utterance's errors capped at its length, and the median utterance. + +| Set | Metric | Reference: seeds (mean / capped / median) | codec.cpp Q8_0 codec | codec.cpp F16 codec | +|---|---|---|---|---| +| zh | CER | .42 .13 .04 .00 .06 (.131 / .131 / .057) | .22 .14 .64 .02 .08 (.219 / .163 / .029) | 1.11 .04 .02 .20 .05 (.283 / .142 / .031) | +| ja | CER | .54 .51 .47 .45 1.49 (.692 / .513 / .549) | .33 .43 .45 .44 .52 (.433 / .433 / .424) | .53 .39 .52 .43 .59 (.492 / .492 / .496) | +| en | WER | .55 .28 .10 .04 .35 (.264 / .264 / .165) | .51 4.03 .15 .31 .10 (1.021 / .344 / .189) | .12 .40 .12 .17 .50 (.259 / .256 / .134) | +| zh, en voice | CER | .25 .13 .49 .07 .44 (.274 / .274 / .125) | .15 .20 .14 .37 .23 (.219 / .219 / .195) | .34 .23 .10 .35 .25 (.253 / .253 / .318) | + +The single unseeded reference run quoted earlier (zh .042, ja .43, en .115, +zh/en voice .085) is one draw of the same spread; re-scored with this scorer +it is zh .042, ja .406, en .115, zh/en voice .085. Failure modes are the +reference's too: an early audio end (a clipped sentence), a repeated phrase. + +Host speed, `tts-cli`, 8 threads, CPU only (AMD Ryzen AI Max+ 395), over +the 70 utterances of the F16 run (723 s of audio): generation (backbone + +depth decoder, prompt included) RTF 0.095, about 7.5 ms per 80 ms frame; +codec decode RTF 0.051; the voice (resample + encode) 0.35 s for a 6 s clip, +2.1 s for an 18 s one, once per voice. + +`tests/e2e/moss_tts_nano_smoke.py` runs the voice, two sampled syntheses +and, with `MOSS_TTS_NANO_SRC` / `MOSS_AUDIO_TOKENIZER_SRC`, the parity checks +above; `ttscli_synthesize_smoke.py` and `python_tts_smoke.py` have a +`moss_tts_nano` case. From af7516e7c723e946d9e365834e8a545d6c8a3f28 Mon Sep 17 00:00:00 2001 From: Hans Date: Sat, 14 Nov 2026 20:26:43 +0800 Subject: [PATCH 08/11] =?UTF-8?q?docs(moss-tts-nano):=20status=20?= =?UTF-8?q?=F0=9F=9F=A1,=20model-side=20draw=20in=20the=20sampling=20contr?= =?UTF-8?q?act;=20smoke=20reports=20CER?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit model_status: 🟡 like the other seed-fragile models (sampled output varies a lot by seed, as the reference's). codec_common_api's sampling section names the one model-side draw (the MOSS-TTS-Nano text slot). The model notes add the family-path greedy parity (244 / 300 frames equal), the no-voice / speaker-file / streaming runs, the F16 voice-code range, and that the two sides' seeds are not the same draws. The smoke reports the sampled Whisper CER instead of asserting it and documents the F16 codec conversion. Co-Authored-By: Claude Opus 5.5 --- docs/codec_common_api.md | 7 +++++-- docs/model_status.md | 2 +- docs/models/moss_tts_nano.md | 28 ++++++++++++++++++---------- scripts/utils/sampling.py | 3 ++- tests/e2e/moss_tts_nano_smoke.py | 16 ++++++++-------- 5 files changed, 34 insertions(+), 22 deletions(-) diff --git a/docs/codec_common_api.md b/docs/codec_common_api.md index 2652394..7d79a75 100644 --- a/docs/codec_common_api.md +++ b/docs/codec_common_api.md @@ -149,8 +149,11 @@ The host samples every token with llama.cpp's sampler: the backbone's, and each codec-side head's (`SAMPLE_HEAD` verdicts: `codec_audio_lm_head_logits` gives the head's logits, the model's constraints already applied as -inf and guidance already combined; `codec_audio_lm_head_token` takes the id back and -gives the next verdict). codec_audio_lm holds no sampler and no sampling -settings; it only suggests constraints: `grammar` / `allowed` / +gives the next verdict). codec_audio_lm holds no token sampler and no sampling +settings (one exception: MOSS-TTS-Nano's text slot, a two-way stop decision the +reference draws at its own temperature, is drawn by the family from its own +stream seeded by `codec_audio_lm_set_seed`, and the host gets a one-hot head; +see models/moss_tts_nano.md); it only suggests constraints: `grammar` / `allowed` / `penalty_exempt` for the backbone, and `head_groups` for the heads. Build one host sampler per group (one random stream and penalty history; seed group `g` with seed + 1 + g), with the same llama.cpp settings as the backbone; a group diff --git a/docs/model_status.md b/docs/model_status.md index 9fb41e7..fde68d2 100644 --- a/docs/model_status.md +++ b/docs/model_status.md @@ -44,7 +44,7 @@ | OuteTTS-1.0 (0.6B / Llama-1B) | 🟡 | Builtin voices in a per-model codec GGUF, no voice clone; see [models/outetts.md](models/outetts.md) | | OuteTTS-0.2 / 0.3 | 🟡 | Same; text reduced to a-z words (numbers / romanization are the caller's job) | | Pocket-TTS | 🟡 | Needs a voice (reference audio / speaker file); a few seeds drop words, as in the reference; see [models/pocket_tts.md](models/pocket_tts.md) | -| MOSS-TTS-Nano-100M | ✅ | Voice clone (`--ref-audio`) or no voice; zh / ja / en; see [models/moss_tts_nano.md](models/moss_tts_nano.md) | +| MOSS-TTS-Nano-100M | 🟡 | Voice clone (`--ref-audio`) or no voice; sampled output varies a lot by seed (clipped or repeated phrases), as in the reference; see [models/moss_tts_nano.md](models/moss_tts_nano.md) | | Soprano | 🟡 | Text normalization + sentence splitting not ported (pass normalized sentences); see [models/soprano.md](models/soprano.md) | Moshi is out of scope for `synthesize` (full-duplex, no Helium arch in llama.cpp); tts-cli refuses it. diff --git a/docs/models/moss_tts_nano.md b/docs/models/moss_tts_nano.md index 1b961a6..2a33cc9 100644 --- a/docs/models/moss_tts_nano.md +++ b/docs/models/moss_tts_nano.md @@ -27,8 +27,8 @@ python scripts/convert-backbone-to-gguf.py --model-id MOSS-TTS-Nano-100M \ ``` The voice is encoded by the codec's encoder, so its precision shows in the -reference codes: equal to the reference's `batch_encode` on 96 % (F32), 95 % -(F16) and 56–72 % (Q8_0) of the codes on the eval clips. Intelligibility did +reference codes: equal to the reference's `batch_encode` on 96 % (F32), +92.5–95.7 % (F16) and 56–72 % (Q8_0) of the codes on the eval clips. Intelligibility did not differ measurably between F16 and Q8_0 (below), but F16 keeps the voice prompt closest to the reference's. @@ -109,7 +109,8 @@ prompt (331 rows): | tokenizer (normalizer + llama.cpp SPM) | equal to SentencePiece on 18 / 18 texts | | backbone hidden (llama.cpp starcoder2) | rel. error 4e-4 (F32 weights), 4e-3 (BF16) | | depth decoder, teacher-forced frame 0 (BF16 adaptor) | 17 / 17 argmax equal, logits max abs diff 0.05 | -| greedy generation, all F32 | first 34 frames (17 tokens each) equal, then a float-noise near-tie flips | +| greedy generation, all F32, stages chained by hand | first 34 frames (17 tokens each) equal, then a float-noise near-tie flips | +| greedy `codec_cpp.TTS` (the family path: normalize, tokenize, voice rows, frame loop), all F32, same voice codes on both sides | first 244 frames equal (91 % of 300 frames' codes) | | voice codes vs `batch_encode` (F32 codec) | 96 % equal (as plain `codec_encode`; deep RVQ levels) | ## Evaluation @@ -120,10 +121,11 @@ codec + BF16 adaptor, model-default sampling) against the PyTorch reference and voices: zh = 4 FLEURS cmn sentences in a FLEURS zh voice, ja = 4 FLEURS ja sentences in a ja voice, en = 4 FLEURS en sentences in an en voice, zh/en voice = 2 zh sentences in the en voice. ASR: whisper large-v3-turbo -(live-translate `lt-eval`, cascade mode) on the 16 kHz mono mix; CER for zh +(whisper.cpp, Q8_0, VAD-segmented) on the 16 kHz mono mix; CER for zh (hypothesis to simplified) / ja and WER for en, punctuation and spaces -removed. Both sides use seeds 101 + i, 201 + i, ... 501 + i (20 utterances -per language, 10 for zh/en voice). +removed. Each side ran 5 seeds (101 + i ... 501 + i, 20 utterances per +language, 10 for zh/en voice); the two use different RNGs, so a seed is not +the same draw on both sides: compare the spreads, not the columns. Sampling makes single runs vary a lot, on both sides: the ASR also hallucinates repetitions on some clips (one en utterance scores WER 17.5), @@ -137,10 +139,16 @@ utterance's errors capped at its length, and the median utterance. | en | WER | .55 .28 .10 .04 .35 (.264 / .264 / .165) | .51 4.03 .15 .31 .10 (1.021 / .344 / .189) | .12 .40 .12 .17 .50 (.259 / .256 / .134) | | zh, en voice | CER | .25 .13 .49 .07 .44 (.274 / .274 / .125) | .15 .20 .14 .37 .23 (.219 / .219 / .195) | .34 .23 .10 .35 .25 (.253 / .253 / .318) | -The single unseeded reference run quoted earlier (zh .042, ja .43, en .115, -zh/en voice .085) is one draw of the same spread; re-scored with this scorer -it is zh .042, ja .406, en .115, zh/en voice .085. Failure modes are the -reference's too: an early audio end (a clipped sentence), a repeated phrase. +A single unseeded reference run (zh .042, ja .43, en .115, zh/en voice .085; +with this scorer zh .042, ja .406, en .115, zh/en voice .085) is one draw of +the same spread. Failure modes are the reference's too: an early audio end (a +clipped sentence; 2 sub-second clips in the reference's 70 utterances, 0 and 1 +at 2.5 s in codec.cpp's two runs) and a repeated phrase. + +A run without a voice (the `None` reference section) and the +`--save-speaker` / `--speaker-file` round trip (bit-identical audio) work; +`codec_audio_lm_stream_poll` streams (chunks match the whole decode up to the +crossfades). Host speed, `tts-cli`, 8 threads, CPU only (AMD Ryzen AI Max+ 395), over the 70 utterances of the F16 run (723 s of audio): generation (backbone + diff --git a/scripts/utils/sampling.py b/scripts/utils/sampling.py index dc3cfe2..11a9c86 100644 --- a/scripts/utils/sampling.py +++ b/scripts/utils/sampling.py @@ -33,7 +33,8 @@ # modeling_moss_tts_nano.py inference(do_sample=True): the audio codebooks' # settings (audio_temperature / top_k / top_p, no repetition penalty). Its # text slot (assistant slot vs audio end) uses temperature 1.5 / top_p 1.0; - # every head here takes the backbone's settings (docs/models/moss_tts_nano.md). + # the family draws that one model-side (codec.lm.moss_tts_nano.text_temperature), + # every codebook head takes these (docs/models/moss_tts_nano.md). "moss_tts_nano": dict(temp=1.7, top_k=25, top_p=0.8, min_p=0.0, samplers="temperature;top_k;top_p"), # tts.py::generate. mtl_tts.py uses repetition_penalty 2.0, but only with # its AlignmentStreamAnalyzer (attention-driven EOS forcing), which this diff --git a/tests/e2e/moss_tts_nano_smoke.py b/tests/e2e/moss_tts_nano_smoke.py index 4f30c3e..7a067c7 100644 --- a/tests/e2e/moss_tts_nano_smoke.py +++ b/tests/e2e/moss_tts_nano_smoke.py @@ -4,7 +4,7 @@ Assets (missing → skip): models/moss_tts_nano/moss_tts_nano_codec.gguf codec + LM adaptor scripts/convert-to-gguf.py --checkpoint-path - --lm-source --quantization Q8_0 --lm-outtype BF16 + --lm-source --outtype F16 --lm-outtype BF16 models/moss_tts_nano/backbone-bf16.gguf the global transformer (starcoder2) scripts/convert-backbone-to-gguf.py --model-id --outtype bf16 @@ -13,7 +13,8 @@ 2. Synthesis (codec_cpp.TTS, the bundled llama.cpp backbone, fixed seeds) of an English and a Chinese sentence in the cloned JFK voice: stops on the text slot's audio end, 48 kHz, plausible duration, not silent; the Whisper - CER (when transformers + whisper are available) stays under a loose bound. + CER (when transformers + whisper are available) is reported (sampled + output varies with the seed and the SIMD path). 3. With MOSS_TTS_NANO_SRC= and torch: teacher-forced frame 0 of the depth decoder on PyTorch's backbone hidden (all 17 argmaxes equal, logits close) and the voice codes vs the reference's @@ -42,7 +43,7 @@ CODEC_F32 = M / "moss_tts_nano_codec-f32.gguf" # optional: F32 codec part (--outtype F32) for the voice parity REF_WAV = REPO / "assets" / "refs" / "jfk_en.wav" -CASES = [ # name, text, lang, seed, CER bound (sampled; the reference varies as much from seed to seed) +CASES = [ # name, text, lang, seed, CER flagged above (sampled; the reference varies as much from seed to seed) ("en", "The birch canoe slid on the smooth planks.", "en", 3, 0.35), ("zh", "你也可以咨询除贵国以外其他政府的建议。", "zh", 3, 0.35), ] @@ -78,8 +79,7 @@ def check_synth() -> bool: res = asr_cer(out, text, lang) if res is not None: asr, cer = res - msg += f" ASR='{asr}' CER={cer:.3f}" - ok = ok and cer <= cer_max + msg += f" ASR='{asr}' CER={cer:.3f}" + ("" if cer <= cer_max else " (high, reported)") print(f"[{'PASS' if ok else 'FAIL'}] synth_{name}: {msg}") ok_all &= ok return ok_all @@ -119,12 +119,12 @@ def check_parity(model) -> bool | None: got = codec_cpp.Context(model).speaker_from_audio(x, sr).slot("ref_codes").reshape(-1, 16) n = min(len(got), len(codes)) frac = float((got[:n] == codes[:n]).mean()) - # Exact up to deep-RVQ near ties with an F32 codec part; a quantized - # encoder (the Q8_0 release GGUF) only reports. + # Exact up to deep-RVQ near ties with an F32 codec part; another + # encoder precision only reports. strict = model is not None and CODEC_F32.exists() good = len(got) == len(codes) and (frac >= 0.90 or not strict) print(f"[{'PASS' if good else 'FAIL'}] parity_voice: {len(got)} vs {len(codes)} frames, {frac:.1%} codes equal" - f"{'' if strict else ' (quantized encoder: reported only)'}") + f"{'' if strict else ' (no F32 codec GGUF: reported only)'}") ok &= good else: codes = np.zeros((20, 16), np.int64) # any reference rows exercise the prompt From d0aea172bd47e5e3c960d2945319265f3cd42055 Mon Sep 17 00:00:00 2001 From: Hans Date: Sat, 14 Nov 2026 21:35:34 +0800 Subject: [PATCH 09/11] refactor(moss-tts-nano): no host-visible declaration; document the stop draw - The family factory is declared at its only call site (audio_lm_family.cpp), so common/audio_lm_family.h is back to main. - The text slot (the stop decision) stays drawn in the family from the host's seed. The reference samples it at 1.5 / top_p 1.0 between two logits; a host chain applies top_p before the temperature, so no logit scaling reproduces it. Measured over 5 seeds x 70 utterances: host sampling with scaled logits gives Japanese clips of 20.8 s vs the reference's 11.7 s, and the smoke's English sentence ran to the frame cap. docs/models/moss_tts_nano.md has the table. - docs/proposals/head-group-sampling.md: per-head-group sampler settings, the public API change that would move the draw to the host. Co-Authored-By: Claude Opus 5.5 --- common/audio_lm_family.cpp | 3 ++ common/audio_lm_family.h | 1 - common/audio_lm_family_moss_nano.cpp | 15 +++--- docs/models/moss_tts_nano.md | 45 ++++++++++++---- docs/proposals/head-group-sampling.md | 75 +++++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 16 deletions(-) create mode 100644 docs/proposals/head-group-sampling.md diff --git a/common/audio_lm_family.cpp b/common/audio_lm_family.cpp index db9e9ea..3e70292 100644 --- a/common/audio_lm_family.cpp +++ b/common/audio_lm_family.cpp @@ -9,6 +9,9 @@ namespace codec_common { +// Declared here, not in audio_lm_family.h (a header hosts include): the only caller is the dispatch below. +std::unique_ptr alm_family_moss_nano(audio_lm_context * alm, struct codec_lm * lm); + // ── alm_vocab ──────────────────────────────────────────────────────── std::vector alm_vocab::tokenize(const std::string & text, bool add_special, bool parse_special) const { diff --git a/common/audio_lm_family.h b/common/audio_lm_family.h index 6469838..fe97ec9 100644 --- a/common/audio_lm_family.h +++ b/common/audio_lm_family.h @@ -245,7 +245,6 @@ std::unique_ptr alm_family_chatterbox(audio_lm_context * alm, struct std::unique_ptr alm_family_cosyvoice(audio_lm_context * alm, struct codec_lm * lm); std::unique_ptr alm_family_continuous(audio_lm_context * alm); std::unique_ptr alm_family_flow(audio_lm_context * alm, struct codec_lm * lm); -std::unique_ptr alm_family_moss_nano(audio_lm_context * alm, struct codec_lm * lm); } // namespace codec_common diff --git a/common/audio_lm_family_moss_nano.cpp b/common/audio_lm_family_moss_nano.cpp index fb9efed..ad81ba8 100644 --- a/common/audio_lm_family_moss_nano.cpp +++ b/common/audio_lm_family_moss_nano.cpp @@ -189,12 +189,15 @@ class moss_nano_family : public alm_family { return true; } - // The text slot is the stop decision: the reference samples it between the - // assistant slot and the audio end at its own temperature (1.5, top_p 1), - // apart from the codebooks' settings (1.7 / top_k 25 / top_p 0.8) the host - // applies to every head; under those, the end could not be drawn below - // p = 0.2 and generations ran on. So the model draws it here, like a stop - // head, with its own seeded stream, and hands the host a one-hot head. + // The text slot is the stop decision. The reference (modeling_moss_tts_nano.py, + // _sample_next_assistant_text_token) keeps two text_lm_head logits, the assistant slot (continue) and the audio + // end (stop), and samples them at text_temperature 1.5 / top_p 1.0; the 16 codebooks use 1.7 / top_k 25 / + // top_p 0.8. The host samples every head with one llama.cpp chain, which applies top_p before the temperature, + // so no logit scaling here can give the 1.5 / no-truncation draw: under top_p 0.8 the end is dropped while its + // reference probability is below ~0.31, and generations run long (docs/models/moss_tts_nano.md, measured). So + // the family draws the decision from its two logits with a stream seeded by the host's seed (as the continuous + // and flow families draw their noise) and hands the host a one-hot head. A per-head-group sampler setting would + // move it to the host (docs/proposals/head-group-sampling.md). // codec.lm.moss_tts_nano.text_temperature <= 0: argmax (greedy). void decide_text_slot() { const int32_t n = (int32_t) logits_.size(), end = mi_->audio_end, slot = mi_->assistant_slot; diff --git a/docs/models/moss_tts_nano.md b/docs/models/moss_tts_nano.md index 2a33cc9..3189c90 100644 --- a/docs/models/moss_tts_nano.md +++ b/docs/models/moss_tts_nano.md @@ -89,14 +89,26 @@ The family (`common/audio_lm_family_moss_nano.cpp`) follows The reference samples the codebooks at temperature 1.7 / top_k 25 / top_p 0.8 (the backbone GGUF's `general.sampling.*`, temperature first, no repetition -penalty), and the text slot apart at temperature 1.5 / top_p 1. A host -applies one setting to every codec-side head, and with the codebooks' top_p -the audio end could not be drawn while its probability is below 0.2: -generations ran past the end. So the text slot is drawn model-side, like a -stop head: the family samples it from its two logits at -`codec.lm.moss_tts_nano.text_temperature` (1.5; `<= 0` = argmax) with its own -stream seeded by `codec_audio_lm_set_seed`, and hands the host a one-hot -head. `--temp 0` makes the codebooks greedy; for a fully greedy run also pass +penalty). The text slot is the stop decision: `_sample_next_assistant_text_token` +keeps only two `text_lm_head` logits, the assistant slot (continue) and +`<|audio_end|>` (stop), and samples them at temperature 1.5, top_p 1.0 +(`inference(text_temperature=1.5, text_top_p=1.0)`). + +A host samples every codec-side head with one llama.cpp chain (the card's +settings). That can't reproduce the stop draw: llama.cpp's default order applies +top_p **before** the temperature, so the codebooks' top_p 0.8 drops the end +whenever the continue probability is >= 0.8, i.e. while the reference's end +probability is below about 0.31. Scaling the two logits by 1.7 / 1.5 in the +family fixes the temperature but not the truncation, and the generation then +stops near the argmax point. Measured below, Japanese runs ~1.7x long, and the +smoke's English sentence ran to the frame cap. So the family draws the slot +itself: from its two logits at `codec.lm.moss_tts_nano.text_temperature` (1.5; +`<= 0` = argmax), with its own stream seeded by `codec_audio_lm_set_seed` (as +the continuous and flow families draw their noise), and it hands the host a +one-hot head. Moving the draw to the host needs a sampler of its own for that +head, which is a `codec_audio_lm.h` change, proposed in +`docs/proposals/head-group-sampling.md`. `--temp 0` makes the codebooks greedy. +For a fully greedy run also pass `--override-kv codec.lm.moss_tts_nano.text_temperature=float:0`. ## Parity @@ -130,7 +142,7 @@ the same draw on both sides: compare the spreads, not the columns. Sampling makes single runs vary a lot, on both sides: the ASR also hallucinates repetitions on some clips (one en utterance scores WER 17.5), so the table gives the corpus score per seed, its mean, the mean with each -utterance's errors capped at its length, and the median utterance. +utterance's errors capped at its length, and the median utterance. The table after it compares the stop decisions. | Set | Metric | Reference: seeds (mean / capped / median) | codec.cpp Q8_0 codec | codec.cpp F16 codec | |---|---|---|---|---| @@ -139,6 +151,21 @@ utterance's errors capped at its length, and the median utterance. | en | WER | .55 .28 .10 .04 .35 (.264 / .264 / .165) | .51 4.03 .15 .31 .10 (1.021 / .344 / .189) | .12 .40 .12 .17 .50 (.259 / .256 / .134) | | zh, en voice | CER | .25 .13 .49 .07 .44 (.274 / .274 / .125) | .15 .20 .14 .37 .23 (.219 / .219 / .195) | .34 .23 .10 .35 .25 (.253 / .253 / .318) | +Stop decision, F16 codec, same 5 seeds (durations: mean / >20 s clips of 20; the +reference's in the first column): + +| Set | Reference | drawn in the library (this PR) | host-sampled, logits scaled 1.7/1.5 | argmax stop | +|---|---|---|---|---| +| zh CER | .131 · 9.1 s / 0 | .283 (capped .142) · 9.4 s / 0 | .071 · 9.9 s / 0 | .049 · 9.4 s / 0 | +| ja CER | .692 (capped .513) · 11.7 s / 1 | .492 · 12.8 s / 3 | .451 · 20.8 s / 11 | .534 (capped .438) · 20.0 s / 10 | +| en WER | .264 · 8.6 s / 0 | .259 · 7.4 s / 0 | .200 · 8.7 s / 1 | .213 · 8.7 s / 1 | +| zh, en voice CER | .274 · 12.7 s / 1 | .253 · 12.9 s / 1 | .191 · 13.7 s / 1 | .170 · 13.7 s / 1 | + +The later stop costs no read-back accuracy (the scorer counts words, not +trailing audio) but the Japanese clips run long: 11 of 20 past 20 s, up to 42 s, +against 1 at 22 s for the reference. The library draw matches the reference's +lengths. + A single unseeded reference run (zh .042, ja .43, en .115, zh/en voice .085; with this scorer zh .042, ja .406, en .115, zh/en voice .085) is one draw of the same spread. Failure modes are the reference's too: an early audio end (a diff --git a/docs/proposals/head-group-sampling.md b/docs/proposals/head-group-sampling.md new file mode 100644 index 0000000..1d544df --- /dev/null +++ b/docs/proposals/head-group-sampling.md @@ -0,0 +1,75 @@ +# Proposal: per-head-group sampler settings in `codec_audio_lm_head_group` + +Status: proposal for review, not implemented. If accepted it changes `include/codec_audio_lm.h` +(`struct codec_audio_lm_head_group`), `common/tts_runner.cpp` (the reference host), `python/codec_cpp/_ffi.py` +(the struct mirror) and `docs/codec_common_api.md`. + +## Motivation + +Some models sample different codec-side heads with different settings, and the host can't reproduce that today: +the header says "All groups use the same llama.cpp settings as the backbone" (`codec_audio_lm.h:255`). + +- **MOSS-TTS-Nano**: the stop decision is a two-way text slot (continue / `<|audio_end|>`) sampled at + temperature 1.5, top_p 1.0, and the 16 codebooks at 1.7 / top_k 25 / top_p 0.8 (`modeling_moss_tts_nano.py`, + `_sample_next_assistant_text_token` and `inference(text_temperature=1.5, text_top_p=1.0, audio_temperature=1.7, + audio_top_p=0.8)`). Under one shared setting, llama.cpp's chain applies top_p 0.8 before the temperature and + drops the end while its reference probability is below ~0.31. Measured (5 seeds, 70 utterances): Japanese clips + run 20.8 s on average against the reference's 11.7 s (11 of 20 over 20 s against 1). Scaling the logits + in the family fixes the temperature but can't undo the truncation, because temperature is the last step. +- **Qwen3-TTS** ships separate `subtalker_temperature / top_k / top_p` for the code predictor next to the + talker's (`generation_config.json`). Today they're equal (0.9 / 50 / 1.0), so nothing is lost yet. + +What PR #7 does today is draw the decision inside the library, from the host's seed. That matches the +reference's lengths, and the continuous and flow families already draw their noise the same way. But it puts +sampling in the library, out of the host's control. + +## Proposal + +Append an optional override to the group, with an explicit flag (no "0 means inherit"): + +```c +struct codec_audio_lm_head_group { + bool penalties; + const int32_t * history; + int32_t n_history; + const int32_t * penalty_exempt; + int32_t n_penalty_exempt; + // new + bool own_sampling; // true: sample this group with the settings below, not the backbone's + float temp; // llama.cpp semantics (<= 0: greedy) + int32_t top_k; // llama.cpp semantics (<= 0: off) + float top_p; // llama.cpp semantics (1.0: off) +}; +``` + +The family fills them from model metadata: MOSS-Nano's text-slot group gets `{true, 1.5, 0, 1.0}`, and the +codebook group keeps `own_sampling = false`. A host that builds one sampler per group (as `tts_runner` already +does, `tts_runner.cpp:402`) applies the override when `own_sampling` is set. The user's `--temp` etc. keep +applying to groups without it. A user who wants a greedy run still gets one: `--temp 0` makes every group greedy. + +## Alternatives + +1. **Keep the library draw** (PR #7 as it stands): exact and needs no API change, but the library samples. +2. **Host sampling with logit scaling** (tried, measured above): no API change and no library sampling, but the + stop comes late. The smoke's 3 s English sentence ran to the 24 s frame cap. +3. **Logit scaling plus a high "top_p floor" hint** (a per-group `min top_p`): a narrower version of this + proposal, fixing only this case. +4. **A new verdict field** carrying sampling settings per SAMPLE_HEAD step: more flexible per step, but larger, + and every host's loop changes. + +## Compatibility + +- ABI: the struct grows at the end. Hosts compiled against the old header read the old fields at the same + offsets, but iterate `head_groups[g]` with the old stride, which breaks for `n_head_groups > 1`. So this needs a + version bump, or the array has to come through a size-carrying accessor (`codec_audio_lm_head_group_get(ctx, g, + &out, sizeof out)`), which keeps old binaries working. +- Source: existing hosts compile unchanged and ignore the new fields, so they get today's behaviour. +- Python: `_ffi.py` appends the four fields. + +## Migration + +1. Add the fields (or the accessor) and document them. +2. `tts_runner`: `HeadSampler::build` takes the group's settings when `own_sampling` is set. +3. MOSS-Nano: the text slot becomes its own head group (group 1) with `{1.5, top_k off, top_p 1.0}`, and the + logit scaling goes away. +4. Optional: Qwen3-TTS fills `subtalker_*` into its code-predictor group, from the converter. From c2788a3014f95f2d98217b9f5028476d6ada1bdd Mon Sep 17 00:00:00 2001 From: Hans Date: Sun, 15 Nov 2026 00:31:38 +0800 Subject: [PATCH 10/11] feat(moss-tts-nano): host-sampled stop decision; top_p 1.0 is the required setting The library-side draw of the text slot goes. The family offers the host the two candidates (assistant slot, audio end) as their log-probabilities at the reference's text_temperature 1.5, scaled by the host temperature (codec.lm.moss_tts_nano.audio_temperature = 1.7). The host chain (temperature;top_k;top_p) then reproduces the reference's draw exactly when top_p is 1.0, which becomes the model's required setting (general.sampling.top_p from the converter; the smoke passes it explicitly). Measured over 5 seeds x 70 utterances: no clip runs past 20 s, lengths are within the reference's, and read-back error is at or below the reference on all four sets. 25 candidates with dummy tokens under the card's top_p 0.8 still ran long (ja 19.9 s vs 11.7 s). The head-group sampling proposal is dropped. Co-Authored-By: Claude Opus 5.5 --- common/audio_lm_family_moss_nano.cpp | 58 +++++++------- docs/models/moss_tts_nano.md | 75 +++++++++---------- docs/proposals/head-group-sampling.md | 75 ------------------- .../converters/lm_adaptor/moss_tts_local.py | 7 +- scripts/utils/sampling.py | 12 +-- tests/e2e/moss_tts_nano_smoke.py | 4 +- 6 files changed, 76 insertions(+), 155 deletions(-) delete mode 100644 docs/proposals/head-group-sampling.md diff --git a/common/audio_lm_family_moss_nano.cpp b/common/audio_lm_family_moss_nano.cpp index ad81ba8..722eb40 100644 --- a/common/audio_lm_family_moss_nano.cpp +++ b/common/audio_lm_family_moss_nano.cpp @@ -23,7 +23,6 @@ #include #include #include -#include namespace codec_common { namespace { @@ -164,8 +163,6 @@ class moss_nano_family : public alm_family { const float * next_embd(int32_t) const override { return audio_lm_get_next_embed(alm_, nullptr); } - void set_seed(uint32_t seed) override { rng_.seed(alm_resolve_seed(seed)); } - private: bool next_head(codec_audio_lm_verdict * v) { if (cb_ < n_cb_) { @@ -173,7 +170,7 @@ class moss_nano_family : public alm_family { const float * lg = audio_lm_step_logits(alm_, &idx, &n); if (lg == nullptr) return fail_alm("step logits"); logits_.assign(lg, lg + n); - if (cb_ == 0) decide_text_slot(); + if (cb_ == 0) present_text_slot(); *v = {CODEC_AUDIO_LM_SAMPLE_HEAD, false, true, false, -1, 0, n}; return true; } @@ -189,36 +186,34 @@ class moss_nano_family : public alm_family { return true; } - // The text slot is the stop decision. The reference (modeling_moss_tts_nano.py, - // _sample_next_assistant_text_token) keeps two text_lm_head logits, the assistant slot (continue) and the audio - // end (stop), and samples them at text_temperature 1.5 / top_p 1.0; the 16 codebooks use 1.7 / top_k 25 / - // top_p 0.8. The host samples every head with one llama.cpp chain, which applies top_p before the temperature, - // so no logit scaling here can give the 1.5 / no-truncation draw: under top_p 0.8 the end is dropped while its - // reference probability is below ~0.31, and generations run long (docs/models/moss_tts_nano.md, measured). So - // the family draws the decision from its two logits with a stream seeded by the host's seed (as the continuous - // and flow families draw their noise) and hands the host a one-hot head. A per-head-group sampler setting would - // move it to the host (docs/proposals/head-group-sampling.md). - // codec.lm.moss_tts_nano.text_temperature <= 0: argmax (greedy). - void decide_text_slot() { + // The text slot is the stop decision. The reference (modeling_moss_tts_nano.py, _sample_next_assistant_text_token) + // keeps two text_lm_head logits, the assistant slot (continue) and the audio end (stop), and samples them at + // text_temperature 1.5 with no top_p; the codebooks use audio_temperature 1.7 / top_k 25. The host samples every + // head with one chain, so the head offers only those two, as log-probabilities at 1.5 scaled by the host's + // temperature (codec.lm.moss_tts_nano.audio_temperature, = general.sampling.temp): the host's temperature step + // gives the reference's draw exactly, provided the chain keeps both (top_p 1, the model's required setting; + // with top_p < 1 the end is cut while its probability is below 1 - top_p and generations run long). + void present_text_slot() { const int32_t n = (int32_t) logits_.size(), end = mi_->audio_end, slot = mi_->assistant_slot; if (end < 0 || end >= n || slot < 0 || slot >= n) return; - bool stop; - if (frames_ < min_frames_) { - stop = false; // min_frames not reached - } else { - const char * tv = audio_lm_meta_str(alm_, "codec.lm.moss_tts_nano.text_temperature"); - const float temp = tv ? std::strtof(tv, nullptr) : 1.5f; - const float d = logits_[(size_t) end] - logits_[(size_t) slot]; - if (temp <= 0.0f) { - stop = d > 0.0f; - } else { - const double p_end = 1.0 / (1.0 + std::exp(-(double) d / temp)); - stop = std::uniform_real_distribution(0.0, 1.0)(rng_) < p_end; - } - } - for (int32_t i = 0; i < n; ++i) { - if (i != (stop ? end : slot)) logits_[(size_t) i] = -INFINITY; + auto kv = [&](const char * key, float dflt) { + const char * v = audio_lm_meta_str(alm_, key); + return v ? std::strtof(v, nullptr) : dflt; + }; + const double t_text = kv("codec.lm.moss_tts_nano.text_temperature", 1.5f); + const double t_host = kv("codec.lm.moss_tts_nano.audio_temperature", 1.7f); + const double d = (double) logits_[(size_t) end] - (double) logits_[(size_t) slot]; + std::fill(logits_.begin(), logits_.end(), -INFINITY); + if (frames_ < min_frames_) { // min_frames not reached: continue only + logits_[(size_t) slot] = 0.0f; + return; } + // log-sigmoid at text_temperature, times the host temperature (the host divides by it) + const double x = d / t_text; + const double log_end = x > 0 ? -std::log1p(std::exp(-x)) : x - std::log1p(std::exp(x)); + const double log_cont = log_end - x; + logits_[(size_t) end] = (float) (log_end * t_host); + logits_[(size_t) slot] = (float) (log_cont * t_host); } // The voice's reference codes: I32 [n_q, T] with n_q = n_codebook - 1. @@ -245,7 +240,6 @@ class moss_nano_family : public alm_family { codec_lm * lm_; const codec_lm_moss_nano_info * mi_; std::vector hidden_frame_, logits_; - std::mt19937 rng_; int32_t hidden_ = 0, n_cb_ = 0, cb_ = 0, frames_ = 0, min_frames_ = 0; }; diff --git a/docs/models/moss_tts_nano.md b/docs/models/moss_tts_nano.md index 3189c90..53df5d8 100644 --- a/docs/models/moss_tts_nano.md +++ b/docs/models/moss_tts_nano.md @@ -85,31 +85,29 @@ The family (`common/audio_lm_family_moss_nano.cpp`) follows the whole clip and keeps `floor(n / 3840)` frames. Stereo references are downmixed first (the reference encodes both channels as they are). -### Sampling - -The reference samples the codebooks at temperature 1.7 / top_k 25 / top_p 0.8 -(the backbone GGUF's `general.sampling.*`, temperature first, no repetition -penalty). The text slot is the stop decision: `_sample_next_assistant_text_token` -keeps only two `text_lm_head` logits, the assistant slot (continue) and -`<|audio_end|>` (stop), and samples them at temperature 1.5, top_p 1.0 -(`inference(text_temperature=1.5, text_top_p=1.0)`). - -A host samples every codec-side head with one llama.cpp chain (the card's -settings). That can't reproduce the stop draw: llama.cpp's default order applies -top_p **before** the temperature, so the codebooks' top_p 0.8 drops the end -whenever the continue probability is >= 0.8, i.e. while the reference's end -probability is below about 0.31. Scaling the two logits by 1.7 / 1.5 in the -family fixes the temperature but not the truncation, and the generation then -stops near the argmax point. Measured below, Japanese runs ~1.7x long, and the -smoke's English sentence ran to the frame cap. So the family draws the slot -itself: from its two logits at `codec.lm.moss_tts_nano.text_temperature` (1.5; -`<= 0` = argmax), with its own stream seeded by `codec_audio_lm_set_seed` (as -the continuous and flow families draw their noise), and it hands the host a -one-hot head. Moving the draw to the host needs a sampler of its own for that -head, which is a `codec_audio_lm.h` change, proposed in -`docs/proposals/head-group-sampling.md`. `--temp 0` makes the codebooks greedy. -For a fully greedy run also pass -`--override-kv codec.lm.moss_tts_nano.text_temperature=float:0`. +### Sampling (required settings) + +**Use `--temp 1.7 --top-k 25 --top-p 1.0 --min-p 0 --samplers "temperature;top_k;top_p"`.** These are the +backbone GGUF's `general.sampling.*` defaults from the converter, so a host that honours them gets them +automatically. + +The reference (`modeling_moss_tts_nano.py`, `inference(do_sample=True)`) samples two kinds of head: +- **The stop decision.** `_sample_next_assistant_text_token` keeps two `text_lm_head` logits, the assistant slot + (continue) and `<|audio_end|>` (stop), and samples them at `text_temperature` 1.5 with no top_p. +- **The 16 codebooks**, at `audio_temperature` 1.7 / top_k 25 / top_p 0.8. + +The host samples every head with one llama.cpp chain. The family hands the host only the two candidates: their +log-probabilities at 1.5, multiplied by `codec.lm.moss_tts_nano.audio_temperature` (1.7, the host's +temperature). The host's temperature step then reproduces the reference's stop draw exactly, as long as nothing +in the chain truncates: +- **top_p 0.8 would truncate.** With top_p after the temperature, it drops the minority whenever the other + candidate's probability is ≥ 0.8, so the end can't be drawn while its probability is ≤ 0.2. With top_p before + the temperature, the end is lost below 0.307. +- **So top_p is 1.0 for every head.** The codebooks lose the reference's top_p 0.8, at the cost measured in + Evaluation: no read-back loss, and lengths within the reference's. + +`--temp 0` makes the whole frame greedy, the stop included. Running with another `--temp` changes the stop's +temperature in proportion: 1.5 × T / 1.7. ## Parity @@ -151,20 +149,21 @@ utterance's errors capped at its length, and the median utterance. The table aft | en | WER | .55 .28 .10 .04 .35 (.264 / .264 / .165) | .51 4.03 .15 .31 .10 (1.021 / .344 / .189) | .12 .40 .12 .17 .50 (.259 / .256 / .134) | | zh, en voice | CER | .25 .13 .49 .07 .44 (.274 / .274 / .125) | .15 .20 .14 .37 .23 (.219 / .219 / .195) | .34 .23 .10 .35 .25 (.253 / .253 / .318) | -Stop decision, F16 codec, same 5 seeds (durations: mean / >20 s clips of 20; the -reference's in the first column): +Stop decision and host settings, F16 codec, same 5 seeds. Each cell is the read-back error, then the mean +duration / number of clips over 20 s (out of 20, or 10 for zh with the en voice): -| Set | Reference | drawn in the library (this PR) | host-sampled, logits scaled 1.7/1.5 | argmax stop | -|---|---|---|---|---| -| zh CER | .131 · 9.1 s / 0 | .283 (capped .142) · 9.4 s / 0 | .071 · 9.9 s / 0 | .049 · 9.4 s / 0 | -| ja CER | .692 (capped .513) · 11.7 s / 1 | .492 · 12.8 s / 3 | .451 · 20.8 s / 11 | .534 (capped .438) · 20.0 s / 10 | -| en WER | .264 · 8.6 s / 0 | .259 · 7.4 s / 0 | .200 · 8.7 s / 1 | .213 · 8.7 s / 1 | -| zh, en voice CER | .274 · 12.7 s / 1 | .253 · 12.9 s / 1 | .191 · 13.7 s / 1 | .170 · 13.7 s / 1 | - -The later stop costs no read-back accuracy (the scorer counts words, not -trailing audio) but the Japanese clips run long: 11 of 20 past 20 s, up to 42 s, -against 1 at 22 s for the reference. The library draw matches the reference's -lengths. +| Set | Reference (PyTorch) | **top_p 1.0 (this PR)** | drawn in the library | 25 candidates + dummies, top_p 0.8 | 2 candidates, top_p 0.8 | +|---|---|---|---|---|---| +| zh CER | .131 · 9.1 s / 0 | **.105 · 8.5 s / 0** | .283 · 9.4 s / 0 | .119 · 9.4 s / 0 | .071 · 9.9 s / 0 | +| ja CER | .692 · 11.7 s / 1 | **.541 · 11.1 s / 0** | .492 · 12.8 s / 3 | .449 · 19.9 s / 10 | .451 · 20.8 s / 11 | +| en WER | .264 · 8.6 s / 0 | **.241 · 7.1 s / 0** | .259 · 7.4 s / 0 | .231 · 8.7 s / 1 | .200 · 8.7 s / 1 | +| zh, en voice CER | .274 · 12.7 s / 1 | **.151 · 10.9 s / 0** | .253 · 12.9 s / 1 | .155 · 13.7 s / 1 | .191 · 13.7 s / 1 | + +The 25-candidate column keeps the card's top_p 0.8. The 23 dummy tokens soak up 0.195 of the mass, so top_p keeps +exactly continue and end. That is exact only while both candidates are ≥ 1.07 %, and below that the end is cut. +In these runs the end probability after the speech often sits under 1 %, so the Japanese clips still run long. + +The read-back scores do not penalise trailing audio, so the length columns are the stop measure. A single unseeded reference run (zh .042, ja .43, en .115, zh/en voice .085; with this scorer zh .042, ja .406, en .115, zh/en voice .085) is one draw of diff --git a/docs/proposals/head-group-sampling.md b/docs/proposals/head-group-sampling.md deleted file mode 100644 index 1d544df..0000000 --- a/docs/proposals/head-group-sampling.md +++ /dev/null @@ -1,75 +0,0 @@ -# Proposal: per-head-group sampler settings in `codec_audio_lm_head_group` - -Status: proposal for review, not implemented. If accepted it changes `include/codec_audio_lm.h` -(`struct codec_audio_lm_head_group`), `common/tts_runner.cpp` (the reference host), `python/codec_cpp/_ffi.py` -(the struct mirror) and `docs/codec_common_api.md`. - -## Motivation - -Some models sample different codec-side heads with different settings, and the host can't reproduce that today: -the header says "All groups use the same llama.cpp settings as the backbone" (`codec_audio_lm.h:255`). - -- **MOSS-TTS-Nano**: the stop decision is a two-way text slot (continue / `<|audio_end|>`) sampled at - temperature 1.5, top_p 1.0, and the 16 codebooks at 1.7 / top_k 25 / top_p 0.8 (`modeling_moss_tts_nano.py`, - `_sample_next_assistant_text_token` and `inference(text_temperature=1.5, text_top_p=1.0, audio_temperature=1.7, - audio_top_p=0.8)`). Under one shared setting, llama.cpp's chain applies top_p 0.8 before the temperature and - drops the end while its reference probability is below ~0.31. Measured (5 seeds, 70 utterances): Japanese clips - run 20.8 s on average against the reference's 11.7 s (11 of 20 over 20 s against 1). Scaling the logits - in the family fixes the temperature but can't undo the truncation, because temperature is the last step. -- **Qwen3-TTS** ships separate `subtalker_temperature / top_k / top_p` for the code predictor next to the - talker's (`generation_config.json`). Today they're equal (0.9 / 50 / 1.0), so nothing is lost yet. - -What PR #7 does today is draw the decision inside the library, from the host's seed. That matches the -reference's lengths, and the continuous and flow families already draw their noise the same way. But it puts -sampling in the library, out of the host's control. - -## Proposal - -Append an optional override to the group, with an explicit flag (no "0 means inherit"): - -```c -struct codec_audio_lm_head_group { - bool penalties; - const int32_t * history; - int32_t n_history; - const int32_t * penalty_exempt; - int32_t n_penalty_exempt; - // new - bool own_sampling; // true: sample this group with the settings below, not the backbone's - float temp; // llama.cpp semantics (<= 0: greedy) - int32_t top_k; // llama.cpp semantics (<= 0: off) - float top_p; // llama.cpp semantics (1.0: off) -}; -``` - -The family fills them from model metadata: MOSS-Nano's text-slot group gets `{true, 1.5, 0, 1.0}`, and the -codebook group keeps `own_sampling = false`. A host that builds one sampler per group (as `tts_runner` already -does, `tts_runner.cpp:402`) applies the override when `own_sampling` is set. The user's `--temp` etc. keep -applying to groups without it. A user who wants a greedy run still gets one: `--temp 0` makes every group greedy. - -## Alternatives - -1. **Keep the library draw** (PR #7 as it stands): exact and needs no API change, but the library samples. -2. **Host sampling with logit scaling** (tried, measured above): no API change and no library sampling, but the - stop comes late. The smoke's 3 s English sentence ran to the 24 s frame cap. -3. **Logit scaling plus a high "top_p floor" hint** (a per-group `min top_p`): a narrower version of this - proposal, fixing only this case. -4. **A new verdict field** carrying sampling settings per SAMPLE_HEAD step: more flexible per step, but larger, - and every host's loop changes. - -## Compatibility - -- ABI: the struct grows at the end. Hosts compiled against the old header read the old fields at the same - offsets, but iterate `head_groups[g]` with the old stride, which breaks for `n_head_groups > 1`. So this needs a - version bump, or the array has to come through a size-carrying accessor (`codec_audio_lm_head_group_get(ctx, g, - &out, sizeof out)`), which keeps old binaries working. -- Source: existing hosts compile unchanged and ignore the new fields, so they get today's behaviour. -- Python: `_ffi.py` appends the four fields. - -## Migration - -1. Add the fields (or the accessor) and document them. -2. `tts_runner`: `HeadSampler::build` takes the group's settings when `own_sampling` is set. -3. MOSS-Nano: the text slot becomes its own head group (group 1) with `{1.5, top_k off, top_p 1.0}`, and the - logit scaling goes away. -4. Optional: Qwen3-TTS fills `subtalker_*` into its code-predictor group, from the converter. diff --git a/scripts/converters/lm_adaptor/moss_tts_local.py b/scripts/converters/lm_adaptor/moss_tts_local.py index c251493..ca70f68 100644 --- a/scripts/converters/lm_adaptor/moss_tts_local.py +++ b/scripts/converters/lm_adaptor/moss_tts_local.py @@ -411,9 +411,12 @@ def _dump_nano(writer, sd, cfg, *, verbose: bool) -> None: for k in ("audio_start", "audio_end", "audio_user_slot", "audio_assistant_slot"): writer.add_uint32(pre + k, ids[k]) writer.add_uint32(pre + "audio_pad", pad) - # inference(text_temperature): the text slot (the stop decision) is drawn at - # its own temperature, model-side (the family); <= 0 = argmax. + # inference(text_temperature, audio_temperature): the text slot (the stop + # decision) samples at 1.5; the host samples every head at the codebooks' + # temperature (general.sampling.temp = 1.7), so the family scales the slot's + # log-probabilities by audio_temperature. writer.add_float32(pre + "text_temperature", 1.5) + writer.add_float32(pre + "audio_temperature", 1.7) m = spm_pb2.ModelProto() m.ParseFromString(tok_path.read_bytes()) ns = m.normalizer_spec diff --git a/scripts/utils/sampling.py b/scripts/utils/sampling.py index 11a9c86..54b17e4 100644 --- a/scripts/utils/sampling.py +++ b/scripts/utils/sampling.py @@ -30,12 +30,12 @@ "moss_tts_realtime": dict(temp=0.8, top_k=30, top_p=0.6, min_p=0.0, penalty_repeat=1.1, penalty_last_n=50, samplers=_HF), "lfm2_audio": dict(temp=0.0, top_k=0, top_p=1.0, min_p=0.0), - # modeling_moss_tts_nano.py inference(do_sample=True): the audio codebooks' - # settings (audio_temperature / top_k / top_p, no repetition penalty). Its - # text slot (assistant slot vs audio end) uses temperature 1.5 / top_p 1.0; - # the family draws that one model-side (codec.lm.moss_tts_nano.text_temperature), - # every codebook head takes these (docs/models/moss_tts_nano.md). - "moss_tts_nano": dict(temp=1.7, top_k=25, top_p=0.8, min_p=0.0, samplers="temperature;top_k;top_p"), + # modeling_moss_tts_nano.py inference(do_sample=True): audio_temperature 1.7 / + # top_k 25 for the codebooks. top_p is 1.0, not the reference's audio_top_p + # 0.8: the text slot (the stop decision, temperature 1.5 / top_p 1.0) is + # sampled by the same host chain, and top_p < 1 would cut the end token + # (required setting, docs/models/moss_tts_nano.md). + "moss_tts_nano": dict(temp=1.7, top_k=25, top_p=1.0, min_p=0.0, samplers="temperature;top_k;top_p"), # tts.py::generate. mtl_tts.py uses repetition_penalty 2.0, but only with # its AlignmentStreamAnalyzer (attention-driven EOS forcing), which this # runtime does not have; without it 2.0 runs to max length on half the diff --git a/tests/e2e/moss_tts_nano_smoke.py b/tests/e2e/moss_tts_nano_smoke.py index 7a067c7..4552f45 100644 --- a/tests/e2e/moss_tts_nano_smoke.py +++ b/tests/e2e/moss_tts_nano_smoke.py @@ -35,7 +35,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) import codec_cpp # noqa: E402 -from _common import asr_cer, read_wav_mono_f32 # noqa: E402 +from _common import MODEL_SAMPLING, asr_cer, read_wav_mono_f32 # noqa: E402 M = REPO / "models" / "moss_tts_nano" CODEC = M / "moss_tts_nano_codec.gguf" @@ -65,7 +65,7 @@ def check_synth() -> bool: ok_all = True with codec_cpp.TTS(BACKBONE, CODEC) as tts: for name, text, lang, seed, cer_max in CASES: - audio, sr = tts.synthesize(text, ref_audio=REF_WAV, seed=seed) + audio, sr = tts.synthesize(text, ref_audio=REF_WAV, seed=seed, **MODEL_SAMPLING["moss_tts_nano"]) stop = tts.last_result["stop_reason"] a = audio if audio.ndim == 1 else audio.mean(axis=1) dur, rms = len(a) / sr, float(np.sqrt((a ** 2).mean())) From ef27658aa04f944d40efb53829b9bdee890c0343 Mon Sep 17 00:00:00 2001 From: Hans Date: Sun, 15 Nov 2026 00:31:56 +0800 Subject: [PATCH 11/11] docs(codec-common): codec_audio_lm holds no sampler again (MOSS-TTS-Nano stop is host-sampled) Co-Authored-By: Claude Opus 5.5 --- docs/codec_common_api.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/docs/codec_common_api.md b/docs/codec_common_api.md index 7d79a75..e499ce3 100644 --- a/docs/codec_common_api.md +++ b/docs/codec_common_api.md @@ -149,11 +149,8 @@ The host samples every token with llama.cpp's sampler: the backbone's, and each codec-side head's (`SAMPLE_HEAD` verdicts: `codec_audio_lm_head_logits` gives the head's logits, the model's constraints already applied as -inf and guidance already combined; `codec_audio_lm_head_token` takes the id back and -gives the next verdict). codec_audio_lm holds no token sampler and no sampling -settings (one exception: MOSS-TTS-Nano's text slot, a two-way stop decision the -reference draws at its own temperature, is drawn by the family from its own -stream seeded by `codec_audio_lm_set_seed`, and the host gets a one-hot head; -see models/moss_tts_nano.md); it only suggests constraints: `grammar` / `allowed` / +gives the next verdict). codec_audio_lm holds no sampler and no sampling +settings; it only suggests constraints: `grammar` / `allowed` / `penalty_exempt` for the backbone, and `head_groups` for the heads. Build one host sampler per group (one random stream and penalty history; seed group `g` with seed + 1 + g), with the same llama.cpp settings as the backbone; a group @@ -255,7 +252,7 @@ A family that needs something else entirely can still override both. |---|---|---|---| | `codebook` | CSM, Qwen3-TTS, MOSS-TTSD | CODEC_HEAD | depth decoder or delayed parallel heads; MOSS-TTSD samples codebook 0 from the backbone under a grammar | | `realtime` | MOSS-TTS-Realtime | CODEC_HEAD | text lane from the backbone's embedding table (`params.backbone_path`) | -| `moss_tts_nano` | MOSS-TTS-Nano | CODEC_HEAD | starcoder2 backbone; reference codes as voice rows; the depth decoder's text slot (drawn model-side) stops it | +| `moss_tts_nano` | MOSS-TTS-Nano | CODEC_HEAD | starcoder2 backbone; reference codes as voice rows; the depth decoder's text slot (continue / audio end, sampled by the host; requires top_p 1.0) stops it | | `lfm2` | LFM2-Audio | CODEC_HEAD | text warm-up from the tied embedding head (`verdict.token`), then audio frames | | `chatterbox` | Chatterbox T3, Turbo, Multilingual | CODEC_HEAD | guidance pair (`n_seq` 2) for T3 | | `cosyvoice` | CosyVoice 1/2/3, BreezyVoice | CODEC_HEAD | SFT / zero-shot / cross-lingual / instruct modes; v1 disables flash attention |