Skip to content

Commit 9912c04

Browse files
hans00claude
andcommitted
converters: sampling goes to the backbone GGUF's general.sampling.*
convert-backbone-to-gguf.py writes each model's recommended sampling (scripts/utils/sampling.py) as llama.cpp's general.sampling.* keys; scripts/set-backbone-sampling.py writes them into an existing backbone (upstream ones included). The codec converters stop writing codec.lm.*.sampling / presets / RAS / temperature keys; BlueMagpie's CFM steps and guidance become codec.lm.cfm_n_timesteps / cfm_cfg_value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7f49314 commit 9912c04

8 files changed

Lines changed: 89 additions & 33 deletions

File tree

‎scripts/convert-backbone-to-gguf.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1098,6 +1098,46 @@ def run_llama_cpp_converter(
10981098
sys.path[:] = saved_path
10991099

11001100

1101+
_ARCH_SAMPLING = {
1102+
"CsmForConditionalGeneration": "csm",
1103+
"Qwen3TTSForConditionalGeneration": "qwen3_tts",
1104+
"MossTTSDForCausalLM": "moss_ttsd",
1105+
"AsteroidTTSModel": "moss_ttsd",
1106+
"MossTTSRealtime": "moss_tts_realtime",
1107+
"Lfm2AudioForConditionalGeneration": "lfm2_audio",
1108+
"KittenTTS2": "kitten_tts2",
1109+
"CosyVoice": "cosyvoice",
1110+
"Soprano": "soprano",
1111+
}
1112+
1113+
1114+
def sampling_model(arch: str, src: Path, model_id: str) -> str | None:
1115+
"""The scripts/utils/sampling.py entry of a backbone (None: no TTS sampling)."""
1116+
if arch == "ChatterboxT3":
1117+
return "chatterbox_turbo" if _chatterbox_find_t3_safetensors(src).name == "t3_turbo_v1.safetensors" \
1118+
else "chatterbox"
1119+
if arch in ("CosyVoice1", "CosyVoice") and "breezy" in model_id.lower():
1120+
return "breezyvoice"
1121+
if arch == "CosyVoice1":
1122+
return "cosyvoice"
1123+
if arch == "PocketTTS":
1124+
return "pocket_tts"
1125+
return _ARCH_SAMPLING.get(arch)
1126+
1127+
1128+
def write_sampling(output: Path, model: str | None) -> None:
1129+
"""Rewrite the backbone GGUF with the model's general.sampling.* keys."""
1130+
if model is None:
1131+
return
1132+
here = Path(__file__).resolve().parent
1133+
sys.path[:0] = [str(here), str(here.parent / "common" / "third-party" / "llama.cpp" / "gguf-py")]
1134+
from utils.sampling import add_sampling_to_gguf
1135+
tmp = output.with_name(output.name + ".sampling.tmp")
1136+
add_sampling_to_gguf(output, tmp, model)
1137+
tmp.replace(output)
1138+
print(f"[bb] general.sampling.*: {model}", flush=True)
1139+
1140+
11011141
def load_config(src: Path) -> dict:
11021142
return json.loads((src / "config.json").read_text())
11031143

@@ -1123,12 +1163,14 @@ def main() -> int:
11231163
if (src / "cosyvoice.yaml").is_file(): # CosyVoice v1: custom arch, written directly
11241164
args.output.parent.mkdir(parents=True, exist_ok=True)
11251165
write_cosyvoice1_backbone(src, args.output, args.outtype)
1166+
write_sampling(args.output, sampling_model("CosyVoice1", src, args.model_id))
11261167
print(f"[bb] wrote {args.output}", flush=True)
11271168
return 0
11281169
pocket = pocket_tts_checkpoint(src)
11291170
if pocket is not None: # Pocket-TTS: stock starcoder2, written directly
11301171
args.output.parent.mkdir(parents=True, exist_ok=True)
11311172
write_pocket_tts_backbone(pocket, args.output, args.outtype)
1173+
write_sampling(args.output, sampling_model("PocketTTS", src, args.model_id))
11321174
print(f"[bb] wrote {args.output}", flush=True)
11331175
return 0
11341176
if chatterbox_layout_detected(src):
@@ -1157,6 +1199,7 @@ def main() -> int:
11571199
print(f"[bb] running llama.cpp converter …", flush=True)
11581200
run_llama_cpp_converter(hf_dir, args.output, Path(args.llama_cpp),
11591201
args.outtype, patches)
1202+
write_sampling(args.output, sampling_model(arch, src, args.model_id))
11601203

11611204
print(f"[bb] wrote {args.output}", flush=True)
11621205
return 0

‎scripts/converters/bluemagpie.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,9 @@ def add_minicpm_stack(src: str, out: str, n_layers: int) -> None:
426426
writer.add_float32("codec.lm.rms_eps", cfg["rms_eps"])
427427
writer.add_float32("codec.lm.cfm_sigma_min", float(cfg["cfm"]["sigma_min"]))
428428
writer.add_string("codec.lm.cfm_solver", str(cfg["cfm"]["solver"]))
429+
# Decoder graph settings of VoxCPM.generate (inference_timesteps, cfg_value).
430+
writer.add_uint32("codec.lm.cfm_n_timesteps", 10)
431+
writer.add_float32("codec.lm.cfm_cfg_value", 2.0)
429432
# speaker section: the SpeakerProjector weights ship in the GGUF
430433
# (lm.speaker.*), but the ECAPA centroid front-end isn't wired into the
431434
# codec_lm speaker API yet, so don't advertise a speaker encoder.

‎scripts/converters/cosyvoice.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,6 @@ def load_from_checkpoint(self, checkpoint_dir: Path) -> None:
421421
cfg["mel_fmax"] = float(fmax) if fmax not in (None, "null") else cfg["sample_rate"] / 2
422422
cfg["mel_n_fft"] = int(_yaml_scalar(feat, "n_fft") or 1024)
423423
cfg["mel_hop"] = int(_yaml_scalar(feat, "hop_size") or 256)
424-
cfg["ras_sampling"] = "ras_sampling" in yaml_text
425424
self.config = cfg
426425

427426
self.flow = _load_pt(d / "flow.pt")

‎scripts/converters/kitten_tts2.py‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -116,20 +116,13 @@ def _write_extra_encoders(self, writer: GGUFWriter) -> None:
116116
self._write_lm_contract(writer)
117117

118118
def _write_lm_contract(self, writer: GGUFWriter) -> None:
119-
"""Prompt layout + sampling the host runner needs (kittenml defaults)."""
119+
"""Prompt layout the host runner needs (kittenml defaults); the sampling
120+
(decode presets, repetition / token-run penalties) is the backbone GGUF's."""
120121
cfg = self.kitten_cfg
121122
p = "codec.lm.kitten."
122123
for key, val in cfg["token_map"].items():
123124
writer.add_uint32(p + "token." + key, int(val))
124125
gen = cfg.get("generation", {})
125-
writer.add_string(p + "default_preset", cfg.get("default_preset", "stable"))
126-
for name, preset in cfg.get("decode_presets", {}).items():
127-
for k in ("temperature", "top_p", "top_k", "min_p"):
128-
writer.add_float32(f"{p}preset.{name}.{k}", float(preset.get(k, 0.0)))
129-
writer.add_float32(p + "repetition_penalty", 1.1)
130-
writer.add_uint32(p + "repetition_window", int(gen.get("repetition_window", 50)))
131-
writer.add_float32(p + "token_run_penalty", 1.3)
132-
writer.add_uint32(p + "token_run_grace", 10)
133126
writer.add_uint32(p + "silence_token", 4299)
134127
writer.add_uint32(p + "n_trailing_silence", 3)
135128
writer.add_bool(p + "use_reference_prompt", bool(gen.get("use_reference_prompt", True)))

‎scripts/converters/lm_adaptor/chatterbox.py‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -167,15 +167,8 @@ def dump(writer, sd: Dict[str, np.ndarray], cfg: Dict[str, Any],
167167
writer.add_uint32 ("codec.lm.chatterbox.speaker_embed_dim",
168168
SPEAKER_EMBED_DIM)
169169
writer.add_uint32 ("codec.lm.chatterbox.cond_len", COND_LEN)
170-
# Reference sampling regime (tts.py::generate defaults). mtl_tts.py uses
171-
# repetition_penalty=2.0, but only together with its AlignmentStreamAnalyzer
172-
# (attention-driven EOS forcing), which this runtime does not have: without
173-
# it 2.0 runs to max length on half the test sentences, so both variants
174-
# keep 1.2.
175-
writer.add_float32("codec.lm.chatterbox.sampling.temperature", 0.8)
176-
writer.add_float32("codec.lm.chatterbox.sampling.top_p", 1.0)
177-
writer.add_float32("codec.lm.chatterbox.sampling.min_p", 0.05)
178-
writer.add_float32("codec.lm.chatterbox.sampling.repetition_penalty", 1.2)
170+
# Guidance weight of the T3 pair (tts.py::generate's cfg_weight), a decoder
171+
# setting; the sampling itself is the backbone GGUF's general.sampling.*.
179172
writer.add_float32("codec.lm.chatterbox.sampling.cfg_weight", 0.5)
180173

181174
# ---- speech embed + head (the n_cb=1 codec_lm pair) --------------
@@ -295,12 +288,7 @@ def dump_turbo(writer, sd: Dict[str, np.ndarray], cfg: Dict[str, Any],
295288
writer.add_uint32 ("codec.lm.chatterbox.speaker_embed_dim", SPEAKER_EMBED_DIM)
296289
writer.add_uint32 ("codec.lm.chatterbox.silence_token", TURBO_SILENCE_TOKEN)
297290
writer.add_uint32 ("codec.lm.chatterbox.n_trailing_silence", TURBO_N_TRAILING_SIL)
298-
# Reference sampling regime (tts_turbo.py::generate defaults).
299-
writer.add_float32("codec.lm.chatterbox.sampling.temperature", 0.8)
300-
writer.add_int32 ("codec.lm.chatterbox.sampling.top_k", 1000)
301-
writer.add_float32("codec.lm.chatterbox.sampling.top_p", 0.95)
302-
writer.add_float32("codec.lm.chatterbox.sampling.min_p", 0.0)
303-
writer.add_float32("codec.lm.chatterbox.sampling.repetition_penalty", 1.2)
291+
# Turbo has no guidance pair; its sampling is the backbone GGUF's.
304292
writer.add_float32("codec.lm.chatterbox.sampling.cfg_weight", 0.0)
305293

306294
_emit(writer, "lm.audio_embd_0.weight", _require(sd, "speech_emb.weight"),

‎scripts/converters/lm_adaptor/cosyvoice.py‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,6 @@ def dump_cosyvoice_lm(writer, ckpt_dir: Path, cfg: Dict[str, Any],
8484
w.add_uint32(p + "ignore_eos_id", speech_tokens)
8585
w.add_float32(p + "min_token_text_ratio", 2.0)
8686
w.add_float32(p + "max_token_text_ratio", 20.0)
87-
ras = bool(cfg.get("ras_sampling", True))
88-
w.add_string(p + "sampling", "ras" if ras else "top_k")
89-
w.add_uint32(p + "top_k", 25)
90-
w.add_float32(p + "top_p", 0.8)
91-
w.add_uint32(p + "win_size", 10)
92-
w.add_float32(p + "tau_r", 0.1)
9387
w.add_bool(p + "text_in_backbone", v != 1)
9488
if v == 3:
9589
w.add_array(p + "silent_tokens", V3_SILENT_TOKENS)

‎scripts/converters/pocket_tts.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,6 @@ def load_from_checkpoint(self, checkpoint_dir: Path) -> None:
141141
"ldim": 32, # latent dim (= quantizer.dimension)
142142
# LSD / EOS decode defaults (default_parameters.py)
143143
"lsd_decode_steps": 1,
144-
"temperature": 0.7,
145144
"eos_threshold": -4.0,
146145
"noise_clamp": 0.0, # None -> 0 sentinel (unused = no clamp)
147146
"frames_after_eos": -1, # DEFAULT_FRAMES_AFTER_EOS = None -> -1
@@ -388,7 +387,6 @@ def add_lin(src: str, out: str, bias: bool) -> None:
388387
writer.add_bool("codec.lm.insert_bos_before_voice", bool(cfg["insert_bos_before_voice"]))
389388
# LSD / EOS defaults + semantics.
390389
writer.add_uint32("codec.lm.lsd_decode_steps", cfg["lsd_decode_steps"])
391-
writer.add_float32("codec.lm.temperature", float(cfg["temperature"]))
392390
writer.add_float32("codec.lm.eos_threshold", float(cfg["eos_threshold"]))
393391
writer.add_float32("codec.lm.noise_clamp", float(cfg["noise_clamp"]))
394392
writer.add_int32("codec.lm.frames_after_eos", int(cfg["frames_after_eos"]))

‎scripts/set-backbone-sampling.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#!/usr/bin/env python3
2+
"""Write a model's recommended sampling (general.sampling.*) into a backbone GGUF.
3+
4+
scripts/set-backbone-sampling.py --model qwen3_tts in.gguf out.gguf
5+
6+
The values are scripts/utils/sampling.py's MODEL_SAMPLING; convert-backbone-to-gguf.py
7+
writes them on conversion, this tool updates an existing backbone (including
8+
upstream ones such as OuteTTS / NeuTTS). `out` may not be `in`.
9+
"""
10+
11+
from __future__ import annotations
12+
13+
import argparse
14+
import sys
15+
from pathlib import Path
16+
17+
REPO = Path(__file__).resolve().parents[1]
18+
sys.path.insert(0, str(REPO / "common" / "third-party" / "llama.cpp" / "gguf-py"))
19+
sys.path.insert(0, str(REPO / "scripts"))
20+
21+
from utils.sampling import MODEL_SAMPLING, add_sampling_to_gguf # noqa: E402
22+
23+
24+
def main() -> int:
25+
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
26+
ap.add_argument("--model", required=True, choices=sorted(MODEL_SAMPLING))
27+
ap.add_argument("input", type=Path)
28+
ap.add_argument("output", type=Path)
29+
a = ap.parse_args()
30+
if a.input.resolve() == a.output.resolve():
31+
raise SystemExit("output must differ from input")
32+
add_sampling_to_gguf(a.input, a.output, a.model)
33+
print(f"wrote {a.output} with {a.model}'s sampling: {MODEL_SAMPLING[a.model]}")
34+
return 0
35+
36+
37+
if __name__ == "__main__":
38+
raise SystemExit(main())

0 commit comments

Comments
 (0)