| 11 | |
| 12 | |
| 13 | class KimiAudioModel(MoonshotKimiaForCausalLM): |
| 14 | def __init__(self, config): |
| 15 | super().__init__(config) |
| 16 | self.whisper_model = WhisperEncoder("openai/whisper-large-v3", mel_batch_size=20, unfreeze_online_whisper_model=True) |
| 17 | |
| 18 | @classmethod |
| 19 | def init_from_pretrained(cls, model_name_or_path, model_load_kwargs): |
| 20 | if os.path.exists(model_name_or_path): |
| 21 | # local path |
| 22 | cache_path = model_name_or_path |
| 23 | else: |
| 24 | # cache everything if model_path is a model-id |
| 25 | cache_path = snapshot_download(model_name_or_path) |
| 26 | |
| 27 | audio_model = AutoModelForCausalLM.from_pretrained( |
| 28 | cache_path, |
| 29 | device_map=None, |
| 30 | torch_dtype=torch.bfloat16, trust_remote_code=True, **model_load_kwargs, |
| 31 | ) |
| 32 | |
| 33 | whisper_model = WhisperEncoder( |
| 34 | os.path.join(cache_path, "whisper-large-v3"), mel_batch_size=20, unfreeze_online_whisper_model=True |
| 35 | ) |
| 36 | kimia_model = cls(audio_model.config) |
| 37 | |
| 38 | # merge audio model and whisper model's state dict |
| 39 | pretrained_state_dict = audio_model.state_dict() |
| 40 | |
| 41 | for n, p in whisper_model.state_dict().items(): |
| 42 | pretrained_state_dict["whisper_model." + n] = p |
| 43 | |
| 44 | kimia_model.load_state_dict(pretrained_state_dict) |
| 45 | |
| 46 | return kimia_model |
| 47 | |
| 48 | @staticmethod |
| 49 | def export_model(input_dir, output_dir): |
| 50 | print("Loading model from {}".format(input_dir)) |
| 51 | kimiaudio = KimiAudioModel.from_pretrained(input_dir) |
| 52 | |
| 53 | print("Saving Kimi-Audio LM to {}".format(output_dir)) |
| 54 | audio_model = MoonshotKimiaForCausalLM(kimiaudio.config) |
| 55 | audio_model_state_dict = {k: v for k, v in kimiaudio.state_dict().items() if not k.startswith("whisper_model")} |
| 56 | audio_model.load_state_dict(audio_model_state_dict) |
| 57 | |
| 58 | audio_model.save_pretrained(output_dir) |
| 59 | |
| 60 | shutil.copyfile("finetune_codes/configuration_moonshot_kimia.py", os.path.join(output_dir, "configuration_moonshot_kimia.py")) |
| 61 | shutil.copyfile("finetune_codes/modeling_kimia.py", os.path.join(output_dir, "modeling_moonshot_kimia.py")) |
| 62 | |
| 63 | from kimia_infer.models.tokenizer.whisper_Lv3.whisper import WhisperModel |
| 64 | |
| 65 | whisper_model = WhisperModel.from_pretrained("openai/whisper-large-v3") |
| 66 | |
| 67 | kimiaudio_whisper_encoder_state_dict = {k.replace("speech_encoder.", "encoder."): v for k, v in kimiaudio.whisper_model.state_dict().items() if k.startswith("speech_encoder")} |
| 68 | |
| 69 | missing_keys, unexpected_keys = whisper_model.load_state_dict(kimiaudio_whisper_encoder_state_dict, strict=False) |
| 70 | assert len(unexpected_keys) == 0, f"Unexpected keys: {unexpected_keys}" |
nothing calls this directly
no outgoing calls
no test coverage detected