|
| 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