Skip to content

Commit fc504f9

Browse files
authored
mtmd: support higgs v3 STT and vibevoice-ASR (ggml-org#32329)
* mtmd: support higgs v3 and vibevoice-ASR * use proper mapping * address review comment * nits * rm hacky get_audio_length, add mtmd_helper_get_media_meta
1 parent 18b74fa commit fc504f9

24 files changed

Lines changed: 1101 additions & 18 deletions

‎common/chat.cpp‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -827,6 +827,11 @@ static std::string string_lower(std::string s) {
827827
return s;
828828
}
829829

830+
// VibeVoice-ASR: default system prompt of the template written by the converter
831+
static bool is_vibevoice_asr_template(const std::string & src) {
832+
return src.find("transcribes audio input into text output in JSON format") != std::string::npos;
833+
}
834+
830835
// LFM3-Audio: language code -> name
831836
static std::string lfm3_language_name(const std::string & language) {
832837
static const std::map<std::string, std::string> names = {
@@ -847,7 +852,8 @@ static std::string lfm3_asr_system_prompt(const std::string & language) {
847852
return "Perform ASR in " + lfm3_language_name(language) + ".";
848853
}
849854

850-
common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language) {
855+
common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language,
856+
double audio_length, const std::string & context) {
851857
common_chat_prompt_preset asr_preset;
852858
asr_preset.system = "";
853859
asr_preset.user = "Transcribe audio to text";
@@ -861,6 +867,17 @@ common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates
861867
asr_preset.system = lfm3_asr_system_prompt(language);
862868
asr_preset.user = "";
863869
asr_preset.has_language = true;
870+
} else if (is_vibevoice_asr_template(src)) {
871+
// without the audio length the model does not know where the audio ends and loops
872+
const char * keys = "transcribe it with these keys: Start time, End time, Speaker ID, Content";
873+
if (context.empty()) {
874+
asr_preset.user = string_format("\nThis is a %.2f seconds audio, please %s", audio_length, keys);
875+
} else {
876+
asr_preset.user = string_format("\nThis is a %.2f seconds audio, with extra info: %s\n\nPlease %s", audio_length, context.c_str(), keys);
877+
asr_preset.has_context = true;
878+
}
879+
asr_preset.media_first = true;
880+
asr_preset.needs_audio_length = true;
864881
}
865882
}
866883

‎common/chat.h‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -491,10 +491,16 @@ std::optional<common_chat_params> common_chat_try_specialized_template(
491491
struct common_chat_prompt_preset {
492492
std::string system;
493493
std::string user;
494-
bool has_language = false; // the preset already names the requested language
494+
bool has_language = false; // the preset already names the requested language
495+
bool has_context = false; // the user text already holds the context
496+
bool media_first = false; // the media goes before the user text
497+
bool needs_audio_length = false; // the user text depends on the audio length, call again with it
495498
};
496499

497-
common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language = "");
500+
// audio_length: in seconds, 0 if unknown
501+
// context: extra info from the user (e.g. names, hotwords), only used by some presets, see has_context
502+
common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language = "",
503+
double audio_length = 0.0, const std::string & context = "");
498504

499505
// prompt of the model's "tts" chat template for the text to speak, empty if the model has none
500506
// language and voice are optional, the template defines their defaults

‎conversion/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@
138138
"Grok1ForCausalLM": "grok",
139139
"GrokForCausalLM": "grok",
140140
"GroveMoeForCausalLM": "grovemoe",
141+
"HiggsAudio3Model": "higgs_audio",
141142
"HunYuanDenseV1ForCausalLM": "hunyuan",
142143
"HunYuanMoEV1ForCausalLM": "hunyuan",
143144
"HunYuanVLForConditionalGeneration": "hunyuan",
@@ -325,6 +326,7 @@
325326
"UMT5Model": "t5",
326327
"UltravoxModel": "ultravox",
327328
"UnlimitedOCRForCausalLM": "deepseek",
329+
"VibeVoiceAsrForConditionalGeneration": "vibevoice_asr",
328330
"VLlama3ForCausalLM": "llama",
329331
"VllmDecision2Model": "vllm_decision2",
330332
"VoxtralForConditionalGeneration": "llama",
@@ -372,6 +374,7 @@
372374
"Granite4VisionForConditionalGeneration": "granite",
373375
"GraniteSpeechForConditionalGeneration": "granite",
374376
"GraniteSpeechPlusForConditionalGeneration": "granite",
377+
"HiggsAudio3Model": "higgs_audio",
375378
"HunYuanVLForConditionalGeneration": "hunyuan",
376379
"Idefics3ForConditionalGeneration": "smolvlm",
377380
"Inkling2ForConditionalGeneration": "inkling2",
@@ -431,6 +434,7 @@
431434
"Step3p7ForConditionalGeneration": "step3",
432435
"UltravoxModel": "ultravox",
433436
"UnlimitedOCRForCausalLM": "deepseek",
437+
"VibeVoiceAsrForConditionalGeneration": "vibevoice_asr",
434438
"VoxtralForConditionalGeneration": "ultravox",
435439
"VoxtralRealtimeForConditionalGeneration": "ultravox",
436440
"YoutuVLForConditionalGeneration": "youtuvl",

‎conversion/base.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3475,7 +3475,7 @@ def get_model_architecture(hparams: dict[str, Any], model_type: ModelType) -> st
34753475
# Kimi-K3's text_config reports "KimiLinearForCausalLM", which is the older
34763476
# Kimi-Linear-48B architecture and cannot load K3 (no attention residuals,
34773477
# latent MoE, situ, ...). Route on the top-level architecture instead.
3478-
if model_type == ModelType.TEXT and arch in ("NEOChatModel", "StepVLForConditionalGeneration", "Sarashina2VisionForCausalLM", "Exaone4_5_ForConditionalGeneration", "Step3p7ForConditionalGeneration", "KimiK3ForConditionalGeneration", "KimiK31ForConditionalGeneration", "Nemotron3_5TranscribeForConditionalGeneration"):
3478+
if model_type == ModelType.TEXT and arch in ("NEOChatModel", "StepVLForConditionalGeneration", "Sarashina2VisionForCausalLM", "Exaone4_5_ForConditionalGeneration", "Step3p7ForConditionalGeneration", "KimiK3ForConditionalGeneration", "KimiK31ForConditionalGeneration", "Nemotron3_5TranscribeForConditionalGeneration", "HiggsAudio3Model"):
34793479
return arch
34803480

34813481
# if "architectures" is found in the sub-config, use that instead

‎conversion/higgs_audio.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
from __future__ import annotations
2+
3+
from typing import Any, Callable, TYPE_CHECKING
4+
5+
if TYPE_CHECKING:
6+
from torch import Tensor
7+
8+
from .base import ModelBase, gguf
9+
from .qwen import Qwen3Model
10+
from .ultravox import WhisperEncoderModel
11+
12+
13+
# plain ChatML as built by transcribe.py upstream, the Qwen3 template renders past assistant turns differently from the last one
14+
HIGGS_AUDIO_CHAT_TEMPLATE = (
15+
"{%- for message in messages -%}"
16+
"{{- '<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>\\n' -}}"
17+
"{%- endfor -%}"
18+
"{%- if add_generation_prompt -%}"
19+
"{{- '<|im_start|>assistant\\n' -}}"
20+
"{%- if enable_thinking is defined and enable_thinking is false -%}"
21+
"{{- '<think>\\n\\n</think>\\n\\n' -}}"
22+
"{%- endif -%}"
23+
"{%- endif -%}"
24+
)
25+
26+
27+
@ModelBase.register("HiggsAudio3Model")
28+
@ModelBase.example("bosonai/higgs-audio-v3-stt")
29+
class HiggsAudioModel(Qwen3Model):
30+
model_arch = gguf.MODEL_ARCH.QWEN3
31+
32+
def set_vocab(self):
33+
super().set_vocab()
34+
self.gguf_writer.add_chat_template(HIGGS_AUDIO_CHAT_TEMPLATE)
35+
36+
@classmethod
37+
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
38+
name, gen = item
39+
40+
# the audio_* tensors are dropped by TextModel, rename the text head before that
41+
if name == "audio_decoder_proj.text_lm_head.weight":
42+
name = "lm_head.weight"
43+
else:
44+
name = "model." + name
45+
46+
return super().filter_tensors((name, gen))
47+
48+
49+
@ModelBase.register("HiggsAudio3Model")
50+
class HiggsAudioWhisperEncoderModel(WhisperEncoderModel):
51+
has_vision_encoder = False
52+
has_audio_encoder = True
53+
54+
def get_audio_config(self) -> dict[str, Any] | None:
55+
return self.global_config["audio_encoder_config"]
56+
57+
def tensor_force_quant(self, name, new_name, bid, n_dims):
58+
# depthwise conv kernel, same as the whisper convs
59+
if name == "audio_encoder_proj.temporal.weight":
60+
return gguf.GGMLQuantizationType.F16
61+
return super().tensor_force_quant(name, new_name, bid, n_dims)
62+
63+
def set_gguf_parameters(self):
64+
assert self.global_config["projector_type"] == "mlp" and self.global_config["projector_temporal_downsample"] == 2
65+
assert self.global_config["audio_adapter_type"] == "stack" and not self.global_config.get("duplicate_audio_triplet", False)
66+
super().set_gguf_parameters()
67+
self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.HIGGS_AUDIO)
68+
69+
@classmethod
70+
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
71+
name, _ = item
72+
if not name.startswith(("audio_tower.", "audio_encoder_proj.")):
73+
return None
74+
return super().filter_tensors(item)

‎conversion/vibevoice_asr.py‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
from __future__ import annotations
2+
3+
from typing import Any, Callable, Iterable, TYPE_CHECKING
4+
5+
if TYPE_CHECKING:
6+
from torch import Tensor
7+
8+
from .base import MmprojModel, ModelBase, gguf
9+
from .qwen import Qwen2Model
10+
11+
12+
# the upstream chat_template.jinja is a processor template (list content, audio parts), use plain ChatML with its default system prompt
13+
VIBEVOICE_ASR_CHAT_TEMPLATE = (
14+
"{%- if messages[0]['role'] == 'system' -%}"
15+
"{{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' -}}"
16+
"{%- set loop_messages = messages[1:] -%}"
17+
"{%- else -%}"
18+
"{{- '<|im_start|>system\\nYou are a helpful assistant that transcribes audio input into text output in JSON format.<|im_end|>\\n' -}}"
19+
"{%- set loop_messages = messages -%}"
20+
"{%- endif -%}"
21+
"{%- for message in loop_messages -%}"
22+
"{{- '<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>\\n' -}}"
23+
"{%- endfor -%}"
24+
"{%- if add_generation_prompt -%}"
25+
"{{- '<|im_start|>assistant\\n' -}}"
26+
"{%- endif -%}"
27+
)
28+
29+
30+
@ModelBase.register("VibeVoiceAsrForConditionalGeneration")
31+
@ModelBase.example("microsoft/VibeVoice-ASR-HF")
32+
class VibeVoiceAsrModel(Qwen2Model):
33+
model_arch = gguf.MODEL_ARCH.QWEN2
34+
35+
def set_vocab(self):
36+
super().set_vocab()
37+
self.gguf_writer.add_chat_template(VIBEVOICE_ASR_CHAT_TEMPLATE)
38+
39+
@classmethod
40+
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
41+
name, _ = item
42+
if not name.startswith("language_model."):
43+
return None
44+
return super().filter_tensors(item)
45+
46+
47+
@ModelBase.register("VibeVoiceAsrForConditionalGeneration")
48+
class VibeVoiceAsrAudioModel(MmprojModel):
49+
has_vision_encoder = False
50+
has_audio_encoder = True
51+
52+
# values hard-coded in tools/mtmd/models/vibevoice-asr.cpp
53+
_encoder_consts = {"channels": 1, "kernel_size": 7, "num_filters": 32, "ffn_expansion": 4, "hidden_act": "gelu", "rms_norm_eps": 1e-5}
54+
_encoders = ("acoustic_tokenizer_encoder", "semantic_tokenizer_encoder")
55+
56+
def get_audio_config(self) -> dict[str, Any] | None:
57+
c = self.global_config["acoustic_tokenizer_encoder_config"]
58+
return {
59+
**c,
60+
"intermediate_size": c["ffn_expansion"] * c["hidden_size"],
61+
"num_attention_heads": 1,
62+
"num_hidden_layers": sum(c["depths"]),
63+
}
64+
65+
def set_gguf_parameters(self):
66+
super().set_gguf_parameters()
67+
for enc in self._encoders:
68+
c = self.global_config[f"{enc}_config"]
69+
for k, v in self._encoder_consts.items():
70+
assert c[k] == v, f"{enc}.{k} = {c[k]}, expected {v}"
71+
assert c["depths"] == self.hparams["depths"] and c["downsampling_ratios"] == self.hparams["downsampling_ratios"]
72+
73+
self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.VIBEVOICE_ASR)
74+
# the input is the raw waveform, one channel takes the place of the mel bins
75+
self.gguf_writer.add_audio_num_mel_bins(1)
76+
self.gguf_writer.add_audio_attention_layernorm_eps(self.hparams["rms_norm_eps"])
77+
self.gguf_writer.add_audio_conv_kernel_size(self.hparams["kernel_size"])
78+
# stride of each stage, the stem has none
79+
self.gguf_writer.add_audio_patch_sizes([1] + [int(r) for r in self.hparams["downsampling_ratios"]])
80+
self.gguf_writer.add_audio_depths([int(d) for d in self.hparams["depths"]])
81+
82+
def tensor_force_quant(self, name, new_name, bid, n_dims):
83+
if ".dw." in new_name:
84+
return gguf.GGMLQuantizationType.F32 # ggml_ssm_conv
85+
if ".conv." in new_name and new_name.endswith(".weight"):
86+
return gguf.GGMLQuantizationType.F16
87+
return super().tensor_force_quant(name, new_name, bid, n_dims)
88+
89+
@classmethod
90+
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
91+
name, _ = item
92+
if not name.startswith(cls._encoders + ("multi_modal_projector.",)):
93+
return None
94+
return super().filter_tensors(item)
95+
96+
_block_tensors = {
97+
"norm.weight": gguf.MODEL_TENSOR.A_ENC_CNX_NORM,
98+
"mixer.conv.weight": gguf.MODEL_TENSOR.A_ENC_CNX_DW,
99+
"mixer.conv.bias": gguf.MODEL_TENSOR.A_ENC_CNX_DW,
100+
"gamma": gguf.MODEL_TENSOR.A_ENC_CNX_LS1,
101+
"ffn_norm.weight": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_NORM,
102+
"ffn.linear1.weight": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_UP,
103+
"ffn.linear1.bias": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_UP,
104+
"ffn.linear2.weight": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_DOWN,
105+
"ffn.linear2.bias": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_DOWN,
106+
"ffn_gamma": gguf.MODEL_TENSOR.A_ENC_CNX_LS2,
107+
}
108+
109+
# mm.a.mlp.{0,1} + mm.a.mlp_norm.0 for the acoustic connector, {2,3} + 2 for the semantic one
110+
_proj_tensors = {
111+
"acoustic_linear_1": (gguf.MODEL_TENSOR.A_MMPROJ, 0),
112+
"acoustic_norm": (gguf.MODEL_TENSOR.A_MMPROJ_NORM, 0),
113+
"acoustic_linear_2": (gguf.MODEL_TENSOR.A_MMPROJ, 1),
114+
"semantic_linear_1": (gguf.MODEL_TENSOR.A_MMPROJ, 2),
115+
"semantic_norm": (gguf.MODEL_TENSOR.A_MMPROJ_NORM, 2),
116+
"semantic_linear_2": (gguf.MODEL_TENSOR.A_MMPROJ, 3),
117+
}
118+
119+
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
120+
# the layer scales (gamma) have no suffix upstream
121+
suffix = "." + name.rsplit(".", 1)[-1] if name.endswith((".weight", ".bias")) else ".weight"
122+
123+
if name.startswith("multi_modal_projector."):
124+
key, idx = self._proj_tensors[name.split(".")[1]]
125+
yield (self.format_tensor_name(key, idx, suffix=suffix), data_torch)
126+
return
127+
128+
enc, _, rest = name.partition(".")
129+
enc_id = self._encoders.index(enc)
130+
parts = rest.split(".")
131+
depths = [int(d) for d in self.hparams["depths"]]
132+
133+
# causal convs of the stages: 0 = stem, 1..6 = downsample, 7 = head
134+
if rest.startswith("stem.conv."):
135+
conv_id = 0
136+
elif parts[0] == "conv_layers" and parts[2] == "conv":
137+
conv_id = int(parts[1]) + 1
138+
elif parts[0] == "head":
139+
conv_id = len(depths)
140+
else:
141+
conv_id = None
142+
if conv_id is not None:
143+
yield (gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.A_ENC_CNX_CONV].format(bid=enc_id, xid=conv_id) + suffix, data_torch)
144+
return
145+
146+
# ConvNeXt blocks are numbered per stage upstream and flat here
147+
if parts[0] == "stem":
148+
stage, blk, tail = 0, int(parts[2]), ".".join(parts[3:])
149+
else:
150+
assert parts[0] == "conv_layers" and parts[2] == "stage", name
151+
stage, blk, tail = int(parts[1]) + 1, int(parts[3]), ".".join(parts[4:])
152+
xid = sum(depths[:stage]) + blk
153+
154+
key = self._block_tensors[tail]
155+
if key == gguf.MODEL_TENSOR.A_ENC_CNX_DW and tail.endswith(".weight"):
156+
data_torch = data_torch.squeeze(1) # [C, 1, K] -> [C, K] for ggml_ssm_conv
157+
yield (gguf.TENSOR_NAMES[key].format(bid=enc_id, xid=xid) + suffix, data_torch)

0 commit comments

Comments
 (0)