happyme531 commited on
Commit
e11f7fb
·
verified ·
1 Parent(s): 3848825

Upload 68 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +15 -0
  2. README.md +232 -3
  3. audio_vae_decode.rknn +3 -0
  4. audio_vae_encode.rknn +3 -0
  5. base_lm.rkllm +3 -0
  6. basic_ref_zh.wav +3 -0
  7. config.json +60 -0
  8. convert/MiniCPM4-0.5B/added_tokens.json +10 -0
  9. convert/MiniCPM4-0.5B/config.json +37 -0
  10. convert/MiniCPM4-0.5B/configuration_minicpm.py +203 -0
  11. convert/MiniCPM4-0.5B/generation_config.json +12 -0
  12. convert/MiniCPM4-0.5B/modeling_minicpm.py +1514 -0
  13. convert/MiniCPM4-0.5B/special_tokens_map.json +33 -0
  14. convert/MiniCPM4-0.5B/tokenizer.json +0 -0
  15. convert/MiniCPM4-0.5B/tokenizer.model +3 -0
  16. convert/MiniCPM4-0.5B/tokenizer_config.json +117 -0
  17. convert/README.md +53 -0
  18. convert/scripts/build_rk3588_pipeline.py +290 -0
  19. convert/scripts/convert_vox_minicpm_to_hf.py +120 -0
  20. convert/scripts/export_onnx.py +297 -0
  21. convert/scripts/export_rkllm.py +65 -0
  22. convert/src/voxcpm/__init__.py +5 -0
  23. convert/src/voxcpm/cli.py +308 -0
  24. convert/src/voxcpm/core.py +282 -0
  25. convert/src/voxcpm/model/__init__.py +3 -0
  26. convert/src/voxcpm/model/utils.py +122 -0
  27. convert/src/voxcpm/model/voxcpm.py +972 -0
  28. convert/src/voxcpm/modules/__init__.py +0 -0
  29. convert/src/voxcpm/modules/audiovae/__init__.py +1 -0
  30. convert/src/voxcpm/modules/audiovae/audio_vae.py +377 -0
  31. convert/src/voxcpm/modules/layers/__init__.py +1 -0
  32. convert/src/voxcpm/modules/layers/lora.py +133 -0
  33. convert/src/voxcpm/modules/layers/scalar_quantization_layer.py +26 -0
  34. convert/src/voxcpm/modules/locdit/__init__.py +2 -0
  35. convert/src/voxcpm/modules/locdit/local_dit.py +114 -0
  36. convert/src/voxcpm/modules/locdit/unified_cfm.py +231 -0
  37. convert/src/voxcpm/modules/locenc/__init__.py +1 -0
  38. convert/src/voxcpm/modules/locenc/local_encoder.py +30 -0
  39. convert/src/voxcpm/modules/minicpm4/__init__.py +3 -0
  40. convert/src/voxcpm/modules/minicpm4/cache.py +47 -0
  41. convert/src/voxcpm/modules/minicpm4/config.py +29 -0
  42. convert/src/voxcpm/modules/minicpm4/model.py +473 -0
  43. convert/src/voxcpm/training/__init__.py +28 -0
  44. convert/src/voxcpm/training/accelerator.py +166 -0
  45. convert/src/voxcpm/training/config.py +40 -0
  46. convert/src/voxcpm/training/data.py +216 -0
  47. convert/src/voxcpm/training/packers.py +289 -0
  48. convert/src/voxcpm/training/state.py +21 -0
  49. convert/src/voxcpm/training/tracker.py +79 -0
  50. convert/src/voxcpm/utils/text_normalize.py +185 -0
.gitattributes CHANGED
@@ -33,3 +33,18 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ audio_vae_decode.rknn filter=lfs diff=lfs merge=lfs -text
37
+ audio_vae_encode.rknn filter=lfs diff=lfs merge=lfs -text
38
+ base_lm.rkllm filter=lfs diff=lfs merge=lfs -text
39
+ basic_ref_zh.wav filter=lfs diff=lfs merge=lfs -text
40
+ dit_step.rknn filter=lfs diff=lfs merge=lfs -text
41
+ fsq_layer.rknn filter=lfs diff=lfs merge=lfs -text
42
+ librkllmrt.so filter=lfs diff=lfs merge=lfs -text
43
+ lm_to_dit_proj.rknn filter=lfs diff=lfs merge=lfs -text
44
+ locenc_1.rknn filter=lfs diff=lfs merge=lfs -text
45
+ locenc_64.rknn filter=lfs diff=lfs merge=lfs -text
46
+ res_to_dit_proj.rknn filter=lfs diff=lfs merge=lfs -text
47
+ residual_lm.rkllm filter=lfs diff=lfs merge=lfs -text
48
+ rknn_output_zh.wav filter=lfs diff=lfs merge=lfs -text
49
+ rknn_output.wav filter=lfs diff=lfs merge=lfs -text
50
+ stop_head.rknn filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,232 @@
1
- ---
2
- license: agpl-3.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: agpl-3.0
3
+ language:
4
+ - en
5
+ - zh
6
+ base_model:
7
+ - openbmb/VoxCPM1.5
8
+ pipeline_tag: text-to-speech
9
+ tags:
10
+ - rknn
11
+ - rkllm
12
+ - text-to-speech
13
+ - speech
14
+ - speech generation
15
+ - voice cloning
16
+ ---
17
+
18
+ # VoxCPM1.5-RKNN2
19
+
20
+ ### (English README see below)
21
+
22
+ > VoxCPM 是一种创新的无分词器文本转语音(TTS)系统,重新定义了语音合成的真实感。通过在连续空间中建模语音,它克服了离散标记化的局限,并实现了两项核心能力:上下文感知的语音生成和逼真的零样本语音克隆。
23
+ > 不同于将语音转换为离散标记的主流方法,VoxCPM 采用端到端的扩散自回归架构,直接从文本生成连续的语音表示。它基于 MiniCPM-4 主干构建,通过分层语言建模和 FSQ 约束实现了隐式的语义-声学解耦,极大地提升了表现力和生成稳定性。
24
+
25
+ 我们非常激动地推出 VoxCPM 的重大升级版本。此次更新在显著提升音频质量和效率的同时,保留了核心的上下文感知语音生成和零样本(Zero-shot)语音克隆能力。
26
+
27
+ | 特性 | VoxCPM | VoxCPM1.5 |
28
+ |---------|------------|------------|
29
+ | **Audio VAE 采样率** | 16kHz | 44.1kHz |
30
+ | **LM Token 速率** | 12.5Hz | 6.25Hz |
31
+ | **Patch 大小** | 2 | 4 |
32
+ | **SFT 支持** | ✅ | ✅ |
33
+ | **LoRA 支持** | ✅ | ✅ |
34
+
35
+
36
+ - 推理速度(RKNN2):RK3588上RTF约4.5(生成10s音频需要推理45s,相对于旧版似乎并没有什么提升)
37
+ - 大致内存占用(RKNN2):约3.3GB(相对于旧版同样没有什么提升)
38
+
39
+ ## 使用方法
40
+
41
+ 1. 克隆项目到本地
42
+
43
+ 2. 安装依赖
44
+
45
+ ```bash
46
+ pip install numpy scipy soundfile tqdm transformers sentencepiece ztu-somemodelruntime-ez-rknn-async
47
+ ```
48
+
49
+ 3. 运行
50
+
51
+ ```bash
52
+ python onnx_infer-rknn2.py --onnx-dir . --tokenizer-dir . --base-hf-dir . --residual-hf-dir . --text "哇, VoxCPM1.5 现在也能在 RK3588 上跑起来了。" --prompt-audio basic_ref_zh.wav --prompt-text "对,这就是我,万人敬仰的太乙真人。" --output rknn_output.wav --cfg-value 2.0 --inference-timesteps 10 --seed 1234
53
+ ```
54
+
55
+ 可选参数:
56
+ - `--text`: 要生成的文本
57
+ - `--prompt-audio`: 参考音频路径(用于语音克隆)
58
+ - `--prompt-text`: 参考音频对应的文本(使用参考音频时必填)
59
+ - `--cfg-value`: CFG引导强度,默认2.0
60
+ - `--inference-timesteps`: 扩散步数,默认10
61
+ - `--seed`: 随机种子
62
+ - `--output`: 输出音频路径
63
+
64
+ ## 运行效果
65
+
66
+
67
+ ```log
68
+ > python onnx_infer-rknn2.py --onnx-dir . --tokenizer-dir . --base-hf-dir . --residual-hf-dir . --text "哇, VoxCPM1.5 现在也能在 RK3588 上跑起来了。" --prompt-audio basic_ref_zh.wav --prompt-text "对,这就是我,万人敬仰的太乙真人。" --output rknn_output.wav --cfg-value 2.0 --inference-timesteps 10 --seed 1234
69
+ I rkllm: rkllm-runtime version: 1.2.3, rknpu driver version: 0.9.8, platform: RK3588
70
+ I rkllm: loading rkllm model from ./base_lm.rkllm
71
+ I rkllm: rkllm-toolkit version: 1.2.3, max_context_limit: 4096, npu_core_num: 1, target_platform: RK3588, model_dtype: FP16
72
+ I rkllm: Enabled cpus: [4, 5, 6, 7]
73
+ I rkllm: Enabled cpus num: 4
74
+ I rkllm: rkllm-runtime version: 1.2.3, rknpu driver version: 0.9.8, platform: RK3588
75
+ I rkllm: loading rkllm model from ./residual_lm.rkllm
76
+ I rkllm: rkllm-toolkit version: 1.2.3, max_context_limit: 4096, npu_core_num: 3, target_platform: RK3588, model_dtype: FP16
77
+ I rkllm: Enabled cpus: [4, 5, 6, 7]
78
+ I rkllm: Enabled cpus num: 4
79
+ [time] vae_encode_0: 2127.35 ms
80
+ [time] vae_encode_105840: 2057.71 ms
81
+ [time] vae_encode_211680: 1997.43 ms
82
+ [time] locenc_0: 1791.50 ms
83
+ [time] locenc_64: 1782.49 ms
84
+ [time] base_lm initial: 368.19 ms
85
+ [time] fsq_init_0: 5.52 ms
86
+ [time] fsq_init_64: 4.20 ms
87
+ [time] residual_lm initial: 105.79 ms
88
+ gen_loop: 0%| | 0/2000 [00:00<?, ?it/s][time] lm_to_dit: 1.49 ms
89
+ [time] res_to_dit: 1.11 ms
90
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:00<00:00, 32.15it/s]
91
+ [time] locenc_step: 33.00 ms█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 8/10 [00:00<00:00, 32.24it/s]
92
+ gen_loop: 0%| | 1/2000 [00:00<15:33, 2.14it/s][time] lm_to_dit: 0.67 ms
93
+ [time] res_to_dit: 0.76 ms
94
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:00<00:00, 32.86it/s]
95
+ [time] locenc_step: 31.85 ms█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 8/10 [00:00<00:00, 32.99it/s]
96
+ gen_loop: 0%|▏ | 2/2000 [00:00<15:18, 2.18it/s][time] lm_to_dit: 0.61 ms
97
+ [time] res_to_dit: 0.65 ms
98
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:00<00:00, 32.72it/s]
99
+ [time] locenc_step: 32.01 ms█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 8/10 [00:00<00:00, 32.83it/s]
100
+ gen_loop: 2%|███▉ | 49/2000 [00:22<14:55, 2.18it/s][time] lm_to_dit: 0.88 ms
101
+ [time] res_to_dit: 0.64 ms
102
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:00<00:00, 32.72it/s]
103
+ [time] locenc_step: 32.16 ms█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 8/10 [00:00<00:00, 32.88it/s]
104
+ gen_loop: 2%|███▉ | 49/2000 [00:22<15:05, 2.15it/s]
105
+ [time] vae_decode_0: 2438.31 ms
106
+ [time] vae_decode_60: 2372.92 ms
107
+ [time] vae_decode_120: 2380.40 ms
108
+ [time] vae_decode_180: 2344.88 ms
109
+ Saved: rknn_output.wav
110
+ ```
111
+
112
+ ## 模型转换
113
+
114
+ 查看 https://huggingface.co/happyme531/VoxCPM1.5-RKNN2/tree/main/convert
115
+
116
+ ## 已知问题
117
+
118
+ - 某些情况下语音生成可能陷入死循环,原项目似乎有检测死循环的机制,但我这里没有实现。
119
+ - 由于RKNN工具链的内部问题,locenc模型没有办法在一个模型里配置两种输入长度的两组shape,因此只能单独转换两个模型。
120
+ - 由于RKLLM工具链/运行时的内部问题,两个LLM的输出张量的数值都只有正确结果的四分之一,手动乘4之后可以得到正确结果。
121
+
122
+
123
+ ## 参考
124
+ - [openbmb/VoxCPM1.5](https://huggingface.co/openbmb/VoxCPM1.5)
125
+ - [0seba/VoxCPMANE](https://github.com/0seba/VoxCPMANE)
126
+ - [bluryar/VoxCPM-ONNX](https://github.com/bluryar/VoxCPM-ONNX)
127
+
128
+ # English README
129
+
130
+ > VoxCPM is an innovative tokenizer-free Text-to-Speech (TTS) system that redefines realism in speech synthesis. By modeling speech in continuous space, it overcomes the limitations of discrete tokenization and achieves two core capabilities: context-aware speech generation and realistic zero-shot voice cloning.
131
+
132
+ > Unlike mainstream approaches that convert speech into discrete tokens, VoxCPM adopts an end-to-end diffusion autoregressive architecture that directly generates continuous speech representations from text. Built on the MiniCPM-4 backbone, it achieves implicit semantic-acoustic decoupling through hierarchical language modeling and FSQ constraints, greatly enhancing expressiveness and generation stability.
133
+
134
+ We’re thrilled to introduce a major upgrade that improves audio quality and efficiency of VoxCPM, while maintaining the core capabilities of context-aware speech generation and zero-shot voice cloning.
135
+
136
+ | Feature | VoxCPM | VoxCPM1.5 |
137
+ |---------|------------|------------|
138
+ | **Audio VAE Sampling Rate** | 16kHz | 44.1kHz |
139
+ | **LM Token Rate** | 12.5Hz | 6.25Hz |
140
+ | **Patch Size** | 2 | 4 |
141
+ | **SFT Support** | ✅ | ✅ |
142
+ | **LoRA Support** | ✅ | ✅ |
143
+
144
+ - Inference speed (RKNN2): RTF approximately 4.5 on RK3588 (45s inference time to generate 10s audio, no improvement compared to the previous version)
145
+ - Approximate memory usage (RKNN2): ~3.3GB (no improvement compared to the previous version too)
146
+
147
+ ## Usage
148
+
149
+ 1. Clone the project locally
150
+
151
+ 2. Install dependencies
152
+
153
+ ```bash
154
+ pip install numpy scipy soundfile tqdm transformers sentencepiece ztu-somemodelruntime-ez-rknn-async
155
+ ```
156
+
157
+ 3. Run
158
+
159
+ ```bash
160
+ python onnx_infer-rknn2.py --onnx-dir . --tokenizer-dir . --base-hf-dir . --residual-hf-dir . --text "Wow, VoxCPM1.5 actually runs perfectly on the RK3588 SoC!" --prompt-audio basic_ref_zh.wav --prompt-text "对,这就是我,万人敬仰的太乙真人。" --output rknn_output.wav --cfg-value 2.0 --inference-timesteps 10 --seed 1234
161
+ ```
162
+
163
+ Optional parameters:
164
+ - `--text`: Text to generate
165
+ - `--prompt-audio`: Reference audio path (for voice cloning)
166
+ - `--prompt-text`: Text corresponding to the reference audio (required when using reference audio)
167
+ - `--cfg-value`: CFG guidance strength, default 2.0
168
+ - `--inference-timesteps`: Number of diffusion steps, default 10
169
+ - `--seed`: Random seed
170
+ - `--output`: Output audio path
171
+
172
+ ## Performance
173
+
174
+
175
+ ```log
176
+ > python onnx_infer-rknn2.py --onnx-dir . --tokenizer-dir . --base-hf-dir . --residual-hf-dir . --text "哇, VoxCPM1.5 现在也能在 RK3588 上跑起来了。" --prompt-audio basic_ref_zh.wav --prompt-text "对,这就是我,万人敬仰的太乙真人。" --output rknn_output.wav --cfg-value 2.0 --inference-timesteps 10 --seed 1234
177
+ I rkllm: rkllm-runtime version: 1.2.3, rknpu driver version: 0.9.8, platform: RK3588
178
+ I rkllm: loading rkllm model from ./base_lm.rkllm
179
+ I rkllm: rkllm-toolkit version: 1.2.3, max_context_limit: 4096, npu_core_num: 1, target_platform: RK3588, model_dtype: FP16
180
+ I rkllm: Enabled cpus: [4, 5, 6, 7]
181
+ I rkllm: Enabled cpus num: 4
182
+ I rkllm: rkllm-runtime version: 1.2.3, rknpu driver version: 0.9.8, platform: RK3588
183
+ I rkllm: loading rkllm model from ./residual_lm.rkllm
184
+ I rkllm: rkllm-toolkit version: 1.2.3, max_context_limit: 4096, npu_core_num: 3, target_platform: RK3588, model_dtype: FP16
185
+ I rkllm: Enabled cpus: [4, 5, 6, 7]
186
+ I rkllm: Enabled cpus num: 4
187
+ [time] vae_encode_0: 2127.35 ms
188
+ [time] vae_encode_105840: 2057.71 ms
189
+ [time] vae_encode_211680: 1997.43 ms
190
+ [time] locenc_0: 1791.50 ms
191
+ [time] locenc_64: 1782.49 ms
192
+ [time] base_lm initial: 368.19 ms
193
+ [time] fsq_init_0: 5.52 ms
194
+ [time] fsq_init_64: 4.20 ms
195
+ [time] residual_lm initial: 105.79 ms
196
+ gen_loop: 0%| | 0/2000 [00:00<?, ?it/s][time] lm_to_dit: 1.49 ms
197
+ [time] res_to_dit: 1.11 ms
198
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:00<00:00, 32.15it/s]
199
+ [time] locenc_step: 33.00 ms█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 8/10 [00:00<00:00, 32.24it/s]
200
+ gen_loop: 0%| | 1/2000 [00:00<15:33, 2.14it/s][time] lm_to_dit: 0.67 ms
201
+ [time] res_to_dit: 0.76 ms
202
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:00<00:00, 32.86it/s]
203
+ [time] locenc_step: 31.85 ms█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 8/10 [00:00<00:00, 32.99it/s]
204
+ gen_loop: 0%|▏ | 2/2000 [00:00<15:18, 2.18it/s][time] lm_to_dit: 0.61 ms
205
+ [time] res_to_dit: 0.65 ms
206
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:00<00:00, 32.72it/s]
207
+ [time] locenc_step: 32.01 ms█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 8/10 [00:00<00:00, 32.83it/s]
208
+ gen_loop: 2%|███▉ | 49/2000 [00:22<14:55, 2.18it/s][time] lm_to_dit: 0.88 ms
209
+ [time] res_to_dit: 0.64 ms
210
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:00<00:00, 32.72it/s]
211
+ [time] locenc_step: 32.16 ms█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 8/10 [00:00<00:00, 32.88it/s]
212
+ gen_loop: 2%|███▉ | 49/2000 [00:22<15:05, 2.15it/s]
213
+ [time] vae_decode_0: 2438.31 ms
214
+ [time] vae_decode_60: 2372.92 ms
215
+ [time] vae_decode_120: 2380.40 ms
216
+ [time] vae_decode_180: 2344.88 ms
217
+ Saved: rknn_output.wav
218
+ ```
219
+ ## Model Conversion
220
+
221
+ See https://huggingface.co/happyme531/VoxCPM1.5-RKNN2/tree/main/convert
222
+
223
+ ## Known Issues
224
+
225
+ - In some cases, speech generation may fall into an infinite loop. The original project seems to have a mechanism to detect infinite loops, but it is not implemented here.
226
+ - Due to internal issues with the RKNN toolchain, the locenc model cannot configure two sets of shapes for two different input lengths in a single model, so two separate models must be converted.
227
+ - Due to internal issues with the RKLLM toolchain/runtime, the output tensor values of both LLMs are only one-quarter of the correct result. Multiplying by 4 manually yields the correct result.
228
+
229
+ ## References
230
+ - [openbmb/VoxCPM1.5](https://huggingface.co/openbmb/VoxCPM1.5)
231
+ - [0seba/VoxCPMANE](https://github.com/0seba/VoxCPMANE)
232
+ - [bluryar/VoxCPM-ONNX](https://github.com/bluryar/VoxCPM-ONNX)
audio_vae_decode.rknn ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48c5bd9d6f208db3fac1ab4e6e0fdf645938f1ad49103c3682109b78a4e653c5
3
+ size 97233394
audio_vae_encode.rknn ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e86ab8f8e436ffdafdb56c7daed81f11c0113547ab68876ce2325699594a82c
3
+ size 96550262
base_lm.rkllm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1e9401286336bc4e01f67ac085bda24e3a0a0a74bec866b9e56f315b7f0bc717
3
+ size 1028092444
basic_ref_zh.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:96724a113240d1f82c6ded1334122f0176b96c9226ccd3c919e625bcfd2a3ede
3
+ size 324558
config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architecture": "voxcpm",
3
+ "lm_config": {
4
+ "bos_token_id": 1,
5
+ "eos_token_id": 2,
6
+ "hidden_size": 1024,
7
+ "intermediate_size": 4096,
8
+ "max_position_embeddings": 32768,
9
+ "num_attention_heads": 16,
10
+ "num_hidden_layers": 24,
11
+ "num_key_value_heads": 2,
12
+ "rms_norm_eps": 1e-05,
13
+ "rope_theta": 10000,
14
+ "rope_scaling": {
15
+ "type": "longrope",
16
+ "long_factor": [1.0004360675811768, 1.0668443441390991, 1.1631425619125366, 1.3025742769241333, 1.5040205717086792, 1.7941505908966064, 2.2101221084594727, 2.802666664123535, 3.6389970779418945, 4.804192543029785, 6.39855432510376, 8.527148246765137, 11.277542114257812, 14.684998512268066, 18.69317054748535, 23.13019371032715, 27.72362518310547, 32.1606559753418, 36.168827056884766, 39.57627868652344, 42.32667541503906, 44.45526885986328, 46.04962921142578, 47.21482849121094, 48.05115509033203, 48.64370346069336, 49.05967712402344, 49.34980392456055, 49.551246643066406, 49.69068145751953, 49.78697967529297, 49.85338592529297],
17
+ "short_factor": [1.0004360675811768, 1.0668443441390991, 1.1631425619125366, 1.3025742769241333, 1.5040205717086792, 1.7941505908966064, 2.2101221084594727, 2.802666664123535, 3.6389970779418945, 4.804192543029785, 6.39855432510376, 8.527148246765137, 11.277542114257812, 14.684998512268066, 18.69317054748535, 23.13019371032715, 27.72362518310547, 32.1606559753418, 36.168827056884766, 39.57627868652344, 42.32667541503906, 44.45526885986328, 46.04962921142578, 47.21482849121094, 48.05115509033203, 48.64370346069336, 49.05967712402344, 49.34980392456055, 49.551246643066406, 49.69068145751953, 49.78697967529297, 49.85338592529297],
18
+ "original_max_position_embeddings": 32768
19
+ },
20
+ "vocab_size": 73448,
21
+ "scale_emb": 12,
22
+ "dim_model_base": 256,
23
+ "scale_depth": 1.4,
24
+ "use_mup": false
25
+ },
26
+ "patch_size": 4,
27
+ "feat_dim": 64,
28
+ "scalar_quantization_latent_dim": 256,
29
+ "scalar_quantization_scale": 9,
30
+ "residual_lm_num_layers": 8,
31
+ "encoder_config": {
32
+ "hidden_dim": 1024,
33
+ "ffn_dim": 4096,
34
+ "num_heads": 16,
35
+ "num_layers": 8
36
+ },
37
+ "dit_config": {
38
+ "hidden_dim": 1024,
39
+ "ffn_dim": 4096,
40
+ "num_heads": 16,
41
+ "num_layers": 8,
42
+ "cfm_config": {
43
+ "sigma_min": 1e-06,
44
+ "solver": "euler",
45
+ "t_scheduler": "log-norm",
46
+ "inference_cfg_rate": 2.0
47
+ }
48
+ },
49
+ "audio_vae_config": {
50
+ "encoder_dim": 64,
51
+ "encoder_rates": [2, 3, 6, 7, 7],
52
+ "latent_dim": 64,
53
+ "decoder_dim": 2048,
54
+ "decoder_rates": [7, 7, 6, 3, 2],
55
+ "sample_rate": 44100
56
+ },
57
+ "max_length": 8192,
58
+ "device": "cuda",
59
+ "dtype": "bfloat16"
60
+ }
convert/MiniCPM4-0.5B/added_tokens.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|execute_end|>": 73444,
3
+ "<|execute_start|>": 73443,
4
+ "<|fim_middle|>": 73446,
5
+ "<|fim_prefix|>": 73445,
6
+ "<|fim_suffix|>": 73447,
7
+ "<|im_end|>": 73440,
8
+ "<|im_start|>": 73441,
9
+ "<|tool_call|>": 73442
10
+ }
convert/MiniCPM4-0.5B/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "openbmb/MiniCPM4-0.5B",
3
+ "architectures": [
4
+ "MiniCPMForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_minicpm.MiniCPMConfig",
8
+ "AutoModel": "modeling_minicpm.MiniCPMModel",
9
+ "AutoModelForCausalLM": "modeling_minicpm.MiniCPMForCausalLM",
10
+ "AutoModelForSeq2SeqLM": "modeling_minicpm.MiniCPMForCausalLM",
11
+ "AutoModelForSequenceClassification": "modeling_minicpm.MiniCPMForSequenceClassification"
12
+ },
13
+ "bos_token_id": 1,
14
+ "eos_token_id": [2, 73440],
15
+ "hidden_act": "silu",
16
+ "hidden_size": 1024,
17
+ "initializer_range": 0.1,
18
+ "intermediate_size": 4096,
19
+ "max_position_embeddings": 32768,
20
+ "num_attention_heads": 16,
21
+ "num_hidden_layers": 24,
22
+ "num_key_value_heads": 2,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_scaling": {
25
+ "rope_type": "longrope",
26
+ "long_factor": [1.0004360675811768, 1.0668443441390991, 1.1631425619125366, 1.3025742769241333, 1.5040205717086792, 1.7941505908966064, 2.2101221084594727, 2.802666664123535, 3.6389970779418945, 4.804192543029785, 6.39855432510376, 8.527148246765137, 11.277542114257812, 14.684998512268066, 18.69317054748535, 23.13019371032715, 27.72362518310547, 32.1606559753418, 36.168827056884766, 39.57627868652344, 42.32667541503906, 44.45526885986328, 46.04962921142578, 47.21482849121094, 48.05115509033203, 48.64370346069336, 49.05967712402344, 49.34980392456055, 49.551246643066406, 49.69068145751953, 49.78697967529297, 49.85338592529297],
27
+ "short_factor": [1.0004360675811768, 1.0668443441390991, 1.1631425619125366, 1.3025742769241333, 1.5040205717086792, 1.7941505908966064, 2.2101221084594727, 2.802666664123535, 3.6389970779418945, 4.804192543029785, 6.39855432510376, 8.527148246765137, 11.277542114257812, 14.684998512268066, 18.69317054748535, 23.13019371032715, 27.72362518310547, 32.1606559753418, 36.168827056884766, 39.57627868652344, 42.32667541503906, 44.45526885986328, 46.04962921142578, 47.21482849121094, 48.05115509033203, 48.64370346069336, 49.05967712402344, 49.34980392456055, 49.551246643066406, 49.69068145751953, 49.78697967529297, 49.85338592529297],
28
+ "original_max_position_embeddings": 32768
29
+ },
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.46.3",
32
+ "use_cache": true,
33
+ "vocab_size": 73448,
34
+ "scale_emb": 12,
35
+ "dim_model_base": 256,
36
+ "scale_depth": 1.4
37
+ }
convert/MiniCPM4-0.5B/configuration_minicpm.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The OpenBMB Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ MiniCPM model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+ MINICPM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
23
+
24
+
25
+ class MiniCPMConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`MiniCPMModel`]. It is used to instantiate an MiniCPM
28
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
29
+ defaults will yield a similar configuration to that of the MiniCPM-7B.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32000):
37
+ Vocabulary size of the MiniCPM model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`MiniCPMModel`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 11008):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer decoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer decoder.
47
+ num_key_value_heads (`int`, *optional*):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
54
+ `num_attention_heads`.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
58
+ The maximum sequence length that this model might ever be used with. MiniCPM 1 supports up to 2048 tokens,
59
+ MiniCPM 2 up to 4096, CodeMiniCPM up to 16384.
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
63
+ The epsilon used by the rms normalization layers.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
66
+ relevant if `config.is_decoder=True`.
67
+ pad_token_id (`int`, *optional*):
68
+ Padding token id.
69
+ bos_token_id (`int`, *optional*, defaults to 1):
70
+ Beginning of stream token id.
71
+ eos_token_id (`int`, *optional*, defaults to 2):
72
+ End of stream token id.
73
+ pretraining_tp (`int`, *optional*, defaults to 1):
74
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
75
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
76
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
77
+ issue](https://github.com/pytorch/pytorch/issues/76232).
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ rope_scaling (`Dict`, *optional*):
83
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
84
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
85
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
86
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
87
+ these scaling strategies behave:
88
+ https://www.reddit.com/r/LocalMiniCPM/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
89
+ experimental feature, subject to breaking API changes in future versions.
90
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
91
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
92
+ attention_dropout (`float`, *optional*, defaults to 0.0):
93
+ The dropout ratio for the attention probabilities.
94
+
95
+ ```python
96
+ >>> from transformers import MiniCPMModel, MiniCPMConfig
97
+
98
+ >>> # Initializing a MiniCPM minicpm-7b style configuration
99
+ >>> configuration = MiniCPMConfig()
100
+
101
+ >>> # Initializing a model from the minicpm-7b style configuration
102
+ >>> model = MiniCPMModel(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+
108
+ model_type = 'minicpm'
109
+ keys_to_ignore_at_inference = ['past_key_values']
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=32000,
114
+ hidden_size=4096,
115
+ intermediate_size=11008,
116
+ num_hidden_layers=32,
117
+ num_attention_heads=32,
118
+ num_key_value_heads=None,
119
+ hidden_act='silu',
120
+ max_position_embeddings=2048,
121
+ initializer_range=0.02,
122
+ rms_norm_eps=1e-6,
123
+ use_cache=True,
124
+ pad_token_id=None,
125
+ bos_token_id=1,
126
+ eos_token_id=2,
127
+ pretraining_tp=1,
128
+ tie_word_embeddings=True,
129
+ rope_theta=10000.0,
130
+ rope_scaling=None,
131
+ attention_bias=False,
132
+ attention_dropout=0.0,
133
+ scale_emb=1,
134
+ dim_model_base=1,
135
+ scale_depth=1,
136
+ mup_denominator=None,
137
+ sparse_config=None,
138
+ **kwargs):
139
+
140
+ self.vocab_size = vocab_size
141
+ self.max_position_embeddings = max_position_embeddings
142
+ self.hidden_size = hidden_size
143
+ self.intermediate_size = intermediate_size
144
+ self.num_hidden_layers = num_hidden_layers
145
+ self.num_attention_heads = num_attention_heads
146
+
147
+ # for backward compatibility
148
+ if num_key_value_heads is None:
149
+ num_key_value_heads = num_attention_heads
150
+
151
+ self.num_key_value_heads = num_key_value_heads
152
+ self.hidden_act = hidden_act
153
+ self.initializer_range = initializer_range
154
+ self.rms_norm_eps = rms_norm_eps
155
+ self.pretraining_tp = pretraining_tp
156
+ self.use_cache = use_cache
157
+ self.rope_theta = rope_theta
158
+ self.rope_scaling = rope_scaling
159
+ # self._rope_scaling_validation()
160
+ self.attention_bias = attention_bias
161
+ self.attention_dropout = attention_dropout
162
+ self.scale_emb = scale_emb
163
+ self.dim_model_base = dim_model_base
164
+ self.scale_depth = scale_depth
165
+ # only used for Eagle Head
166
+ self.mup_denominator = mup_denominator
167
+
168
+ # sparse config
169
+ self.sparse_config = sparse_config
170
+
171
+ super().__init__(
172
+ pad_token_id=pad_token_id,
173
+ bos_token_id=bos_token_id,
174
+ eos_token_id=eos_token_id,
175
+ tie_word_embeddings=tie_word_embeddings,
176
+ **kwargs,
177
+ )
178
+ try:
179
+ import flash_attn
180
+ self._attn_implementation = 'flash_attention_2'
181
+ except:
182
+ pass
183
+
184
+ def _rope_scaling_validation(self):
185
+ """
186
+ Validate the `rope_scaling` configuration.
187
+ """
188
+ if self.rope_scaling is None:
189
+ return
190
+
191
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
192
+ raise ValueError(
193
+ '`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, '
194
+ f'got {self.rope_scaling}'
195
+ )
196
+ rope_scaling_type = self.rope_scaling.get('type', None)
197
+ rope_scaling_factor = self.rope_scaling.get('factor', None)
198
+ if rope_scaling_type is None or rope_scaling_type not in ['linear', 'dynamic']:
199
+ raise ValueError(
200
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
201
+ )
202
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
203
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
convert/MiniCPM4-0.5B/generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 2,
6
+ 73440
7
+ ],
8
+ "pad_token_id": 2,
9
+ "temperature": 0.8,
10
+ "top_p": 0.8,
11
+ "transformers_version": "4.46.1"
12
+ }
convert/MiniCPM4-0.5B/modeling_minicpm.py ADDED
@@ -0,0 +1,1514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The OpenBMB Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch MiniCPM model."""
16
+ import math
17
+ import re
18
+ import warnings
19
+ from typing import Any, Dict, List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+ from transformers.activations import ACT2FN
27
+ from transformers.cache_utils import Cache, DynamicCache, CacheLayerMixin, DynamicLayer
28
+ from transformers.modeling_attn_mask_utils import (
29
+ AttentionMaskConverter,
30
+ _prepare_4d_attention_mask,
31
+ _prepare_4d_causal_attention_mask,
32
+ _prepare_4d_causal_attention_mask_for_sdpa,
33
+ )
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ SequenceClassifierOutputWithPast,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
41
+ from transformers.utils import (
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from transformers.utils.import_utils import is_torch_fx_available
49
+
50
+ from .configuration_minicpm import MiniCPMConfig
51
+
52
+ try:
53
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
55
+ except:
56
+ pass
57
+
58
+
59
+
60
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
61
+ # It means that the function will not be traced through and simply appear as a node in the graph.
62
+ if is_torch_fx_available():
63
+ if not is_torch_greater_or_equal_than_1_13:
64
+ import torch.fx
65
+
66
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
67
+
68
+
69
+ logger = logging.get_logger(__name__)
70
+
71
+ _CONFIG_FOR_DOC = 'MiniCPMConfig'
72
+
73
+
74
+ def _get_unpad_data(attention_mask):
75
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
76
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
77
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
78
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
79
+ return (
80
+ indices,
81
+ cu_seqlens,
82
+ max_seqlen_in_batch,
83
+ )
84
+
85
+
86
+
87
+
88
+ # @torch.jit.script # type: ignore
89
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
90
+ old_dtype = hidden.dtype
91
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
92
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
93
+ return hidden * weight
94
+
95
+
96
+ class MiniCPMRMSNorm(nn.Module):
97
+ def __init__(self, hidden_size, eps=1e-6):
98
+ """
99
+ MiniCPMRMSNorm is equivalent to T5LayerNorm
100
+ """
101
+ super().__init__()
102
+ self.weight = nn.Parameter(torch.ones(hidden_size))
103
+ self.variance_epsilon = eps
104
+
105
+ def forward(self, hidden_states):
106
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
107
+
108
+
109
+ ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
110
+
111
+
112
+ class MiniCPMRotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
120
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
121
+
122
+ # Build here to make `torch.jit.trace` work.
123
+ self._set_cos_sin_cache(
124
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
125
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
131
+ freqs = torch.outer(t, self.inv_freq)
132
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
133
+ emb = torch.cat((freqs, freqs), dim=-1)
134
+
135
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
136
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
137
+
138
+ def forward(self, x, seq_len=None):
139
+ # x: [bs, num_attention_heads, seq_len, head_size]
140
+ if seq_len > self.max_seq_len_cached:
141
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
142
+
143
+ return (
144
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
145
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
146
+ )
147
+
148
+
149
+ class MiniCPMLongRoPE(MiniCPMRotaryEmbedding):
150
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
151
+
152
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, short_factor=None, long_factor=None, original_max_position_embeddings=None):
153
+ self.short_factor = short_factor
154
+ self.long_factor = long_factor
155
+ self.original_max_position_embeddings = original_max_position_embeddings
156
+ scale = (max_position_embeddings / self.original_max_position_embeddings)
157
+ self.scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
158
+ super().__init__(dim, max_position_embeddings, base, device)
159
+
160
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
161
+ self.max_seq_len_cached = seq_len
162
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
163
+ if seq_len > self.original_max_position_embeddings:
164
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=device)
165
+ else:
166
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=device)
167
+
168
+ freqs = torch.mul(
169
+ torch.outer(t, 1.0 / ext_factors).to(device=device),
170
+ self.inv_freq.to(device=device).to(dtype)
171
+ )
172
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
173
+ emb = torch.cat((freqs, freqs), dim=-1)
174
+ self.register_buffer('cos_cached', emb.cos().to(dtype) * self.scaling_factor, persistent=False)
175
+ self.register_buffer('sin_cached', emb.sin().to(dtype) * self.scaling_factor, persistent=False)
176
+
177
+
178
+ class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
179
+ """MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
180
+
181
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
182
+ self.scaling_factor = scaling_factor
183
+ super().__init__(dim, max_position_embeddings, base, device)
184
+
185
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
186
+ self.max_seq_len_cached = seq_len
187
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
188
+ t = t / self.scaling_factor
189
+
190
+ freqs = torch.outer(t, self.inv_freq)
191
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
192
+ emb = torch.cat((freqs, freqs), dim=-1)
193
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
194
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
195
+
196
+
197
+ class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
198
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
199
+
200
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
201
+ self.scaling_factor = scaling_factor
202
+ super().__init__(dim, max_position_embeddings, base, device)
203
+
204
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
205
+ self.max_seq_len_cached = seq_len
206
+
207
+ if seq_len > self.max_position_embeddings:
208
+ base = self.base * (
209
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
210
+ ) ** (self.dim / (self.dim - 2))
211
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
212
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
213
+
214
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
215
+
216
+ freqs = torch.outer(t, self.inv_freq)
217
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
218
+ emb = torch.cat((freqs, freqs), dim=-1)
219
+
220
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
221
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
222
+
223
+
224
+ def rotate_half(x):
225
+ """Rotates half the hidden dims of the input."""
226
+ x1 = x[..., : x.shape[-1] // 2]
227
+ x2 = x[..., x.shape[-1] // 2:]
228
+ return torch.cat((-x2, x1), dim=-1)
229
+
230
+
231
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
232
+ """Applies Rotary Position Embedding to the query and key tensors.
233
+
234
+ Args:
235
+ q (`torch.Tensor`): The query tensor.
236
+ k (`torch.Tensor`): The key tensor.
237
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
238
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
239
+ position_ids (`torch.Tensor`):
240
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
241
+ used to pass offsetted position ids when working with a KV-cache.
242
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
243
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
244
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
245
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
246
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
247
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
248
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
249
+ Returns:
250
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
251
+ """
252
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
253
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
254
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
255
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
256
+ orig_dtype = k.dtype
257
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
258
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
259
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
260
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
261
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
262
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
263
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
264
+
265
+
266
+ class MiniCPMMLP(nn.Module):
267
+ def __init__(self, config):
268
+ super().__init__()
269
+ self.config = config
270
+ self.hidden_size = config.hidden_size
271
+ self.intermediate_size = config.intermediate_size
272
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
273
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
274
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
275
+ self.act_fn = ACT2FN[config.hidden_act]
276
+
277
+ def forward(self, x):
278
+ if self.config.pretraining_tp > 1:
279
+ slice = self.intermediate_size // self.config.pretraining_tp
280
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
281
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
282
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
283
+
284
+ gate_proj = torch.cat(
285
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
286
+ )
287
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
288
+
289
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
290
+ down_proj = [
291
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
292
+ ]
293
+ down_proj = sum(down_proj)
294
+ else:
295
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
296
+
297
+ return down_proj
298
+
299
+ def _unpad_one_tensor(hidden_states, attention_mask):
300
+ # Unpad the hidden states using the indices
301
+ indices, cu_seqlens, max_seqlen_in_batch = _get_unpad_data(attention_mask)
302
+ batch_size, seq_len = hidden_states.shape[:2]
303
+
304
+ # Get the remaining dimensions
305
+ remaining_dims = hidden_states.shape[2:]
306
+
307
+ # Reshape to (batch_size * seq_len, *remaining_dims)
308
+ reshaped_states = hidden_states.reshape(batch_size * seq_len, *remaining_dims)
309
+
310
+ # Apply unpadding using indices
311
+ unpadded_states = index_first_axis(reshaped_states, indices)
312
+
313
+ return unpadded_states, indices, cu_seqlens, max_seqlen_in_batch
314
+
315
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
316
+ """
317
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
318
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
319
+ """
320
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
321
+ if n_rep == 1:
322
+ return hidden_states
323
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
324
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
325
+
326
+
327
+ class MiniCPMAttention(nn.Module):
328
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
329
+
330
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
331
+ super().__init__()
332
+ self.config = config
333
+ self.layer_idx = layer_idx
334
+ if layer_idx is None:
335
+ logger.warning_once(
336
+ f'Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will '
337
+ 'to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` '
338
+ 'when creating this class.'
339
+ )
340
+
341
+ self.attention_dropout = config.attention_dropout
342
+ self.hidden_size = config.hidden_size
343
+ self.num_heads = config.num_attention_heads
344
+ self.head_dim = self.hidden_size // self.num_heads
345
+ self.num_key_value_heads = config.num_key_value_heads
346
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
347
+ self.max_position_embeddings = config.max_position_embeddings
348
+ self.rope_theta = config.rope_theta
349
+ self.is_causal = True
350
+
351
+ if (self.head_dim * self.num_heads) != self.hidden_size:
352
+ raise ValueError(
353
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
354
+ f' and `num_heads`: {self.num_heads}).'
355
+ )
356
+
357
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
358
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
359
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
360
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
361
+ self._init_rope()
362
+
363
+ def _init_rope(self):
364
+ if self.config.rope_scaling is None:
365
+ self.rotary_emb = MiniCPMRotaryEmbedding(
366
+ self.head_dim,
367
+ max_position_embeddings=self.max_position_embeddings,
368
+ base=self.rope_theta,
369
+ )
370
+ else:
371
+ scaling_type = self.config.rope_scaling['rope_type']
372
+ scaling_factor = self.config.rope_scaling.get('factor', None)
373
+ if scaling_type == 'linear':
374
+ self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
375
+ self.head_dim,
376
+ max_position_embeddings=self.max_position_embeddings,
377
+ scaling_factor=scaling_factor,
378
+ base=self.rope_theta,
379
+ )
380
+ elif scaling_type == 'dynamic':
381
+ self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
382
+ self.head_dim,
383
+ max_position_embeddings=self.max_position_embeddings,
384
+ scaling_factor=scaling_factor,
385
+ base=self.rope_theta,
386
+ )
387
+ elif scaling_type == 'longrope':
388
+ self.rotary_emb = MiniCPMLongRoPE(
389
+ self.head_dim,
390
+ max_position_embeddings=self.max_position_embeddings,
391
+ short_factor=self.config.rope_scaling['short_factor'],
392
+ long_factor=self.config.rope_scaling['long_factor'],
393
+ base=self.rope_theta,
394
+ original_max_position_embeddings=self.config.rope_scaling['original_max_position_embeddings']
395
+ )
396
+ else:
397
+ raise ValueError(f'Unknown RoPE scaling type {scaling_type}')
398
+
399
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
400
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
401
+
402
+ def forward(
403
+ self,
404
+ hidden_states: torch.Tensor,
405
+ attention_mask: Optional[torch.Tensor] = None,
406
+ position_ids: Optional[torch.LongTensor] = None,
407
+ past_key_value: Optional[Cache] = None,
408
+ output_attentions: bool = False,
409
+ use_cache: bool = False,
410
+ **kwargs,
411
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
412
+ if 'padding_mask' in kwargs:
413
+ warnings.warn(
414
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
415
+ )
416
+
417
+ bsz, q_len, _ = hidden_states.size()
418
+
419
+ if self.config.pretraining_tp > 1:
420
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
421
+ query_slices = self.q_proj.weight.split(
422
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
423
+ )
424
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
425
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
426
+
427
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
428
+ query_states = torch.cat(query_states, dim=-1)
429
+
430
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
431
+ key_states = torch.cat(key_states, dim=-1)
432
+
433
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
434
+ value_states = torch.cat(value_states, dim=-1)
435
+
436
+ else:
437
+ query_states = self.q_proj(hidden_states)
438
+ key_states = self.k_proj(hidden_states)
439
+ value_states = self.v_proj(hidden_states)
440
+
441
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
442
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
443
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
444
+
445
+ kv_seq_len = position_ids.max().item() + 1
446
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
447
+
448
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
449
+
450
+ if past_key_value is not None:
451
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
452
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
453
+
454
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
455
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
456
+
457
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
458
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
459
+ raise ValueError(
460
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
461
+ f' {attn_weights.size()}'
462
+ )
463
+
464
+ if attention_mask is not None:
465
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
466
+ raise ValueError(
467
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
468
+ )
469
+ attn_weights = attn_weights + attention_mask
470
+
471
+ # upcast attention to fp32
472
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
473
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
474
+ attn_output = torch.matmul(attn_weights, value_states)
475
+
476
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
477
+ raise ValueError(
478
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
479
+ f' {attn_output.size()}'
480
+ )
481
+
482
+ attn_output = attn_output.transpose(1, 2).contiguous()
483
+
484
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
485
+
486
+ if self.config.pretraining_tp > 1:
487
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
488
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
489
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
490
+ else:
491
+ attn_output = self.o_proj(attn_output)
492
+
493
+ if not output_attentions:
494
+ attn_weights = None
495
+
496
+ return attn_output, attn_weights, past_key_value
497
+
498
+
499
+ class MiniCPMFlashAttention2(MiniCPMAttention):
500
+ """
501
+ MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
502
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
503
+ flash attention and deal with padding tokens in case the input contains any of them.
504
+ """
505
+
506
+ def __init__(self, *args, **kwargs):
507
+ super().__init__(*args, **kwargs)
508
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
509
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
510
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
511
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
512
+
513
+ def forward(
514
+ self,
515
+ hidden_states: torch.Tensor,
516
+ attention_mask: Optional[torch.LongTensor] = None,
517
+ position_ids: Optional[torch.LongTensor] = None,
518
+ past_key_value: Optional[Cache] = None,
519
+ output_attentions: bool = False,
520
+ use_cache: bool = False,
521
+ **kwargs,
522
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
523
+ # MiniCPMFlashAttention2 attention does not support output_attentions
524
+ if 'padding_mask' in kwargs:
525
+ warnings.warn(
526
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
527
+ )
528
+
529
+ # overwrite attention_mask with padding_mask
530
+ attention_mask = kwargs.pop('padding_mask')
531
+
532
+ output_attentions = False
533
+
534
+ bsz, q_len, _ = hidden_states.size()
535
+
536
+ query_states = self.q_proj(hidden_states)
537
+ key_states = self.k_proj(hidden_states)
538
+ value_states = self.v_proj(hidden_states)
539
+
540
+ # Flash attention requires the input to have the shape
541
+ # batch_size x seq_length x head_dim x hidden_dim
542
+ # therefore we just need to keep the original shape
543
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
544
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
545
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
546
+
547
+ kv_seq_len = position_ids.max().item() + 1
548
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
549
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
550
+
551
+ if past_key_value is not None:
552
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
553
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
554
+
555
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
556
+ # to be able to avoid many of these transpose/reshape/view.
557
+ query_states = query_states.transpose(1, 2)
558
+ key_states = key_states.transpose(1, 2)
559
+ value_states = value_states.transpose(1, 2)
560
+
561
+ dropout_rate = self.attention_dropout if self.training else 0.0
562
+
563
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
564
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
565
+ # cast them back in the correct dtype just to be sure everything works as expected.
566
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
567
+ # in fp32. (MiniCPMRMSNorm handles it correctly)
568
+
569
+ input_dtype = query_states.dtype
570
+ if input_dtype == torch.float32:
571
+ # Handle the case where the model is quantized
572
+ if hasattr(self.config, '_pre_quantization_dtype'):
573
+ target_dtype = self.config._pre_quantization_dtype
574
+ else:
575
+ target_dtype = self.q_proj.weight.dtype
576
+
577
+ logger.warning_once(
578
+ f'The input hidden states seems to be silently casted in float32, this might be related to'
579
+ f' the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in'
580
+ f' {target_dtype}.'
581
+ )
582
+
583
+ query_states = query_states.to(target_dtype)
584
+ key_states = key_states.to(target_dtype)
585
+ value_states = value_states.to(target_dtype)
586
+
587
+ attn_output = self._flash_attention_forward(
588
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
589
+ )
590
+
591
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
592
+ attn_output = self.o_proj(attn_output)
593
+
594
+ if not output_attentions:
595
+ attn_weights = None
596
+
597
+ return attn_output, attn_weights, past_key_value
598
+
599
+ def _flash_attention_forward(
600
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
601
+ ):
602
+ """
603
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
604
+ first unpad the input, then computes the attention scores and pad the final attention scores.
605
+
606
+ Args:
607
+ query_states (`torch.Tensor`):
608
+ Input query states to be passed to Flash Attention API
609
+ key_states (`torch.Tensor`):
610
+ Input key states to be passed to Flash Attention API
611
+ value_states (`torch.Tensor`):
612
+ Input value states to be passed to Flash Attention API
613
+ attention_mask (`torch.Tensor`):
614
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
615
+ position of padding tokens and 1 for the position of non-padding tokens.
616
+ dropout (`int`, *optional*):
617
+ Attention dropout
618
+ softmax_scale (`float`, *optional*):
619
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
620
+ """
621
+ if not self._flash_attn_uses_top_left_mask:
622
+ causal = self.is_causal
623
+ else:
624
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in MiniCPMFlashAttention2 __init__.
625
+ causal = self.is_causal and query_length != 1
626
+ # Contains at least one padding token in the sequence
627
+ if attention_mask is not None:
628
+ batch_size = query_states.shape[0]
629
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
630
+ query_states, key_states, value_states, attention_mask, query_length
631
+ )
632
+
633
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
634
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
635
+ attn_output_unpad = flash_attn_varlen_func(
636
+ query_states,
637
+ key_states,
638
+ value_states,
639
+ cu_seqlens_q=cu_seqlens_q,
640
+ cu_seqlens_k=cu_seqlens_k,
641
+ max_seqlen_q=max_seqlen_in_batch_q,
642
+ max_seqlen_k=max_seqlen_in_batch_k,
643
+ dropout_p=dropout,
644
+ softmax_scale=softmax_scale,
645
+ causal=causal,
646
+ )
647
+
648
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
649
+ else:
650
+ attn_output = flash_attn_func(
651
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
652
+ )
653
+
654
+ return attn_output
655
+
656
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
657
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
658
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
659
+
660
+ key_layer = index_first_axis(
661
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
662
+ )
663
+ value_layer = index_first_axis(
664
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
665
+ )
666
+ if query_length == kv_seq_len:
667
+ query_layer = index_first_axis(
668
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
669
+ )
670
+ cu_seqlens_q = cu_seqlens_k
671
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
672
+ indices_q = indices_k
673
+ elif query_length == 1:
674
+ max_seqlen_in_batch_q = 1
675
+ cu_seqlens_q = torch.arange(
676
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
677
+ ) # There is a memcpy here, that is very bad.
678
+ indices_q = cu_seqlens_q[:-1]
679
+ query_layer = query_layer.squeeze(1)
680
+ else:
681
+ # The -q_len: slice assumes left padding.
682
+ attention_mask = attention_mask[:, -query_length:]
683
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
684
+
685
+ return (
686
+ query_layer,
687
+ key_layer,
688
+ value_layer,
689
+ indices_q,
690
+ (cu_seqlens_q, cu_seqlens_k),
691
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
692
+ )
693
+
694
+
695
+ class MiniCPMSdpaAttention(MiniCPMAttention):
696
+ """
697
+ MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
698
+ `MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
699
+ SDPA API.
700
+ """
701
+
702
+ # Adapted from MiniCPMAttention.forward
703
+ def forward(
704
+ self,
705
+ hidden_states: torch.Tensor,
706
+ attention_mask: Optional[torch.Tensor] = None,
707
+ position_ids: Optional[torch.LongTensor] = None,
708
+ past_key_value: Optional[Cache] = None,
709
+ output_attentions: bool = False,
710
+ use_cache: bool = False,
711
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
712
+ if output_attentions:
713
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
714
+ logger.warning_once(
715
+ 'MiniCPMModel is using MiniCPMSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, '
716
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
717
+ )
718
+ return super().forward(
719
+ hidden_states=hidden_states,
720
+ attention_mask=attention_mask,
721
+ position_ids=position_ids,
722
+ past_key_value=past_key_value,
723
+ output_attentions=output_attentions,
724
+ use_cache=use_cache,
725
+ )
726
+
727
+ bsz, q_len, _ = hidden_states.size()
728
+
729
+ query_states = self.q_proj(hidden_states)
730
+ key_states = self.k_proj(hidden_states)
731
+ value_states = self.v_proj(hidden_states)
732
+
733
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
734
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
735
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+
737
+ kv_seq_len = position_ids.max().item() + 1
738
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
739
+
740
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
741
+
742
+ if past_key_value is not None:
743
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
744
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
745
+
746
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
747
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
748
+
749
+ if attention_mask is not None:
750
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
751
+ raise ValueError(
752
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
753
+ )
754
+
755
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
756
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
757
+ if query_states.device.type == 'cuda' and attention_mask is not None:
758
+ query_states = query_states.contiguous()
759
+ key_states = key_states.contiguous()
760
+ value_states = value_states.contiguous()
761
+
762
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
763
+ query_states,
764
+ key_states,
765
+ value_states,
766
+ attn_mask=attention_mask,
767
+ dropout_p=self.attention_dropout if self.training else 0.0,
768
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
769
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
770
+ )
771
+
772
+ attn_output = attn_output.transpose(1, 2).contiguous()
773
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
774
+
775
+ attn_output = self.o_proj(attn_output)
776
+
777
+ return attn_output, None, past_key_value
778
+
779
+
780
+ MINICPM_ATTENTION_CLASSES = {
781
+ 'eager': MiniCPMAttention,
782
+ 'flash_attention_2': MiniCPMFlashAttention2,
783
+ 'sdpa': MiniCPMSdpaAttention,
784
+ }
785
+
786
+
787
+ class MiniCPMDecoderLayer(nn.Module):
788
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
789
+ super().__init__()
790
+ self.hidden_size = config.hidden_size
791
+ self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
792
+
793
+ self.mlp = MiniCPMMLP(config)
794
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
795
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
796
+
797
+ self.scale_depth = config.scale_depth
798
+ self.num_hidden_layers = config.num_hidden_layers
799
+
800
+ def forward(
801
+ self,
802
+ hidden_states: torch.Tensor,
803
+ attention_mask: Optional[torch.Tensor] = None,
804
+ position_ids: Optional[torch.LongTensor] = None,
805
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
806
+ output_attentions: Optional[bool] = False,
807
+ use_cache: Optional[bool] = False,
808
+ **kwargs,
809
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
810
+ """
811
+ Args:
812
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
813
+ attention_mask (`torch.FloatTensor`, *optional*):
814
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
815
+ query_sequence_length, key_sequence_length)` if default attention is used.
816
+ output_attentions (`bool`, *optional*):
817
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
818
+ returned tensors for more detail.
819
+ use_cache (`bool`, *optional*):
820
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
821
+ (see `past_key_values`).
822
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
823
+ """
824
+ if 'padding_mask' in kwargs:
825
+ warnings.warn(
826
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
827
+ )
828
+
829
+ residual = hidden_states
830
+ hidden_states = self.input_layernorm(hidden_states)
831
+ # Self Attention
832
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
833
+ hidden_states=hidden_states,
834
+ attention_mask=attention_mask,
835
+ position_ids=position_ids,
836
+ past_key_value=past_key_value,
837
+ output_attentions=output_attentions,
838
+ use_cache=use_cache,
839
+ **kwargs,
840
+ )
841
+
842
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
843
+
844
+ # Fully Connected
845
+ residual = hidden_states
846
+ hidden_states = self.post_attention_layernorm(hidden_states)
847
+
848
+ hidden_states = self.mlp(hidden_states)
849
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
850
+
851
+ outputs = (hidden_states,)
852
+
853
+ if output_attentions:
854
+ outputs += (self_attn_weights,)
855
+
856
+ if use_cache:
857
+ outputs += (present_key_value,)
858
+
859
+ return outputs
860
+
861
+
862
+ MINICPM_START_DOCSTRING = r"""
863
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
864
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
865
+ etc.)
866
+
867
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
868
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
869
+ and behavior.
870
+
871
+ Parameters:
872
+ config ([`MiniCPMConfig`]):
873
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
874
+ load the weights associated with the model, only the configuration. Check out the
875
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
876
+ """
877
+
878
+
879
+ @add_start_docstrings(
880
+ 'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
881
+ MINICPM_START_DOCSTRING,
882
+ )
883
+ class MiniCPMPreTrainedModel(PreTrainedModel):
884
+ config_class = MiniCPMConfig
885
+ base_model_prefix = 'model'
886
+ supports_gradient_checkpointing = True
887
+ _no_split_modules = ['MiniCPMDecoderLayer']
888
+ _skip_keys_device_placement = 'past_key_values'
889
+ _supports_flash_attn_2 = True
890
+ _supports_sdpa = True
891
+ _supports_cache_class = True
892
+
893
+ def _init_weights(self, module):
894
+ std = self.config.initializer_range
895
+ if isinstance(module, nn.Linear):
896
+ module.weight.data.normal_(mean=0.0, std=std)
897
+ if module.bias is not None:
898
+ module.bias.data.zero_()
899
+ elif isinstance(module, nn.Embedding):
900
+ module.weight.data.normal_(mean=0.0, std=std)
901
+ if module.padding_idx is not None:
902
+ module.weight.data[module.padding_idx].zero_()
903
+
904
+
905
+ MINICPM_INPUTS_DOCSTRING = r"""
906
+ Args:
907
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
908
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
909
+ it.
910
+
911
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
912
+ [`PreTrainedTokenizer.__call__`] for details.
913
+
914
+ [What are input IDs?](../glossary#input-ids)
915
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
916
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
917
+
918
+ - 1 for tokens that are **not masked**,
919
+ - 0 for tokens that are **masked**.
920
+
921
+ [What are attention masks?](../glossary#attention-mask)
922
+
923
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
924
+ [`PreTrainedTokenizer.__call__`] for details.
925
+
926
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
927
+ `past_key_values`).
928
+
929
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
930
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
931
+ information on the default strategy.
932
+
933
+ - 1 indicates the head is **not masked**,
934
+ - 0 indicates the head is **masked**.
935
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
936
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
937
+ config.n_positions - 1]`.
938
+
939
+ [What are position IDs?](../glossary#position-ids)
940
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
941
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
942
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
943
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
944
+
945
+ Two formats are allowed:
946
+ - a [`~cache_utils.Cache`] instance;
947
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
948
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
949
+ cache format.
950
+
951
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
952
+ legacy cache format will be returned.
953
+
954
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
955
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
956
+ of shape `(batch_size, sequence_length)`.
957
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
958
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
959
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
960
+ model's internal embedding lookup matrix.
961
+ use_cache (`bool`, *optional*):
962
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
963
+ `past_key_values`).
964
+ output_attentions (`bool`, *optional*):
965
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
966
+ tensors for more detail.
967
+ output_hidden_states (`bool`, *optional*):
968
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
969
+ more detail.
970
+ return_dict (`bool`, *optional*):
971
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
972
+ """
973
+
974
+
975
+ @add_start_docstrings(
976
+ 'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
977
+ MINICPM_START_DOCSTRING,
978
+ )
979
+ class MiniCPMModel(MiniCPMPreTrainedModel):
980
+ """
981
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
982
+
983
+ Args:
984
+ config: MiniCPMConfig
985
+ """
986
+
987
+ def __init__(self, config: MiniCPMConfig):
988
+ super().__init__(config)
989
+ self.padding_idx = config.pad_token_id
990
+ self.vocab_size = config.vocab_size
991
+
992
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
993
+ self.layers = nn.ModuleList(
994
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
995
+ )
996
+ self._use_sdpa = config._attn_implementation == 'sdpa'
997
+ self._use_flash_attention_2 = config._attn_implementation == 'flash_attention_2'
998
+
999
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1000
+
1001
+ self.gradient_checkpointing = False
1002
+ # Initialize weights and apply final processing
1003
+ self.post_init()
1004
+
1005
+ def get_input_embeddings(self):
1006
+ return self.embed_tokens
1007
+
1008
+ def set_input_embeddings(self, value):
1009
+ self.embed_tokens = value
1010
+
1011
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1012
+ def forward(
1013
+ self,
1014
+ input_ids: torch.LongTensor = None,
1015
+ attention_mask: Optional[torch.Tensor] = None,
1016
+ position_ids: Optional[torch.LongTensor] = None,
1017
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1018
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1019
+ use_cache: Optional[bool] = None,
1020
+ output_attentions: Optional[bool] = None,
1021
+ output_hidden_states: Optional[bool] = None,
1022
+ return_dict: Optional[bool] = None,
1023
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1024
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1025
+ output_hidden_states = (
1026
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1027
+ )
1028
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1029
+
1030
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1031
+
1032
+ # retrieve input_ids and inputs_embeds
1033
+ if input_ids is not None and inputs_embeds is not None:
1034
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
1035
+ elif input_ids is not None:
1036
+ batch_size, seq_length = input_ids.shape[:2]
1037
+ elif inputs_embeds is not None:
1038
+ batch_size, seq_length = inputs_embeds.shape[:2]
1039
+ else:
1040
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
1041
+
1042
+ if self.gradient_checkpointing and self.training:
1043
+ if use_cache:
1044
+ logger.warning_once(
1045
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
1046
+ )
1047
+ use_cache = False
1048
+
1049
+ past_key_values_length = 0
1050
+
1051
+ if use_cache:
1052
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1053
+ if use_legacy_cache:
1054
+ raise ValueError(
1055
+ 'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
1056
+ )
1057
+
1058
+ # Calculate the usable length of past key values
1059
+ past_key_values_length = past_key_values.get_seq_length() if isinstance(past_key_values, Cache) else 0
1060
+
1061
+
1062
+ if position_ids is None:
1063
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1064
+ position_ids = torch.arange(
1065
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1066
+ )
1067
+ position_ids = position_ids.unsqueeze(0)
1068
+
1069
+ if inputs_embeds is None:
1070
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1071
+
1072
+ if self._use_flash_attention_2:
1073
+ # 2d mask is passed through the layers
1074
+ # attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1075
+ if attention_mask is None:
1076
+ raise ValueError(
1077
+ f'need attention_mask for flash attention, but got {attention_mask}.'
1078
+ )
1079
+ elif self._use_sdpa and not output_attentions:
1080
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1081
+ # the manual implementation that requires a 4D causal mask in all cases.
1082
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1083
+ attention_mask,
1084
+ (batch_size, seq_length),
1085
+ inputs_embeds,
1086
+ past_key_values_length,
1087
+ )
1088
+ else:
1089
+ # 4d mask is passed through the layers
1090
+ attention_mask = _prepare_4d_causal_attention_mask(
1091
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1092
+ )
1093
+
1094
+ # embed positions
1095
+ hidden_states = inputs_embeds
1096
+
1097
+ # decoder layers
1098
+ all_hidden_states = () if output_hidden_states else None
1099
+ all_self_attns = () if output_attentions else None
1100
+ next_decoder_cache = None
1101
+
1102
+ for decoder_layer in self.layers:
1103
+ if output_hidden_states:
1104
+ all_hidden_states += (hidden_states,)
1105
+
1106
+ if self.gradient_checkpointing and self.training:
1107
+ layer_outputs = self._gradient_checkpointing_func(
1108
+ decoder_layer.__call__,
1109
+ hidden_states,
1110
+ attention_mask,
1111
+ position_ids,
1112
+ past_key_values,
1113
+ output_attentions,
1114
+ use_cache,
1115
+ )
1116
+ else:
1117
+ layer_outputs = decoder_layer(
1118
+ hidden_states,
1119
+ attention_mask=attention_mask,
1120
+ position_ids=position_ids,
1121
+ past_key_value=past_key_values,
1122
+ output_attentions=output_attentions,
1123
+ use_cache=use_cache,
1124
+ )
1125
+
1126
+ hidden_states = layer_outputs[0]
1127
+
1128
+ if use_cache:
1129
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1130
+
1131
+ if output_attentions:
1132
+ all_self_attns += (layer_outputs[1],)
1133
+
1134
+ hidden_states = self.norm(hidden_states)
1135
+
1136
+ # add hidden states from the last decoder layer
1137
+ if output_hidden_states:
1138
+ all_hidden_states += (hidden_states,)
1139
+
1140
+ next_cache = None
1141
+ if use_cache:
1142
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1143
+ if not return_dict:
1144
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1145
+ return BaseModelOutputWithPast(
1146
+ last_hidden_state=hidden_states,
1147
+ past_key_values=next_cache,
1148
+ hidden_states=all_hidden_states,
1149
+ attentions=all_self_attns,
1150
+ )
1151
+
1152
+
1153
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1154
+ _tied_weights_keys = ['lm_head.weight']
1155
+
1156
+ def __init__(self, config):
1157
+ super().__init__(config)
1158
+ self.model = MiniCPMModel(config)
1159
+ self.vocab_size = config.vocab_size
1160
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1161
+
1162
+ # Initialize weights and apply final processing
1163
+ self.post_init()
1164
+
1165
+ def get_input_embeddings(self):
1166
+ return self.model.embed_tokens
1167
+
1168
+ def set_input_embeddings(self, value):
1169
+ self.model.embed_tokens = value
1170
+
1171
+ def get_output_embeddings(self):
1172
+ return self.lm_head
1173
+
1174
+ def set_output_embeddings(self, new_embeddings):
1175
+ self.lm_head = new_embeddings
1176
+
1177
+ def set_decoder(self, decoder):
1178
+ self.model = decoder
1179
+
1180
+ def get_decoder(self):
1181
+ return self.model
1182
+
1183
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1184
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1185
+ def forward(
1186
+ self,
1187
+ input_ids: torch.LongTensor = None,
1188
+ attention_mask: Optional[torch.Tensor] = None,
1189
+ position_ids: Optional[torch.LongTensor] = None,
1190
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1191
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1192
+ labels: Optional[torch.LongTensor] = None,
1193
+ use_cache: Optional[bool] = None,
1194
+ output_attentions: Optional[bool] = None,
1195
+ output_hidden_states: Optional[bool] = None,
1196
+ return_dict: Optional[bool] = None,
1197
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1198
+ **kwargs,
1199
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1200
+ r"""
1201
+ Args:
1202
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1203
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1204
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1205
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1206
+
1207
+ Returns:
1208
+
1209
+ Example:
1210
+
1211
+ ```python
1212
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1213
+
1214
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1215
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1216
+
1217
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1218
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1219
+
1220
+ >>> # Generate
1221
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1222
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1223
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1224
+ ```"""
1225
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1226
+ output_hidden_states = (
1227
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1228
+ )
1229
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1230
+
1231
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1232
+ outputs = self.model(
1233
+ input_ids=input_ids,
1234
+ attention_mask=attention_mask,
1235
+ position_ids=position_ids,
1236
+ past_key_values=past_key_values,
1237
+ inputs_embeds=inputs_embeds,
1238
+ use_cache=use_cache,
1239
+ output_attentions=output_attentions,
1240
+ output_hidden_states=output_hidden_states,
1241
+ return_dict=return_dict,
1242
+ )
1243
+
1244
+ hidden_states = outputs[0]
1245
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1246
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1247
+ hidden_states = hidden_states[:, slice_indices, :].contiguous()
1248
+ if self.config.pretraining_tp > 1:
1249
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1250
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1251
+ logits = torch.cat(logits, dim=-1)
1252
+ else:
1253
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
1254
+ logits = logits.float()
1255
+
1256
+ loss = None
1257
+ if labels is not None:
1258
+ # Shift so that tokens < n predict n
1259
+ shift_logits = logits[..., :-1, :].contiguous()
1260
+ shift_labels = labels[..., 1:].contiguous()
1261
+ # Flatten the tokens
1262
+ loss_fct = CrossEntropyLoss()
1263
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1264
+ shift_labels = shift_labels.view(-1)
1265
+ # Enable model parallelism
1266
+ shift_labels = shift_labels.to(shift_logits.device)
1267
+ loss = loss_fct(shift_logits, shift_labels)
1268
+
1269
+ if not return_dict:
1270
+ output = (logits,) + outputs[1:]
1271
+ return (loss,) + output if loss is not None else output
1272
+
1273
+ return CausalLMOutputWithPast(
1274
+ loss=loss,
1275
+ logits=logits,
1276
+ past_key_values=outputs.past_key_values,
1277
+ hidden_states=outputs.hidden_states,
1278
+ attentions=outputs.attentions,
1279
+ )
1280
+
1281
+ def prepare_inputs_for_generation(
1282
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1283
+ ):
1284
+ if past_key_values is not None:
1285
+ if isinstance(past_key_values, Cache):
1286
+ # Use the new Cache class methods
1287
+ cache_length = past_key_values.get_seq_length()
1288
+
1289
+
1290
+ past_length = cache_length
1291
+ max_cache_length = None
1292
+ else:
1293
+ raise ValueError(
1294
+ 'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
1295
+ )
1296
+
1297
+ # Keep only the unprocessed tokens:
1298
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1299
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1300
+ # input)
1301
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1302
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1303
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1304
+ # input_ids based on the past_length.
1305
+ elif past_length < input_ids.shape[1]:
1306
+ input_ids = input_ids[:, past_length:]
1307
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1308
+
1309
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1310
+ if (
1311
+ max_cache_length is not None
1312
+ and attention_mask is not None
1313
+ and cache_length + input_ids.shape[1] > max_cache_length
1314
+ ):
1315
+ attention_mask = attention_mask[:, -max_cache_length:]
1316
+
1317
+ position_ids = kwargs.get('position_ids', None)
1318
+ if attention_mask is not None and position_ids is None:
1319
+ # create position_ids on the fly for batch generation
1320
+ position_ids = attention_mask.long().cumsum(-1) - 1
1321
+ position_ids.masked_fill_(attention_mask == 0, 1)
1322
+ if past_key_values:
1323
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1324
+
1325
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1326
+ if inputs_embeds is not None and past_key_values is None:
1327
+ model_inputs = {'inputs_embeds': inputs_embeds}
1328
+ else:
1329
+ model_inputs = {'input_ids': input_ids}
1330
+
1331
+ model_inputs.update(
1332
+ {
1333
+ 'position_ids': position_ids,
1334
+ 'past_key_values': past_key_values,
1335
+ 'use_cache': kwargs.get('use_cache'),
1336
+ 'attention_mask': attention_mask,
1337
+ }
1338
+ )
1339
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
1340
+ for key, value in kwargs.items():
1341
+ if key not in model_inputs:
1342
+ model_inputs[key] = value
1343
+ return model_inputs
1344
+
1345
+ @staticmethod
1346
+ def _reorder_cache(past_key_values, beam_idx):
1347
+ reordered_past = ()
1348
+ for layer_past in past_key_values:
1349
+ reordered_past += (
1350
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1351
+ )
1352
+ return reordered_past
1353
+
1354
+ @torch.inference_mode()
1355
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = 'user',
1356
+ max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
1357
+ **kwargs):
1358
+ if history is None:
1359
+ history = []
1360
+ if logits_processor:
1361
+ gen_kwargs = {
1362
+ 'max_length': max_length,
1363
+ 'num_beams': num_beams,
1364
+ 'do_sample': do_sample,
1365
+ 'top_p': top_p,
1366
+ 'temperature': temperature,
1367
+ 'logits_processor': logits_processor,
1368
+ **kwargs
1369
+ }
1370
+ else:
1371
+ gen_kwargs = {
1372
+ 'max_length': max_length,
1373
+ 'num_beams': num_beams,
1374
+ 'do_sample': do_sample,
1375
+ 'top_p': top_p,
1376
+ 'temperature': temperature,
1377
+ 'logits_processor': logits_processor,
1378
+ **kwargs
1379
+ }
1380
+
1381
+ history.append({'role': role, 'content': query})
1382
+ history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
1383
+ inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
1384
+ outputs = self.generate(**inputs, **gen_kwargs)
1385
+ outputs = outputs.tolist()[0][len(inputs['input_ids'][0]):-1]
1386
+ response = tokenizer.decode(outputs)
1387
+ pattern = re.compile(r'.*?(?=<AI>|<用户>)', re.DOTALL)
1388
+ matches = pattern.findall(response)
1389
+ if len(matches) > 0:
1390
+ response = matches[0]
1391
+ history.append({'role': 'assistant', 'content': response})
1392
+ return response, history
1393
+
1394
+
1395
+ @add_start_docstrings(
1396
+ """
1397
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1398
+
1399
+ [`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1400
+ (e.g. GPT-2) do.
1401
+
1402
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1403
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1404
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1405
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1406
+ each row of the batch).
1407
+ """,
1408
+ MINICPM_START_DOCSTRING,
1409
+ )
1410
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1411
+ def __init__(self, config):
1412
+ super().__init__(config)
1413
+ self.num_labels = config.num_labels
1414
+ self.model = MiniCPMModel(config)
1415
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1416
+
1417
+ # Initialize weights and apply final processing
1418
+ self.post_init()
1419
+
1420
+ def get_input_embeddings(self):
1421
+ return self.model.embed_tokens
1422
+
1423
+ def set_input_embeddings(self, value):
1424
+ self.model.embed_tokens = value
1425
+
1426
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1427
+ def forward(
1428
+ self,
1429
+ input_ids: torch.LongTensor = None,
1430
+ attention_mask: Optional[torch.Tensor] = None,
1431
+ position_ids: Optional[torch.LongTensor] = None,
1432
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1433
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1434
+ labels: Optional[torch.LongTensor] = None,
1435
+ use_cache: Optional[bool] = None,
1436
+ output_attentions: Optional[bool] = None,
1437
+ output_hidden_states: Optional[bool] = None,
1438
+ return_dict: Optional[bool] = None,
1439
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1440
+ r"""
1441
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1442
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1443
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1444
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1445
+ """
1446
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1447
+
1448
+ transformer_outputs = self.model(
1449
+ input_ids,
1450
+ attention_mask=attention_mask,
1451
+ position_ids=position_ids,
1452
+ past_key_values=past_key_values,
1453
+ inputs_embeds=inputs_embeds,
1454
+ use_cache=use_cache,
1455
+ output_attentions=output_attentions,
1456
+ output_hidden_states=output_hidden_states,
1457
+ return_dict=return_dict,
1458
+ )
1459
+ hidden_states = transformer_outputs[0]
1460
+ logits = self.score(hidden_states)
1461
+
1462
+ if input_ids is not None:
1463
+ batch_size = input_ids.shape[0]
1464
+ else:
1465
+ batch_size = inputs_embeds.shape[0]
1466
+
1467
+ if self.config.pad_token_id is None and batch_size != 1:
1468
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
1469
+ if self.config.pad_token_id is None:
1470
+ sequence_lengths = -1
1471
+ else:
1472
+ if input_ids is not None:
1473
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1474
+ logits.device
1475
+ )
1476
+ else:
1477
+ sequence_lengths = -1
1478
+
1479
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1480
+
1481
+ loss = None
1482
+ if labels is not None:
1483
+ labels = labels.to(logits.device)
1484
+ if self.config.problem_type is None:
1485
+ if self.num_labels == 1:
1486
+ self.config.problem_type = 'regression'
1487
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1488
+ self.config.problem_type = 'single_label_classification'
1489
+ else:
1490
+ self.config.problem_type = 'multi_label_classification'
1491
+
1492
+ if self.config.problem_type == 'regression':
1493
+ loss_fct = MSELoss()
1494
+ if self.num_labels == 1:
1495
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1496
+ else:
1497
+ loss = loss_fct(pooled_logits, labels)
1498
+ elif self.config.problem_type == 'single_label_classification':
1499
+ loss_fct = CrossEntropyLoss()
1500
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1501
+ elif self.config.problem_type == 'multi_label_classification':
1502
+ loss_fct = BCEWithLogitsLoss()
1503
+ loss = loss_fct(pooled_logits, labels)
1504
+ if not return_dict:
1505
+ output = (pooled_logits,) + transformer_outputs[1:]
1506
+ return ((loss,) + output) if loss is not None else output
1507
+
1508
+ return SequenceClassifierOutputWithPast(
1509
+ loss=loss,
1510
+ logits=pooled_logits,
1511
+ past_key_values=transformer_outputs.past_key_values,
1512
+ hidden_states=transformer_outputs.hidden_states,
1513
+ attentions=transformer_outputs.attentions,
1514
+ )
convert/MiniCPM4-0.5B/special_tokens_map.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_end|>",
4
+ "<|im_start|>",
5
+ "<|tool_call|>",
6
+ "<|execute_start|>",
7
+ "<|execute_end|>",
8
+ "<|fim_prefix|>",
9
+ "<|fim_middle|>",
10
+ "<|fim_suffix|>"
11
+ ],
12
+ "bos_token": {
13
+ "content": "<s>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false
18
+ },
19
+ "eos_token": {
20
+ "content": "<|im_end|>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false
25
+ },
26
+ "unk_token": {
27
+ "content": "<unk>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
convert/MiniCPM4-0.5B/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
convert/MiniCPM4-0.5B/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb74d51116831c3bf65db812c553f94ab0c88dcf97a5bbb37e3504f6d359c530
3
+ size 1181204
convert/MiniCPM4-0.5B/tokenizer_config.json ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "73440": {
31
+ "content": "<|im_end|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "73441": {
39
+ "content": "<|im_start|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "73442": {
47
+ "content": "<|tool_call|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "73443": {
55
+ "content": "<|execute_start|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "73444": {
63
+ "content": "<|execute_end|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "73445": {
71
+ "content": "<|fim_prefix|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "73446": {
79
+ "content": "<|fim_middle|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "73447": {
87
+ "content": "<|fim_suffix|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ }
94
+ },
95
+ "additional_special_tokens": [
96
+ "<|im_end|>",
97
+ "<|im_start|>",
98
+ "<|tool_call|>",
99
+ "<|execute_start|>",
100
+ "<|execute_end|>",
101
+ "<|fim_prefix|>",
102
+ "<|fim_middle|>",
103
+ "<|fim_suffix|>"
104
+ ],
105
+ "bos_token": "<s>",
106
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
107
+ "clean_up_tokenization_spaces": false,
108
+ "eos_token": "<|im_end|>",
109
+ "legacy": true,
110
+ "model_max_length": 1000000000000000019884624838656,
111
+ "pad_token": null,
112
+ "sp_model_kwargs": {},
113
+ "spaces_between_special_tokens": false,
114
+ "tokenizer_class": "LlamaTokenizer",
115
+ "unk_token": "<unk>",
116
+ "use_default_system_prompt": false
117
+ }
convert/README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 模型转换
2
+
3
+ 1. 测试可用的依赖版本如下:
4
+
5
+ ```
6
+ torch==2.10.0
7
+ transformers==4.57.6
8
+ onnx==1.18.0
9
+ onnxruntime==1.22.0
10
+ einops==0.8.2
11
+ rknn-toolkit2==2.3.2
12
+ rkllm-toolkit==1.2.3
13
+ ```
14
+
15
+ 2. 下载模型
16
+
17
+ 从`https://huggingface.co/openbmb/VoxCPM1.5`下载模型,保存到`./VoxCPM1.5`文件夹。
18
+
19
+ 3. 转换模型
20
+
21
+ ```bash
22
+ python scripts/build_rk3588_pipeline.py --model-dir VoxCPM1.5
23
+ ```
24
+
25
+ 转换后的模型会放置在`build/rk3588/final_models/`.
26
+
27
+ ---
28
+
29
+ # Model Conversion
30
+
31
+ 1. Tested dependency versions:
32
+
33
+ ```
34
+ torch==2.10.0
35
+ transformers==4.57.6
36
+ onnx==1.18.0
37
+ onnxruntime==1.22.0
38
+ einops==0.8.2
39
+ rknn-toolkit2==2.3.2
40
+ rkllm-toolkit==1.2.3
41
+ ```
42
+
43
+ 2. Download the model
44
+
45
+ Download the model from `https://huggingface.co/openbmb/VoxCPM1.5` and save it to the `./VoxCPM1.5` directory.
46
+
47
+ 3. Convert the model
48
+
49
+ ```bash
50
+ python scripts/build_rk3588_pipeline.py --model-dir VoxCPM1.5
51
+ ```
52
+
53
+ The converted models will be placed in `build/rk3588/final_models/`.
convert/scripts/build_rk3588_pipeline.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import contextlib
3
+ import json
4
+ import math
5
+ import os
6
+ from pathlib import Path
7
+ import shutil
8
+ import subprocess
9
+
10
+ from rknn.api import RKNN
11
+
12
+
13
+ REPO_ROOT = Path(__file__).resolve().parent.parent
14
+ SRC_DIR = REPO_ROOT / "src"
15
+
16
+ TOKENIZER_SUPPORT_FILES = [
17
+ "tokenizer.json",
18
+ "tokenizer_config.json",
19
+ "tokenizer.model",
20
+ "special_tokens_map.json",
21
+ "added_tokens.json",
22
+ "generation_config.json",
23
+ "README.md",
24
+ "modeling_minicpm.py",
25
+ "configuration_minicpm.py",
26
+ ]
27
+
28
+ PATCH_SIZE = 4
29
+ LATENT_DIM = 64
30
+ HIDDEN_SIZE = 1024
31
+ CHUNK_SIZE = math.prod([2, 3, 6, 7, 7])
32
+ VAE_BLOCK_LATENT_LEN = 64
33
+
34
+ RKNN_SPECS = [
35
+ ("audio_vae_encode.onnx", "audio_vae_encode.rknn", ["audio_wave"], [[1, 1, CHUNK_SIZE * VAE_BLOCK_LATENT_LEN]], None),
36
+ ("audio_vae_decode.onnx", "audio_vae_decode.rknn", ["latent"], [[1, LATENT_DIM, VAE_BLOCK_LATENT_LEN]], None),
37
+ ("locenc.onnx", "locenc_64.rknn", ["x"], [[1, 64, PATCH_SIZE, LATENT_DIM]], None),
38
+ ("locenc.onnx", "locenc_1.rknn", ["x"], [[1, 1, PATCH_SIZE, LATENT_DIM]], None),
39
+ ("fsq_layer.onnx", "fsq_layer.rknn", ["hidden"], [[1, 64, HIDDEN_SIZE]], [[[1, 64, HIDDEN_SIZE]], [[1, 1, HIDDEN_SIZE]]]),
40
+ ("stop_head.onnx", "stop_head.rknn", ["hidden"], [[1, HIDDEN_SIZE]], None),
41
+ ("lm_to_dit_proj.onnx", "lm_to_dit_proj.rknn", ["input"], [[1, HIDDEN_SIZE]], None),
42
+ ("res_to_dit_proj.onnx", "res_to_dit_proj.rknn", ["input"], [[1, HIDDEN_SIZE]], None),
43
+ ("dit_step.onnx", "dit_step.rknn", ["x", "mu", "t", "cond", "dt"], [[1, LATENT_DIM, PATCH_SIZE], [1, HIDDEN_SIZE], [1], [1, LATENT_DIM, PATCH_SIZE], [1]], None),
44
+ ]
45
+
46
+
47
+ def run(cmd: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None):
48
+ print("+", " ".join(cmd))
49
+ subprocess.run(cmd, cwd=cwd, env=env, check=True)
50
+
51
+
52
+ @contextlib.contextmanager
53
+ def pushd(path: Path):
54
+ prev = Path.cwd()
55
+ os.chdir(path)
56
+ try:
57
+ yield
58
+ finally:
59
+ os.chdir(prev)
60
+
61
+
62
+ def ensure_dir(path: Path):
63
+ path.mkdir(parents=True, exist_ok=True)
64
+
65
+
66
+ def copy_if_exists(src: Path, dst: Path):
67
+ if src.exists():
68
+ shutil.copy2(src, dst)
69
+
70
+
71
+ def sync_hf_support_files(minicpm_dir: Path, target_dir: Path):
72
+ ensure_dir(target_dir)
73
+ metadata_json = target_dir / "configuration.json"
74
+ if metadata_json.exists():
75
+ metadata_json.unlink()
76
+ for name in TOKENIZER_SUPPORT_FILES:
77
+ copy_if_exists(minicpm_dir / name, target_dir / name)
78
+
79
+
80
+ def patch_hf_config(reference_config_path: Path, target_config_path: Path, architecture: str):
81
+ reference = json.loads(reference_config_path.read_text())
82
+ target = json.loads(target_config_path.read_text())
83
+ if "auto_map" in reference:
84
+ target["auto_map"] = reference["auto_map"]
85
+ target["architectures"] = [architecture]
86
+ target_config_path.write_text(json.dumps(target, indent=2, ensure_ascii=False) + "\n")
87
+
88
+
89
+ def export_onnx(model_dir: Path, onnx_dir: Path):
90
+ ensure_dir(onnx_dir)
91
+ env = os.environ.copy()
92
+ env["PYTHONPATH"] = str(SRC_DIR) + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
93
+ run(
94
+ [
95
+ "python",
96
+ str(REPO_ROOT / "scripts" / "export_onnx.py"),
97
+ "--model-dir",
98
+ str(model_dir),
99
+ "--out-dir",
100
+ str(onnx_dir),
101
+ "--dump-embeddings",
102
+ ],
103
+ cwd=REPO_ROOT,
104
+ env=env,
105
+ )
106
+
107
+
108
+ def convert_one_rknn(
109
+ onnx_dir: Path,
110
+ rknn_dir: Path,
111
+ spec: tuple[str, str, list[str], list[list[int]] | None, list[list[list[int]]] | None],
112
+ target_platform: str,
113
+ ):
114
+ onnx_name, rknn_name, inputs, input_size_list, dynamic_input = spec
115
+ onnx_path = onnx_dir / onnx_name
116
+ out_path = rknn_dir / rknn_name
117
+ ensure_dir(rknn_dir)
118
+
119
+ if not onnx_path.exists():
120
+ raise FileNotFoundError(f"Missing ONNX file: {onnx_path}")
121
+
122
+ rknn = RKNN(verbose=False)
123
+ ret = rknn.config(target_platform=target_platform, dynamic_input=dynamic_input)
124
+ if ret != 0:
125
+ raise RuntimeError(f"RKNN config failed for {onnx_name}, ret={ret}")
126
+
127
+ load_kwargs = {"model": str(onnx_path)}
128
+ if input_size_list is not None:
129
+ load_kwargs["inputs"] = inputs
130
+ load_kwargs["input_size_list"] = input_size_list
131
+
132
+ ret = rknn.load_onnx(**load_kwargs)
133
+ if ret != 0:
134
+ raise RuntimeError(f"RKNN load_onnx failed for {onnx_name}, ret={ret}")
135
+
136
+ ret = rknn.build(do_quantization=False)
137
+ if ret != 0:
138
+ raise RuntimeError(f"RKNN build failed for {onnx_name}, ret={ret}")
139
+
140
+ ret = rknn.export_rknn(str(out_path))
141
+ if ret != 0:
142
+ raise RuntimeError(f"RKNN export failed for {out_path}, ret={ret}")
143
+ rknn.release()
144
+
145
+
146
+ def export_rknn(onnx_dir: Path, rknn_dir: Path, target_platform: str):
147
+ ensure_dir(rknn_dir)
148
+ copy_if_exists(onnx_dir / "embed_tokens.npy", rknn_dir / "embed_tokens.npy")
149
+ with pushd(rknn_dir):
150
+ for spec in RKNN_SPECS:
151
+ convert_one_rknn(onnx_dir, rknn_dir, spec, target_platform)
152
+
153
+
154
+ def collect_final_models(build_dir: Path):
155
+ final_dir = build_dir / "final_models"
156
+ ensure_dir(final_dir)
157
+
158
+ for name in [
159
+ "audio_vae_encode.rknn",
160
+ "audio_vae_decode.rknn",
161
+ "locenc_64.rknn",
162
+ "locenc_1.rknn",
163
+ "fsq_layer.rknn",
164
+ "stop_head.rknn",
165
+ "lm_to_dit_proj.rknn",
166
+ "res_to_dit_proj.rknn",
167
+ "dit_step.rknn",
168
+ "embed_tokens.npy",
169
+ ]:
170
+ copy_if_exists(build_dir / "rknn" / name, final_dir / name)
171
+
172
+ copy_if_exists(build_dir / "rkllm" / "base" / "language_model.rkllm", final_dir / "base_lm.rkllm")
173
+ copy_if_exists(build_dir / "rkllm" / "residual" / "language_model.rkllm", final_dir / "residual_lm.rkllm")
174
+
175
+
176
+ def convert_vox_to_hf(vox_config: Path, vox_state: Path, minicpm_dir: Path, base_out: Path, residual_out: Path):
177
+ ensure_dir(base_out)
178
+ ensure_dir(residual_out)
179
+ run(
180
+ [
181
+ "python",
182
+ str(REPO_ROOT / "scripts" / "convert_vox_minicpm_to_hf.py"),
183
+ "--vox-config",
184
+ str(vox_config),
185
+ "--vox-state",
186
+ str(vox_state),
187
+ "--minicpm-dir",
188
+ str(minicpm_dir),
189
+ "--out-dir",
190
+ str(base_out),
191
+ "--out-residual-dir",
192
+ str(residual_out),
193
+ ],
194
+ cwd=REPO_ROOT,
195
+ )
196
+ sync_hf_support_files(minicpm_dir, base_out)
197
+ sync_hf_support_files(minicpm_dir, residual_out)
198
+ patch_hf_config(minicpm_dir / "config.json", base_out / "config.json", "MiniCPMForCausalLM")
199
+ patch_hf_config(minicpm_dir / "config.json", residual_out / "config.json", "MiniCPMModel")
200
+
201
+
202
+ def export_rkllm(hf_dir: Path, out_path: Path, target_platform: str, num_npu_core: int):
203
+ hf_home = out_path.parent.parent.parent / "cache" / "huggingface"
204
+ ensure_dir(hf_home)
205
+ env = os.environ.copy()
206
+ env["HF_HOME"] = str(hf_home)
207
+ env["HUGGINGFACE_HUB_CACHE"] = str(hf_home / "hub")
208
+ env["TRANSFORMERS_CACHE"] = str(hf_home / "transformers")
209
+ run(
210
+ [
211
+ "python",
212
+ str(REPO_ROOT / "scripts" / "export_rkllm.py"),
213
+ "--model-dir",
214
+ str(hf_dir),
215
+ "--output",
216
+ str(out_path),
217
+ "--target-platform",
218
+ target_platform,
219
+ "--num-npu-core",
220
+ str(num_npu_core),
221
+ "--hf-home",
222
+ str(hf_home),
223
+ ],
224
+ cwd=REPO_ROOT,
225
+ env=env,
226
+ )
227
+
228
+
229
+ def write_manifest(build_dir: Path, model_dir: Path, minicpm_dir: Path):
230
+ manifest = {
231
+ "model_dir": str(model_dir),
232
+ "minicpm_dir": str(minicpm_dir),
233
+ "onnx_dir": str(build_dir / "onnx"),
234
+ "rknn_dir": str(build_dir / "rknn"),
235
+ "hf_base_dir": str(build_dir / "hf" / "base"),
236
+ "hf_residual_dir": str(build_dir / "hf" / "residual"),
237
+ "rkllm_base_model": str(build_dir / "rkllm" / "base" / "language_model.rkllm"),
238
+ "rkllm_residual_model": str(build_dir / "rkllm" / "residual" / "language_model.rkllm"),
239
+ "output_dir": str(build_dir / "output"),
240
+ }
241
+ ensure_dir(build_dir)
242
+ (build_dir / "build_manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n")
243
+
244
+
245
+ def main():
246
+ parser = argparse.ArgumentParser(description="Rebuild the VoxCPM1.5 RK3588 deployment artifacts from scratch.")
247
+ parser.add_argument("--model-dir", default="VoxCPM1.5", help="Path to the original VoxCPM1.5 model directory.")
248
+ parser.add_argument("--minicpm-dir", default="MiniCPM4-0.5B", help="Path to the reference MiniCPM4-0.5B directory.")
249
+ parser.add_argument("--build-dir", default="build/rk3588", help="Output root for rebuilt artifacts.")
250
+ parser.add_argument("--target-platform", default="rk3588", help="RK target platform.")
251
+ parser.add_argument("--skip-onnx", action="store_true", help="Skip ONNX export.")
252
+ parser.add_argument("--skip-rknn", action="store_true", help="Skip RKNN conversion.")
253
+ parser.add_argument("--skip-hf", action="store_true", help="Skip Vox->HF conversion.")
254
+ parser.add_argument("--skip-rkllm", action="store_true", help="Skip RKLLM export.")
255
+ args = parser.parse_args()
256
+
257
+ model_dir = (REPO_ROOT / args.model_dir).resolve()
258
+ minicpm_dir = (REPO_ROOT / args.minicpm_dir).resolve()
259
+ build_dir = (REPO_ROOT / args.build_dir).resolve()
260
+ onnx_dir = build_dir / "onnx"
261
+ rknn_dir = build_dir / "rknn"
262
+ hf_base_dir = build_dir / "hf" / "base"
263
+ hf_residual_dir = build_dir / "hf" / "residual"
264
+ rkllm_base_path = build_dir / "rkllm" / "base" / "language_model.rkllm"
265
+ rkllm_residual_path = build_dir / "rkllm" / "residual" / "language_model.rkllm"
266
+ ensure_dir(build_dir / "output")
267
+
268
+ if not args.skip_onnx:
269
+ export_onnx(model_dir, onnx_dir)
270
+ if not args.skip_rknn:
271
+ export_rknn(onnx_dir, rknn_dir, args.target_platform)
272
+ if not args.skip_hf:
273
+ convert_vox_to_hf(
274
+ vox_config=model_dir / "config.json",
275
+ vox_state=model_dir / "model.safetensors",
276
+ minicpm_dir=minicpm_dir,
277
+ base_out=hf_base_dir,
278
+ residual_out=hf_residual_dir,
279
+ )
280
+ if not args.skip_rkllm:
281
+ export_rkllm(hf_base_dir, rkllm_base_path, args.target_platform, num_npu_core=1)
282
+ export_rkllm(hf_residual_dir, rkllm_residual_path, args.target_platform, num_npu_core=3)
283
+
284
+ collect_final_models(build_dir)
285
+ write_manifest(build_dir, model_dir, minicpm_dir)
286
+ print(f"Saved: {build_dir / 'build_manifest.json'}")
287
+
288
+
289
+ if __name__ == "__main__":
290
+ main()
convert/scripts/convert_vox_minicpm_to_hf.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import sys
5
+ import torch
6
+ import math
7
+
8
+ from safetensors.torch import load_file
9
+
10
+
11
+ def load_vox_configs(vox_config_path: str) -> tuple[dict, dict]:
12
+ """Return (base_lm_cfg, residual_cfg)."""
13
+ with open(vox_config_path, "r") as f:
14
+ data = json.load(f)
15
+
16
+ base = data["lm_config"]
17
+ rope = base.get("rope_scaling")
18
+ if rope:
19
+ rope = dict(rope)
20
+ # Vox config uses "type", transformers expects "rope_type"
21
+ if "type" in rope and "rope_type" not in rope:
22
+ rope["rope_type"] = rope.pop("type")
23
+ base["rope_scaling"] = rope
24
+
25
+ residual = dict(base)
26
+ residual["num_hidden_layers"] = data.get("residual_lm_num_layers", residual["num_hidden_layers"])
27
+ # keep vocab_size for easier loading; Vox sets 0 because inputs_embeds are provided
28
+ residual.setdefault("vocab_size", base.get("vocab_size"))
29
+
30
+ # Align transformers residual scaling with Vox (no scaling when use_mup=False)
31
+ if not base.get("use_mup", True):
32
+ base["scale_depth"] = math.sqrt(base["num_hidden_layers"])
33
+ residual["scale_depth"] = math.sqrt(residual["num_hidden_layers"])
34
+ return base, residual
35
+
36
+
37
+ def build_hf_config(lm_cfg: dict, minicpm_dir: str):
38
+ sys.path.insert(0, minicpm_dir)
39
+ from configuration_minicpm import MiniCPMConfig
40
+
41
+ return MiniCPMConfig(**lm_cfg)
42
+
43
+
44
+ def convert_state_dict(vox_state_path: str, lm_prefix: str) -> dict:
45
+ if vox_state_path.endswith(".safetensors"):
46
+ raw = load_file(vox_state_path, device="cpu")
47
+ else:
48
+ raw = torch.load(vox_state_path, map_location="cpu")
49
+ sd = raw["state_dict"] if isinstance(raw, dict) and "state_dict" in raw else raw
50
+
51
+ out = {}
52
+ prefix = f"{lm_prefix}."
53
+ for k, v in sd.items():
54
+ if not k.startswith(prefix):
55
+ continue
56
+ new_k = "model." + k[len(prefix) :]
57
+ out[new_k] = v
58
+
59
+ # Tie lm_head to embeddings for MiniCPMForCausalLM
60
+ if "model.embed_tokens.weight" in out:
61
+ out["lm_head.weight"] = out["model.embed_tokens.weight"]
62
+ return out
63
+
64
+
65
+ def main():
66
+ parser = argparse.ArgumentParser(description="Convert VoxCPM MiniCPM weights to transformers format")
67
+ parser.add_argument(
68
+ "--vox-config",
69
+ default="VoxCPM1.5/config.json",
70
+ help="Path to VoxCPM config.json (used to read lm_config)",
71
+ )
72
+ parser.add_argument(
73
+ "--vox-state",
74
+ default="VoxCPM1.5/model.safetensors",
75
+ help="Path to VoxCPM checkpoint containing base_lm weights",
76
+ )
77
+ parser.add_argument(
78
+ "--minicpm-dir",
79
+ default="MiniCPM4-0.5B",
80
+ help="Path to local MiniCPM4-0.5B directory (provides configuration_minicpm.py)",
81
+ )
82
+ parser.add_argument(
83
+ "--out-dir",
84
+ default="converted-minicpm-hf",
85
+ help="Output directory for base LM transformers-style checkpoint",
86
+ )
87
+ parser.add_argument(
88
+ "--out-residual-dir",
89
+ default="converted-minicpm-residual-hf",
90
+ help="Output directory for residual LM checkpoint",
91
+ )
92
+ args = parser.parse_args()
93
+
94
+ os.makedirs(args.out_dir, exist_ok=True)
95
+ os.makedirs(args.out_residual_dir, exist_ok=True)
96
+
97
+ base_cfg, residual_cfg = load_vox_configs(args.vox_config)
98
+
99
+ hf_config = build_hf_config(base_cfg, args.minicpm_dir)
100
+ hf_config.save_pretrained(args.out_dir)
101
+
102
+ print("Loaded Vox lm_config and wrote transformers config to", args.out_dir)
103
+
104
+ hf_state = convert_state_dict(args.vox_state, lm_prefix="base_lm")
105
+ out_path = os.path.join(args.out_dir, "pytorch_model.bin")
106
+ torch.save(hf_state, out_path)
107
+ print("Saved base LM weights to", out_path)
108
+
109
+ residual_hf_config = build_hf_config(residual_cfg, args.minicpm_dir)
110
+ residual_hf_config.save_pretrained(args.out_residual_dir)
111
+ residual_state = convert_state_dict(args.vox_state, lm_prefix="residual_lm")
112
+ residual_out_path = os.path.join(args.out_residual_dir, "pytorch_model.bin")
113
+ torch.save(residual_state, residual_out_path)
114
+ print("Saved residual LM weights to", residual_out_path)
115
+
116
+ print("Load with MiniCPMForCausalLM.from_pretrained(...) or MiniCPMModel.from_pretrained(...).")
117
+
118
+
119
+ if __name__ == "__main__":
120
+ main()
convert/scripts/export_onnx.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+ import torch
5
+ from torch import nn
6
+
7
+ REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
8
+ SRC_DIR = os.path.join(REPO_ROOT, "src")
9
+ if SRC_DIR not in sys.path:
10
+ sys.path.insert(0, SRC_DIR)
11
+
12
+ from voxcpm.model.voxcpm import VoxCPMModel
13
+
14
+
15
+ def remove_weight_norm(module: nn.Module):
16
+ """Strip weight_norm wrappers for cleaner ONNX graphs."""
17
+ for name, child in module.named_children():
18
+ remove_weight_norm(child)
19
+ if isinstance(child, (nn.Conv1d, nn.ConvTranspose1d)):
20
+ try:
21
+ torch.nn.utils.remove_weight_norm(child)
22
+ except ValueError:
23
+ # not wrapped, skip
24
+ pass
25
+
26
+
27
+ class VAEEncodeWrapper(nn.Module):
28
+ def __init__(self, audio_vae: nn.Module):
29
+ super().__init__()
30
+ self.audio_vae = audio_vae
31
+
32
+ def forward(self, audio_wave: torch.Tensor):
33
+ return self.audio_vae.encode(audio_wave, self.audio_vae.sample_rate)
34
+
35
+
36
+ class VAEDecodeWrapper(nn.Module):
37
+ def __init__(self, audio_vae: nn.Module):
38
+ super().__init__()
39
+ self.audio_vae = audio_vae
40
+
41
+ def forward(self, latent: torch.Tensor):
42
+ return self.audio_vae.decode(latent)
43
+
44
+
45
+ class LocEncWrapper(nn.Module):
46
+ def __init__(self, locenc: nn.Module):
47
+ super().__init__()
48
+ self.locenc = locenc
49
+
50
+ def forward(self, x: torch.Tensor):
51
+ # x: [B, T, P, D]
52
+ return self.locenc(x)
53
+
54
+
55
+ class LocEncLmWrapper(nn.Module):
56
+ """LocEnc with enc_to_lm projection fused in a single graph."""
57
+
58
+ def __init__(self, locenc: nn.Module, proj: nn.Module):
59
+ super().__init__()
60
+ self.locenc = locenc
61
+ self.proj = proj
62
+
63
+ def forward(self, x: torch.Tensor):
64
+ # x: [B, T, P, D]
65
+ hidden = self.locenc(x)
66
+ return self.proj(hidden)
67
+
68
+
69
+ class FSQWrapper(nn.Module):
70
+ def __init__(self, fsq: nn.Module):
71
+ super().__init__()
72
+ self.fsq = fsq
73
+
74
+ def forward(self, hidden: torch.Tensor):
75
+ return self.fsq(hidden)
76
+
77
+
78
+ class StopHeadWrapper(nn.Module):
79
+ def __init__(self, stop_proj: nn.Linear, stop_actn: nn.Module, stop_head: nn.Linear):
80
+ super().__init__()
81
+ self.stop_proj = stop_proj
82
+ self.stop_actn = stop_actn
83
+ self.stop_head = stop_head
84
+
85
+ def forward(self, hidden: torch.Tensor):
86
+ hidden = self.stop_proj(hidden)
87
+ hidden = self.stop_actn(hidden)
88
+ return self.stop_head(hidden)
89
+
90
+
91
+ class CFMWrapper(nn.Module):
92
+ """
93
+ Wrapper for one diffusion step block.
94
+
95
+ Note: the number of diffusion steps (n_timesteps) is fixed at export time.
96
+ """
97
+
98
+ def __init__(self, cfm: nn.Module, patch_size: int, n_timesteps: int, cfg_value: float):
99
+ super().__init__()
100
+ self.cfm = cfm
101
+ self.patch_size = patch_size
102
+ self.n_timesteps = n_timesteps
103
+ self.cfg_value = cfg_value
104
+
105
+ def forward(self, mu: torch.Tensor, cond: torch.Tensor):
106
+ # mu: [B, H_dit], cond: [B, D_feat, P]
107
+ return self.cfm(
108
+ mu=mu,
109
+ n_timesteps=self.n_timesteps,
110
+ patch_size=self.patch_size,
111
+ cond=cond,
112
+ cfg_value=self.cfg_value,
113
+ )
114
+
115
+
116
+ class DiTStepWrapper(nn.Module):
117
+ """
118
+ Wrapper for a single VoxCPMLocDiT forward (one diffusion score estimation step).
119
+ Inputs match VoxCPMLocDiT.forward: x, mu, t, cond, dt.
120
+ """
121
+
122
+ def __init__(self, dit: nn.Module):
123
+ super().__init__()
124
+ self.dit = dit
125
+
126
+ def forward(self, x: torch.Tensor, mu: torch.Tensor, t: torch.Tensor, cond: torch.Tensor, dt: torch.Tensor):
127
+ return self.dit(x, mu, t, cond, dt)
128
+
129
+
130
+ def export(model: nn.Module, inputs, path: str, dynamic_axes: dict, opset: int):
131
+ os.makedirs(os.path.dirname(path), exist_ok=True)
132
+ torch.onnx.export(
133
+ model,
134
+ inputs,
135
+ path,
136
+ opset_version=opset,
137
+ dynamo=True,
138
+ do_constant_folding=True,
139
+ input_names=list(dynamic_axes.keys()),
140
+ output_names=["output"],
141
+ dynamic_axes=dynamic_axes,
142
+ )
143
+ print(f"Saved: {path}")
144
+
145
+
146
+ def main():
147
+ parser = argparse.ArgumentParser(description="Export VoxCPM submodules to ONNX (LLM excluded).")
148
+ parser.add_argument("--model-dir", required=True, help="Path to VoxCPM model directory (config/weights).")
149
+ parser.add_argument("--out-dir", default="onnx_exports", help="Output directory for ONNX files.")
150
+ parser.add_argument("--opset", type=int, default=18, help="ONNX opset version.")
151
+ parser.add_argument("--audio-samples", type=int, default=1280, help="Dummy audio length for encoder export.")
152
+ parser.add_argument("--latent-steps", type=int, default=6, help="Dummy latent steps for decoder export.")
153
+ parser.add_argument("--seq-len", type=int, default=4, help="Dummy sequence length for LocEnc/FSQ export.")
154
+ parser.add_argument("--dit-step-t", type=float, default=0.5, help="Dummy diffusion time for DiT step export.")
155
+ parser.add_argument("--force-fp32", action="store_true", help="Force submodules to float32 for ONNX export.")
156
+ parser.add_argument("--dump-embeddings", action="store_true", help="Dump base_lm.embed_tokens weights to npy.")
157
+ args = parser.parse_args()
158
+
159
+ device = torch.device("cpu")
160
+ # Load full model once, then peel submodules; keep optimize disabled.
161
+ full_model = VoxCPMModel.from_local(args.model_dir, optimize=False).to(device).eval()
162
+ if args.force_fp32 or full_model.config.dtype != "float32":
163
+ full_model.config.dtype = "float32"
164
+ full_model = full_model.to(torch.float32)
165
+ full_model.audio_vae = full_model.audio_vae.to(torch.float32)
166
+ remove_weight_norm(full_model)
167
+
168
+ # Audio VAE encode
169
+ vae_enc = VAEEncodeWrapper(full_model.audio_vae).to(device).eval()
170
+ dummy_audio = torch.randn(1, 1, args.audio_samples, device=device)
171
+ export(
172
+ vae_enc,
173
+ dummy_audio,
174
+ os.path.join(args.out_dir, "audio_vae_encode.onnx"),
175
+ dynamic_axes={"audio_wave": {0: "batch", 2: "samples"}},
176
+ opset=args.opset,
177
+ )
178
+
179
+ # Audio VAE decode
180
+ vae_dec = VAEDecodeWrapper(full_model.audio_vae).to(device).eval()
181
+ dummy_latent = torch.randn(1, full_model.audio_vae.latent_dim, args.latent_steps, device=device)
182
+ export(
183
+ vae_dec,
184
+ dummy_latent,
185
+ os.path.join(args.out_dir, "audio_vae_decode.onnx"),
186
+ dynamic_axes={"latent": {0: "batch", 2: "latent_steps"}},
187
+ opset=args.opset,
188
+ )
189
+
190
+ # LocEnc with enc_to_lm projection fused
191
+ locenc = LocEncLmWrapper(full_model.feat_encoder, full_model.enc_to_lm_proj).to(device).eval()
192
+ dummy_seq = torch.randn(1, args.seq_len, full_model.patch_size, full_model.feat_dim, device=device)
193
+ export(
194
+ locenc,
195
+ dummy_seq,
196
+ os.path.join(args.out_dir, "locenc.onnx"),
197
+ dynamic_axes={"x": {0: "batch", 1: "seq_len"}},
198
+ opset=args.opset,
199
+ )
200
+
201
+ # FSQ layer
202
+ fsq = FSQWrapper(full_model.fsq_layer).to(device).eval()
203
+ hidden_size = full_model.config.lm_config.hidden_size
204
+ dummy_hidden = torch.randn(1, args.seq_len, hidden_size, device=device)
205
+ export(
206
+ fsq,
207
+ dummy_hidden,
208
+ os.path.join(args.out_dir, "fsq_layer.onnx"),
209
+ dynamic_axes={"hidden": {0: "batch", 1: "seq_len"}},
210
+ opset=args.opset,
211
+ )
212
+
213
+ # Stop head
214
+ stop = StopHeadWrapper(full_model.stop_proj, full_model.stop_actn, full_model.stop_head).to(device).eval()
215
+ dummy_stop_inp = torch.randn(1, hidden_size, device=device)
216
+ export(
217
+ stop,
218
+ dummy_stop_inp,
219
+ os.path.join(args.out_dir, "stop_head.onnx"),
220
+ dynamic_axes={"hidden": {0: "batch"}},
221
+ opset=args.opset,
222
+ )
223
+
224
+ # Projection layers
225
+ # export(
226
+ # full_model.enc_to_lm_proj,
227
+ # dummy_hidden,
228
+ # os.path.join(args.out_dir, "enc_to_lm_proj.onnx"),
229
+ # dynamic_axes={"input": {0: "batch", 1: "seq_len"}},
230
+ # opset=args.opset,
231
+ # )
232
+ lm_hidden = torch.randn(1, full_model.config.lm_config.hidden_size, device=device)
233
+ export(
234
+ full_model.lm_to_dit_proj,
235
+ lm_hidden,
236
+ os.path.join(args.out_dir, "lm_to_dit_proj.onnx"),
237
+ dynamic_axes={"input": {0: "batch"}},
238
+ opset=args.opset,
239
+ )
240
+ export(
241
+ full_model.res_to_dit_proj,
242
+ lm_hidden,
243
+ os.path.join(args.out_dir, "res_to_dit_proj.onnx"),
244
+ dynamic_axes={"input": {0: "batch"}},
245
+ opset=args.opset,
246
+ )
247
+
248
+ # VoxCPMLocDiT single step (score function)
249
+ dit_step = DiTStepWrapper(full_model.feat_decoder.estimator).to(device).eval()
250
+ dummy_x = torch.randn(1, full_model.feat_dim, full_model.patch_size, device=device)
251
+ dummy_mu = torch.randn(1, full_model.config.dit_config.hidden_dim, device=device)
252
+ dummy_t = torch.full((1,), args.dit_step_t, device=device)
253
+ dummy_dt = torch.full((1,), 0.0, device=device)
254
+ dummy_cond = torch.randn(1, full_model.feat_dim, full_model.patch_size, device=device)
255
+ export(
256
+ dit_step,
257
+ (dummy_x, dummy_mu, dummy_t, dummy_cond, dummy_dt),
258
+ os.path.join(args.out_dir, "dit_step.onnx"),
259
+ dynamic_axes={
260
+ "x": {0: "batch"},
261
+ "mu": {0: "batch"},
262
+ "t": {0: "batch"},
263
+ "cond": {0: "batch"},
264
+ "dt": {0: "batch"},
265
+ },
266
+ opset=args.opset,
267
+ )
268
+
269
+ # # UnifiedCFM + VoxCPMLocDiT (single-step sampler unrolled with fixed n_timesteps)
270
+ # cfm = CFMWrapper(
271
+ # full_model.feat_decoder,
272
+ # patch_size=full_model.patch_size,
273
+ # n_timesteps=args.cfm_steps,
274
+ # cfg_value=args.cfg_value,
275
+ # ).to(device).eval()
276
+ # dummy_mu = torch.randn(1, full_model.config.dit_config.hidden_dim, device=device)
277
+ # dummy_cond = torch.randn(1, full_model.feat_dim, full_model.patch_size, device=device)
278
+ # export(
279
+ # cfm,
280
+ # (dummy_mu, dummy_cond),
281
+ # os.path.join(args.out_dir, "cfm_step.onnx"),
282
+ # dynamic_axes={"mu": {0: "batch"}, "cond": {0: "batch"}},
283
+ # opset=args.opset,
284
+ # )
285
+
286
+ if args.dump_embeddings and hasattr(full_model.base_lm, "embed_tokens"):
287
+ import numpy as np
288
+ emb = full_model.base_lm.embed_tokens.weight.detach().cpu().numpy()
289
+ os.makedirs(args.out_dir, exist_ok=True)
290
+ np.save(os.path.join(args.out_dir, "embed_tokens.npy"), emb)
291
+ print(f"Saved: {os.path.join(args.out_dir, 'embed_tokens.npy')}")
292
+
293
+ print("Done.")
294
+
295
+
296
+ if __name__ == "__main__":
297
+ main()
convert/scripts/export_rkllm.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ from pathlib import Path
4
+
5
+ from rkllm.api import RKLLM
6
+
7
+
8
+ def export_rkllm(
9
+ model_dir: Path,
10
+ output_path: Path,
11
+ target_platform: str,
12
+ num_npu_core: int,
13
+ optimization_level: int,
14
+ ):
15
+ llm = RKLLM()
16
+ ret = llm.load_huggingface(model=str(model_dir), model_lora=None, device="cpu")
17
+ if ret != 0:
18
+ raise RuntimeError(f"load_huggingface failed for {model_dir}, ret={ret}")
19
+
20
+ ret = llm.build(
21
+ do_quantization=False,
22
+ optimization_level=optimization_level,
23
+ quantized_dtype="w8a8",
24
+ quantized_algorithm="normal",
25
+ target_platform=target_platform,
26
+ num_npu_core=num_npu_core,
27
+ extra_qparams=None,
28
+ )
29
+ if ret != 0:
30
+ raise RuntimeError(f"RKLLM build failed for {model_dir}, ret={ret}")
31
+
32
+ output_path.parent.mkdir(parents=True, exist_ok=True)
33
+ ret = llm.export_rkllm(str(output_path))
34
+ if ret != 0:
35
+ raise RuntimeError(f"export_rkllm failed for {output_path}, ret={ret}")
36
+
37
+
38
+ def main():
39
+ parser = argparse.ArgumentParser(description="Export a HuggingFace-format MiniCPM model to RKLLM.")
40
+ parser.add_argument("--model-dir", required=True, help="Input HuggingFace model directory.")
41
+ parser.add_argument("--output", required=True, help="Output .rkllm path.")
42
+ parser.add_argument("--target-platform", default="rk3588", help="RK target platform.")
43
+ parser.add_argument("--num-npu-core", type=int, default=1, help="NPU cores for RKLLM build.")
44
+ parser.add_argument("--optimization-level", type=int, default=1, help="RKLLM optimization level.")
45
+ parser.add_argument("--hf-home", default=None, help="Optional writable Hugging Face cache root.")
46
+ args = parser.parse_args()
47
+
48
+ if args.hf_home:
49
+ hf_home = str(Path(args.hf_home).resolve())
50
+ os.environ["HF_HOME"] = hf_home
51
+ os.environ["HUGGINGFACE_HUB_CACHE"] = str(Path(hf_home) / "hub")
52
+ os.environ["TRANSFORMERS_CACHE"] = str(Path(hf_home) / "transformers")
53
+
54
+ export_rkllm(
55
+ model_dir=Path(args.model_dir),
56
+ output_path=Path(args.output),
57
+ target_platform=args.target_platform,
58
+ num_npu_core=args.num_npu_core,
59
+ optimization_level=args.optimization_level,
60
+ )
61
+ print(f"Saved: {args.output}")
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
convert/src/voxcpm/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .core import VoxCPM
2
+
3
+ __all__ = [
4
+ "VoxCPM",
5
+ ]
convert/src/voxcpm/cli.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ VoxCPM Command Line Interface
4
+
5
+ Unified CLI for voice cloning, direct TTS synthesis, and batch processing.
6
+ """
7
+
8
+ import argparse
9
+ import os
10
+ import sys
11
+ from pathlib import Path
12
+ import soundfile as sf
13
+
14
+ from voxcpm.core import VoxCPM
15
+
16
+
17
+ # -----------------------------
18
+ # Validators
19
+ # -----------------------------
20
+
21
+ def validate_file_exists(file_path: str, file_type: str = "file") -> Path:
22
+ path = Path(file_path)
23
+ if not path.exists():
24
+ raise FileNotFoundError(f"{file_type} '{file_path}' does not exist")
25
+ return path
26
+
27
+
28
+ def validate_output_path(output_path: str) -> Path:
29
+ path = Path(output_path)
30
+ path.parent.mkdir(parents=True, exist_ok=True)
31
+ return path
32
+
33
+
34
+ def validate_ranges(args, parser):
35
+ """Validate numeric argument ranges."""
36
+ if not (0.1 <= args.cfg_value <= 10.0):
37
+ parser.error("--cfg-value must be between 0.1 and 10.0")
38
+
39
+ if not (1 <= args.inference_timesteps <= 100):
40
+ parser.error("--inference-timesteps must be between 1 and 100")
41
+
42
+ if args.lora_r <= 0:
43
+ parser.error("--lora-r must be a positive integer")
44
+
45
+ if args.lora_alpha <= 0:
46
+ parser.error("--lora-alpha must be a positive integer")
47
+
48
+ if not (0.0 <= args.lora_dropout <= 1.0):
49
+ parser.error("--lora-dropout must be between 0.0 and 1.0")
50
+
51
+
52
+ # -----------------------------
53
+ # Model loading
54
+ # -----------------------------
55
+
56
+ def load_model(args) -> VoxCPM:
57
+ print("Loading VoxCPM model...", file=sys.stderr)
58
+
59
+ zipenhancer_path = getattr(args, "zipenhancer_path", None) or os.environ.get(
60
+ "ZIPENHANCER_MODEL_PATH", None
61
+ )
62
+
63
+ # Build LoRA config if provided
64
+ lora_config = None
65
+ lora_weights_path = getattr(args, "lora_path", None)
66
+ if lora_weights_path:
67
+ from voxcpm.model.voxcpm import LoRAConfig
68
+
69
+ lora_config = LoRAConfig(
70
+ enable_lm=not args.lora_disable_lm,
71
+ enable_dit=not args.lora_disable_dit,
72
+ enable_proj=args.lora_enable_proj,
73
+ r=args.lora_r,
74
+ alpha=args.lora_alpha,
75
+ dropout=args.lora_dropout,
76
+ )
77
+
78
+ print(
79
+ f"LoRA config: r={lora_config.r}, alpha={lora_config.alpha}, "
80
+ f"lm={lora_config.enable_lm}, dit={lora_config.enable_dit}, proj={lora_config.enable_proj}",
81
+ file=sys.stderr,
82
+ )
83
+
84
+ # Load local model if specified
85
+ if args.model_path:
86
+ try:
87
+ model = VoxCPM(
88
+ voxcpm_model_path=args.model_path,
89
+ zipenhancer_model_path=zipenhancer_path,
90
+ enable_denoiser=not args.no_denoiser,
91
+ lora_config=lora_config,
92
+ lora_weights_path=lora_weights_path,
93
+ )
94
+ print("Model loaded (local).", file=sys.stderr)
95
+ return model
96
+ except Exception as e:
97
+ print(f"Failed to load model (local): {e}", file=sys.stderr)
98
+ sys.exit(1)
99
+
100
+ # Load from Hugging Face Hub
101
+ try:
102
+ model = VoxCPM.from_pretrained(
103
+ hf_model_id=args.hf_model_id,
104
+ load_denoiser=not args.no_denoiser,
105
+ zipenhancer_model_id=zipenhancer_path,
106
+ cache_dir=args.cache_dir,
107
+ local_files_only=args.local_files_only,
108
+ lora_config=lora_config,
109
+ lora_weights_path=lora_weights_path,
110
+ )
111
+ print("Model loaded (from_pretrained).", file=sys.stderr)
112
+ return model
113
+ except Exception as e:
114
+ print(f"Failed to load model (from_pretrained): {e}", file=sys.stderr)
115
+ sys.exit(1)
116
+
117
+
118
+ # -----------------------------
119
+ # Commands
120
+ # -----------------------------
121
+
122
+ def cmd_clone(args):
123
+ if not args.text:
124
+ sys.exit("Error: Please provide --text for synthesis")
125
+
126
+ if not args.prompt_audio or not args.prompt_text:
127
+ sys.exit("Error: Voice cloning requires both --prompt-audio and --prompt-text")
128
+
129
+ prompt_audio_path = validate_file_exists(args.prompt_audio, "reference audio file")
130
+ output_path = validate_output_path(args.output)
131
+
132
+ model = load_model(args)
133
+
134
+ audio_array = model.generate(
135
+ text=args.text,
136
+ prompt_wav_path=str(prompt_audio_path),
137
+ prompt_text=args.prompt_text,
138
+ cfg_value=args.cfg_value,
139
+ inference_timesteps=args.inference_timesteps,
140
+ normalize=args.normalize,
141
+ denoise=args.denoise,
142
+ )
143
+
144
+ sf.write(str(output_path), audio_array, model.tts_model.sample_rate)
145
+
146
+ duration = len(audio_array) / model.tts_model.sample_rate
147
+ print(f"Saved audio to: {output_path} ({duration:.2f}s)", file=sys.stderr)
148
+
149
+
150
+ def cmd_synthesize(args):
151
+ if not args.text:
152
+ sys.exit("Error: Please provide --text for synthesis")
153
+
154
+ output_path = validate_output_path(args.output)
155
+ model = load_model(args)
156
+
157
+ audio_array = model.generate(
158
+ text=args.text,
159
+ prompt_wav_path=None,
160
+ prompt_text=None,
161
+ cfg_value=args.cfg_value,
162
+ inference_timesteps=args.inference_timesteps,
163
+ normalize=args.normalize,
164
+ denoise=False,
165
+ )
166
+
167
+ sf.write(str(output_path), audio_array, model.tts_model.sample_rate)
168
+
169
+ duration = len(audio_array) / model.tts_model.sample_rate
170
+ print(f"Saved audio to: {output_path} ({duration:.2f}s)", file=sys.stderr)
171
+
172
+
173
+ def cmd_batch(args):
174
+ input_file = validate_file_exists(args.input, "input file")
175
+ output_dir = Path(args.output_dir)
176
+ output_dir.mkdir(parents=True, exist_ok=True)
177
+
178
+ with open(input_file, "r", encoding="utf-8") as f:
179
+ texts = [line.strip() for line in f if line.strip()]
180
+
181
+ if not texts:
182
+ sys.exit("Error: Input file is empty")
183
+
184
+ model = load_model(args)
185
+
186
+ prompt_audio_path = None
187
+ if args.prompt_audio:
188
+ prompt_audio_path = str(validate_file_exists(args.prompt_audio, "reference audio file"))
189
+
190
+ success_count = 0
191
+
192
+ for i, text in enumerate(texts, 1):
193
+ try:
194
+ audio_array = model.generate(
195
+ text=text,
196
+ prompt_wav_path=prompt_audio_path,
197
+ prompt_text=args.prompt_text,
198
+ cfg_value=args.cfg_value,
199
+ inference_timesteps=args.inference_timesteps,
200
+ normalize=args.normalize,
201
+ denoise=args.denoise and prompt_audio_path is not None,
202
+ )
203
+
204
+ output_file = output_dir / f"output_{i:03d}.wav"
205
+ sf.write(str(output_file), audio_array, model.tts_model.sample_rate)
206
+
207
+ duration = len(audio_array) / model.tts_model.sample_rate
208
+ print(f"Saved: {output_file} ({duration:.2f}s)", file=sys.stderr)
209
+ success_count += 1
210
+
211
+ except Exception as e:
212
+ print(f"Failed on line {i}: {e}", file=sys.stderr)
213
+
214
+ print(f"\nBatch finished: {success_count}/{len(texts)} succeeded", file=sys.stderr)
215
+
216
+
217
+ # -----------------------------
218
+ # Parser
219
+ # -----------------------------
220
+
221
+ def _build_unified_parser():
222
+ parser = argparse.ArgumentParser(
223
+ description="VoxCPM CLI - voice cloning, direct TTS, and batch processing",
224
+ formatter_class=argparse.RawDescriptionHelpFormatter,
225
+ epilog="""
226
+ Examples:
227
+ voxcpm --text "Hello world" --output out.wav
228
+ voxcpm --text "Hello" --prompt-audio ref.wav --prompt-text "hi" --output out.wav --denoise
229
+ voxcpm --input texts.txt --output-dir ./outs
230
+ """,
231
+ )
232
+
233
+ # Mode selection
234
+ parser.add_argument("--input", "-i", help="Input text file (batch mode only)")
235
+ parser.add_argument("--output-dir", "-od", help="Output directory (batch mode only)")
236
+ parser.add_argument("--text", "-t", help="Text to synthesize (single or clone mode)")
237
+ parser.add_argument("--output", "-o", help="Output audio file path (single or clone mode)")
238
+
239
+ # Prompt
240
+ parser.add_argument("--prompt-audio", "-pa", help="Reference audio file path (clone mode)")
241
+ parser.add_argument("--prompt-text", "-pt", help="Reference text corresponding to the audio")
242
+ parser.add_argument("--denoise", action="store_true", help="Enable prompt speech enhancement")
243
+
244
+ # Generation parameters
245
+ parser.add_argument("--cfg-value", type=float, default=2.0,
246
+ help="CFG guidance scale (float, recommended 0.5–5.0, default: 2.0)")
247
+ parser.add_argument("--inference-timesteps", type=int, default=10,
248
+ help="Inference steps (int, 1–100, default: 10)")
249
+ parser.add_argument("--normalize", action="store_true", help="Enable text normalization")
250
+
251
+ # Model loading
252
+ parser.add_argument("--model-path", type=str, help="Local VoxCPM model path")
253
+ parser.add_argument("--hf-model-id", type=str, default="openbmb/VoxCPM1.5",
254
+ help="Hugging Face repo id (default: openbmb/VoxCPM1.5)")
255
+ parser.add_argument("--cache-dir", type=str, help="Cache directory for Hub downloads")
256
+ parser.add_argument("--local-files-only", action="store_true", help="Disable network access")
257
+ parser.add_argument("--no-denoiser", action="store_true", help="Disable denoiser model loading")
258
+ parser.add_argument("--zipenhancer-path", type=str,
259
+ help="ZipEnhancer model id or local path (or env ZIPENHANCER_MODEL_PATH)")
260
+
261
+ # LoRA
262
+ parser.add_argument("--lora-path", type=str, help="Path to LoRA weights")
263
+ parser.add_argument("--lora-r", type=int, default=32, help="LoRA rank (positive int, default: 32)")
264
+ parser.add_argument("--lora-alpha", type=int, default=16, help="LoRA alpha (positive int, default: 16)")
265
+ parser.add_argument("--lora-dropout", type=float, default=0.0,
266
+ help="LoRA dropout rate (0.0–1.0, default: 0.0)")
267
+ parser.add_argument("--lora-disable-lm", action="store_true", help="Disable LoRA on LM layers")
268
+ parser.add_argument("--lora-disable-dit", action="store_true", help="Disable LoRA on DiT layers")
269
+ parser.add_argument("--lora-enable-proj", action="store_true", help="Enable LoRA on projection layers")
270
+
271
+ return parser
272
+
273
+
274
+ # -----------------------------
275
+ # Entrypoint
276
+ # -----------------------------
277
+
278
+ def main():
279
+ parser = _build_unified_parser()
280
+ args = parser.parse_args()
281
+
282
+ # Validate ranges
283
+ validate_ranges(args, parser)
284
+
285
+ # Mode conflict checks
286
+ if args.input and args.text:
287
+ parser.error("Use either batch mode (--input) or single mode (--text), not both.")
288
+
289
+ # Batch mode
290
+ if args.input:
291
+ if not args.output_dir:
292
+ parser.error("Batch mode requires --output-dir")
293
+ return cmd_batch(args)
294
+
295
+ # Single mode
296
+ if not args.text or not args.output:
297
+ parser.error("Single-sample mode requires --text and --output")
298
+
299
+ # Clone mode
300
+ if args.prompt_audio or args.prompt_text:
301
+ return cmd_clone(args)
302
+
303
+ # Direct synthesis
304
+ return cmd_synthesize(args)
305
+
306
+
307
+ if __name__ == "__main__":
308
+ main()
convert/src/voxcpm/core.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import re
4
+ import tempfile
5
+ import numpy as np
6
+ from typing import Generator, Optional
7
+ from huggingface_hub import snapshot_download
8
+ from .model.voxcpm import VoxCPMModel, LoRAConfig
9
+
10
+ class VoxCPM:
11
+ def __init__(self,
12
+ voxcpm_model_path : str,
13
+ zipenhancer_model_path : str = "iic/speech_zipenhancer_ans_multiloss_16k_base",
14
+ enable_denoiser : bool = True,
15
+ optimize: bool = True,
16
+ lora_config: Optional[LoRAConfig] = None,
17
+ lora_weights_path: Optional[str] = None,
18
+ ):
19
+ """Initialize VoxCPM TTS pipeline.
20
+
21
+ Args:
22
+ voxcpm_model_path: Local filesystem path to the VoxCPM model assets
23
+ (weights, configs, etc.). Typically the directory returned by
24
+ a prior download step.
25
+ zipenhancer_model_path: ModelScope acoustic noise suppression model
26
+ id or local path. If None, denoiser will not be initialized.
27
+ enable_denoiser: Whether to initialize the denoiser pipeline.
28
+ optimize: Whether to optimize the model with torch.compile. True by default, but can be disabled for debugging.
29
+ lora_config: LoRA configuration for fine-tuning. If lora_weights_path is
30
+ provided without lora_config, a default config will be created.
31
+ lora_weights_path: Path to pre-trained LoRA weights (.pth file or directory
32
+ containing lora_weights.ckpt). If provided, LoRA weights will be loaded.
33
+ """
34
+ print(f"voxcpm_model_path: {voxcpm_model_path}, zipenhancer_model_path: {zipenhancer_model_path}, enable_denoiser: {enable_denoiser}", file=sys.stderr)
35
+
36
+ # If lora_weights_path is provided but no lora_config, create a default one
37
+ if lora_weights_path is not None and lora_config is None:
38
+ lora_config = LoRAConfig(
39
+ enable_lm=True,
40
+ enable_dit=True,
41
+ enable_proj=False,
42
+ )
43
+ print(f"Auto-created default LoRAConfig for loading weights from: {lora_weights_path}", file=sys.stderr)
44
+
45
+ self.tts_model = VoxCPMModel.from_local(voxcpm_model_path, optimize=optimize, lora_config=lora_config)
46
+
47
+ # Load LoRA weights if path is provided
48
+ if lora_weights_path is not None:
49
+ print(f"Loading LoRA weights from: {lora_weights_path}", file=sys.stderr)
50
+ loaded_keys, skipped_keys = self.tts_model.load_lora_weights(lora_weights_path)
51
+ print(f"Loaded {len(loaded_keys)} LoRA parameters, skipped {len(skipped_keys)}", file=sys.stderr)
52
+
53
+ self.text_normalizer = None
54
+ if enable_denoiser and zipenhancer_model_path is not None:
55
+ from .zipenhancer import ZipEnhancer
56
+ self.denoiser = ZipEnhancer(zipenhancer_model_path)
57
+ else:
58
+ self.denoiser = None
59
+ if optimize:
60
+ print("Warm up VoxCPMModel...", file=sys.stderr)
61
+ self.tts_model.generate(
62
+ target_text="Hello, this is the first test sentence.",
63
+ max_len=10,
64
+ )
65
+
66
+ @classmethod
67
+ def from_pretrained(cls,
68
+ hf_model_id: str = "openbmb/VoxCPM1.5",
69
+ load_denoiser: bool = True,
70
+ zipenhancer_model_id: str = "iic/speech_zipenhancer_ans_multiloss_16k_base",
71
+ cache_dir: str = None,
72
+ local_files_only: bool = False,
73
+ optimize: bool = True,
74
+ lora_config: Optional[LoRAConfig] = None,
75
+ lora_weights_path: Optional[str] = None,
76
+ **kwargs,
77
+ ):
78
+ """Instantiate ``VoxCPM`` from a Hugging Face Hub snapshot.
79
+
80
+ Args:
81
+ hf_model_id: Explicit Hugging Face repository id (e.g. "org/repo") or local path.
82
+ load_denoiser: Whether to initialize the denoiser pipeline.
83
+ optimize: Whether to optimize the model with torch.compile. True by default, but can be disabled for debugging.
84
+ zipenhancer_model_id: Denoiser model id or path for ModelScope
85
+ acoustic noise suppression.
86
+ cache_dir: Custom cache directory for the snapshot.
87
+ local_files_only: If True, only use local files and do not attempt
88
+ to download.
89
+ lora_config: LoRA configuration for fine-tuning. If lora_weights_path is
90
+ provided without lora_config, a default config will be created with
91
+ enable_lm=True and enable_dit=True.
92
+ lora_weights_path: Path to pre-trained LoRA weights (.pth file or directory
93
+ containing lora_weights.ckpt). If provided, LoRA weights will be loaded
94
+ after model initialization.
95
+ Kwargs:
96
+ Additional keyword arguments passed to the ``VoxCPM`` constructor.
97
+
98
+ Returns:
99
+ VoxCPM: Initialized instance whose ``voxcpm_model_path`` points to
100
+ the downloaded snapshot directory.
101
+
102
+ Raises:
103
+ ValueError: If neither a valid ``hf_model_id`` nor a resolvable
104
+ ``hf_model_id`` is provided.
105
+ """
106
+ repo_id = hf_model_id
107
+ if not repo_id:
108
+ raise ValueError("You must provide hf_model_id")
109
+
110
+ # Load from local path if provided
111
+ if os.path.isdir(repo_id):
112
+ local_path = repo_id
113
+ else:
114
+ # Otherwise, try from_pretrained (Hub); exit on failure
115
+ local_path = snapshot_download(
116
+ repo_id=repo_id,
117
+ cache_dir=cache_dir,
118
+ local_files_only=local_files_only,
119
+ )
120
+
121
+ return cls(
122
+ voxcpm_model_path=local_path,
123
+ zipenhancer_model_path=zipenhancer_model_id if load_denoiser else None,
124
+ enable_denoiser=load_denoiser,
125
+ optimize=optimize,
126
+ lora_config=lora_config,
127
+ lora_weights_path=lora_weights_path,
128
+ **kwargs,
129
+ )
130
+
131
+ def generate(self, *args, **kwargs) -> np.ndarray:
132
+ return next(self._generate(*args, streaming=False, **kwargs))
133
+
134
+ def generate_streaming(self, *args, **kwargs) -> Generator[np.ndarray, None, None]:
135
+ return self._generate(*args, streaming=True, **kwargs)
136
+
137
+ def _generate(self,
138
+ text : str,
139
+ prompt_wav_path : str = None,
140
+ prompt_text : str = None,
141
+ cfg_value : float = 2.0,
142
+ inference_timesteps : int = 10,
143
+ min_len : int = 2,
144
+ max_len : int = 4096,
145
+ normalize : bool = False,
146
+ denoise : bool = False,
147
+ retry_badcase : bool = True,
148
+ retry_badcase_max_times : int = 3,
149
+ retry_badcase_ratio_threshold : float = 6.0,
150
+ streaming: bool = False,
151
+ ) -> Generator[np.ndarray, None, None]:
152
+ """Synthesize speech for the given text and return a single waveform.
153
+
154
+ This method optionally builds and reuses a prompt cache. If an external
155
+ prompt (``prompt_wav_path`` + ``prompt_text``) is provided, it will be
156
+ used for all sub-sentences. Otherwise, the prompt cache is built from
157
+ the first generated result and reused for the remaining text chunks.
158
+
159
+ Args:
160
+ text: Input text. Can include newlines; each non-empty line is
161
+ treated as a sub-sentence.
162
+ prompt_wav_path: Path to a reference audio file for prompting.
163
+ prompt_text: Text content corresponding to the prompt audio.
164
+ cfg_value: Guidance scale for the generation model.
165
+ inference_timesteps: Number of inference steps.
166
+ max_len: Maximum token length during generation.
167
+ normalize: Whether to run text normalization before generation.
168
+ denoise: Whether to denoise the prompt audio if a denoiser is
169
+ available.
170
+ retry_badcase: Whether to retry badcase.
171
+ retry_badcase_max_times: Maximum number of times to retry badcase.
172
+ retry_badcase_ratio_threshold: Threshold for audio-to-text ratio.
173
+ streaming: Whether to return a generator of audio chunks.
174
+ Returns:
175
+ Generator of numpy.ndarray: 1D waveform array (float32) on CPU.
176
+ Yields audio chunks for each generations step if ``streaming=True``,
177
+ otherwise yields a single array containing the final audio.
178
+ """
179
+ if not text.strip() or not isinstance(text, str):
180
+ raise ValueError("target text must be a non-empty string")
181
+
182
+ if prompt_wav_path is not None:
183
+ if not os.path.exists(prompt_wav_path):
184
+ raise FileNotFoundError(f"prompt_wav_path does not exist: {prompt_wav_path}")
185
+
186
+ if (prompt_wav_path is None) != (prompt_text is None):
187
+ raise ValueError("prompt_wav_path and prompt_text must both be provided or both be None")
188
+
189
+ text = text.replace("\n", " ")
190
+ text = re.sub(r'\s+', ' ', text)
191
+ temp_prompt_wav_path = None
192
+
193
+ try:
194
+ if prompt_wav_path is not None and prompt_text is not None:
195
+ if denoise and self.denoiser is not None:
196
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file:
197
+ temp_prompt_wav_path = tmp_file.name
198
+ self.denoiser.enhance(prompt_wav_path, output_path=temp_prompt_wav_path)
199
+ prompt_wav_path = temp_prompt_wav_path
200
+ fixed_prompt_cache = self.tts_model.build_prompt_cache(
201
+ prompt_wav_path=prompt_wav_path,
202
+ prompt_text=prompt_text
203
+ )
204
+ else:
205
+ fixed_prompt_cache = None # will be built from the first inference
206
+
207
+ if normalize:
208
+ if self.text_normalizer is None:
209
+ from .utils.text_normalize import TextNormalizer
210
+ self.text_normalizer = TextNormalizer()
211
+ text = self.text_normalizer.normalize(text)
212
+
213
+ generate_result = self.tts_model._generate_with_prompt_cache(
214
+ target_text=text,
215
+ prompt_cache=fixed_prompt_cache,
216
+ min_len=min_len,
217
+ max_len=max_len,
218
+ inference_timesteps=inference_timesteps,
219
+ cfg_value=cfg_value,
220
+ retry_badcase=retry_badcase,
221
+ retry_badcase_max_times=retry_badcase_max_times,
222
+ retry_badcase_ratio_threshold=retry_badcase_ratio_threshold,
223
+ streaming=streaming,
224
+ )
225
+
226
+ for wav, _, _ in generate_result:
227
+ yield wav.squeeze(0).cpu().numpy()
228
+
229
+ finally:
230
+ if temp_prompt_wav_path and os.path.exists(temp_prompt_wav_path):
231
+ try:
232
+ os.unlink(temp_prompt_wav_path)
233
+ except OSError:
234
+ pass
235
+
236
+ # ------------------------------------------------------------------ #
237
+ # LoRA Interface (delegated to VoxCPMModel)
238
+ # ------------------------------------------------------------------ #
239
+ def load_lora(self, lora_weights_path: str) -> tuple:
240
+ """Load LoRA weights from a checkpoint file.
241
+
242
+ Args:
243
+ lora_weights_path: Path to LoRA weights (.pth file or directory
244
+ containing lora_weights.ckpt).
245
+
246
+ Returns:
247
+ tuple: (loaded_keys, skipped_keys) - lists of loaded and skipped parameter names.
248
+
249
+ Raises:
250
+ RuntimeError: If model was not initialized with LoRA config.
251
+ """
252
+ if self.tts_model.lora_config is None:
253
+ raise RuntimeError(
254
+ "Cannot load LoRA weights: model was not initialized with LoRA config. "
255
+ "Please reinitialize with lora_config or lora_weights_path parameter."
256
+ )
257
+ return self.tts_model.load_lora_weights(lora_weights_path)
258
+
259
+ def unload_lora(self):
260
+ """Unload LoRA by resetting all LoRA weights to initial state (effectively disabling LoRA)."""
261
+ self.tts_model.reset_lora_weights()
262
+
263
+ def set_lora_enabled(self, enabled: bool):
264
+ """Enable or disable LoRA layers without unloading weights.
265
+
266
+ Args:
267
+ enabled: If True, LoRA layers are active; if False, only base model is used.
268
+ """
269
+ self.tts_model.set_lora_enabled(enabled)
270
+
271
+ def get_lora_state_dict(self) -> dict:
272
+ """Get current LoRA parameters state dict.
273
+
274
+ Returns:
275
+ dict: State dict containing all LoRA parameters (lora_A, lora_B).
276
+ """
277
+ return self.tts_model.get_lora_state_dict()
278
+
279
+ @property
280
+ def lora_enabled(self) -> bool:
281
+ """Check if LoRA is currently configured."""
282
+ return self.tts_model.lora_config is not None
convert/src/voxcpm/model/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .voxcpm import VoxCPMModel
2
+
3
+ __all__ = ["VoxCPMModel"]
convert/src/voxcpm/model/utils.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import torch
3
+ from transformers import PreTrainedTokenizer
4
+
5
+
6
+ def mask_multichar_chinese_tokens(tokenizer: PreTrainedTokenizer):
7
+ """Create a tokenizer wrapper that converts multi-character Chinese tokens to single characters.
8
+
9
+ This function creates a wrapper around the provided tokenizer that automatically
10
+ splits multi-character Chinese tokens into individual characters. This is useful
11
+ for ensuring consistent tokenization of Chinese text.
12
+
13
+ Args:
14
+ tokenizer: The base tokenizer to wrap
15
+
16
+ Returns:
17
+ A CharTokenizerWrapper instance that handles multi-character Chinese tokens
18
+
19
+ Example:
20
+ >>> from transformers import LlamaTokenizerFast
21
+ >>> tokenizer = LlamaTokenizerFast.from_pretrained("path/to/tokenizer")
22
+ >>> wrapped_tokenizer = mask_multichar_chinese_tokens(tokenizer)
23
+ >>> tokens = wrapped_tokenizer("你好世界")
24
+ """
25
+ # Pre-compute multi-character tokens (length >= 2, pure Chinese characters)
26
+ multichar_tokens = {
27
+ token for token in tokenizer.vocab.keys()
28
+ if len(token) >= 2 and all("\u4e00" <= c <= "\u9fff" for c in token)
29
+ }
30
+
31
+ class CharTokenizerWrapper:
32
+ """Wrapper class for tokenizers that handles multi-character Chinese tokens.
33
+
34
+ This wrapper automatically splits multi-character Chinese tokens into
35
+ individual characters while preserving the original tokenizer's interface.
36
+ """
37
+
38
+ def __init__(self, base_tokenizer: PreTrainedTokenizer) -> None:
39
+ """Initialize the wrapper with a base tokenizer.
40
+
41
+ Args:
42
+ base_tokenizer: The tokenizer to wrap
43
+ """
44
+ self.tokenizer = base_tokenizer
45
+ self.multichar_tokens = multichar_tokens
46
+
47
+ def tokenize(self, text: str, **kwargs) -> List[str]:
48
+ """Tokenize text and split multi-character Chinese tokens into single characters.
49
+
50
+ Args:
51
+ text: Input text to tokenize
52
+ **kwargs: Additional arguments passed to the base tokenizer
53
+
54
+ Returns:
55
+ List of processed tokens with multi-character Chinese tokens split
56
+
57
+ Example:
58
+ >>> wrapper = CharTokenizerWrapper(tokenizer)
59
+ >>> tokens = wrapper.tokenize("你好世界")
60
+ >>> # Returns ["你", "好", "世", "界"] instead of ["你好", "世界"]
61
+ """
62
+ if not isinstance(text, str):
63
+ raise TypeError(f"Expected string input, got {type(text)}")
64
+
65
+ tokens = self.tokenizer.tokenize(text, **kwargs)
66
+ processed = []
67
+
68
+ for token in tokens:
69
+ # Remove possible subword prefix
70
+ clean_token = token.replace("▁", "")
71
+
72
+ if clean_token in self.multichar_tokens:
73
+ # Split multi-character token into single characters
74
+ chars = list(clean_token)
75
+ processed.extend(chars)
76
+ else:
77
+ processed.append(token)
78
+
79
+ return processed
80
+
81
+ def __call__(self, text: str, **kwargs) -> List[int]:
82
+ """Call the tokenizer and return token IDs.
83
+
84
+ This method provides the same interface as the original tokenizer
85
+ but with multi-character Chinese token handling.
86
+
87
+ Args:
88
+ text: Input text to tokenize
89
+ **kwargs: Additional arguments passed to the base tokenizer
90
+
91
+ Returns:
92
+ List of token IDs
93
+
94
+ Raises:
95
+ TypeError: If input is not a string
96
+ ValueError: If tokenization fails
97
+ """
98
+ try:
99
+ tokens = self.tokenize(text, **kwargs)
100
+ result = self.tokenizer.convert_tokens_to_ids(tokens)
101
+ return result
102
+ except Exception as e:
103
+ raise ValueError(f"Tokenization failed: {str(e)}") from e
104
+
105
+ return CharTokenizerWrapper(tokenizer)
106
+
107
+
108
+ def get_dtype(dtype: str):
109
+ if dtype == "bfloat16":
110
+ return torch.bfloat16
111
+ elif dtype == "bf16":
112
+ return torch.bfloat16
113
+ elif dtype == "float16":
114
+ return torch.float16
115
+ elif dtype == "fp16":
116
+ return torch.float16
117
+ elif dtype == "float32":
118
+ return torch.float32
119
+ elif dtype == "fp32":
120
+ return torch.float32
121
+ else:
122
+ raise ValueError(f"Unsupported dtype: {dtype}")
convert/src/voxcpm/model/voxcpm.py ADDED
@@ -0,0 +1,972 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ VoxCPM: A Tokenizer-free speech generation model
3
+
4
+ This module contains the main VoxCPM model implementation, including configuration classes
5
+ and the core VoxCPMModel for text-to-speech generation.
6
+
7
+ Copyright 2025 OpenBMB
8
+ Licensed under the Apache License, Version 2.0 (the "License");
9
+ you may not use this file except in compliance with the License.
10
+ You may obtain a copy of the License at
11
+
12
+ http://www.apache.org/licenses/LICENSE-2.0
13
+
14
+ Unless required by applicable law or agreed to in writing, software
15
+ distributed under the License is distributed on an "AS IS" BASIS,
16
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ See the License for the specific language governing permissions and
18
+ limitations under the License.
19
+ """
20
+
21
+ import os
22
+ import sys
23
+ from typing import Tuple, Union, Generator, List, Optional
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ import torchaudio
29
+ import warnings
30
+ from einops import rearrange
31
+ from pydantic import BaseModel
32
+
33
+ try:
34
+ from safetensors.torch import load_file
35
+ SAFETENSORS_AVAILABLE = True
36
+ except ImportError:
37
+ SAFETENSORS_AVAILABLE = False
38
+ from tqdm import tqdm
39
+ from transformers import LlamaTokenizerFast
40
+
41
+ from ..modules.audiovae import AudioVAE, AudioVAEConfig
42
+ from ..modules.layers import ScalarQuantizationLayer
43
+ from ..modules.layers.lora import apply_lora_to_named_linear_modules
44
+ from ..modules.locdit import CfmConfig, UnifiedCFM, VoxCPMLocDiT
45
+ from ..modules.locenc import VoxCPMLocEnc
46
+ from ..modules.minicpm4 import MiniCPM4Config, MiniCPMModel
47
+ from .utils import get_dtype, mask_multichar_chinese_tokens
48
+
49
+
50
+ class VoxCPMEncoderConfig(BaseModel):
51
+ hidden_dim: int = 1024
52
+ ffn_dim: int = 4096
53
+ num_heads: int = 16
54
+ num_layers: int = 4
55
+ kv_channels: int = None
56
+
57
+
58
+ class VoxCPMDitConfig(BaseModel):
59
+ hidden_dim: int = 1024
60
+ ffn_dim: int = 4096
61
+ num_heads: int = 16
62
+ num_layers: int = 4
63
+ kv_channels: int = None
64
+
65
+ cfm_config: CfmConfig
66
+
67
+
68
+ class VoxCPMConfig(BaseModel):
69
+ lm_config: MiniCPM4Config
70
+ patch_size: int = 2
71
+ feat_dim: int = 64
72
+ residual_lm_num_layers: int = 6
73
+ scalar_quantization_latent_dim: int = 256
74
+ scalar_quantization_scale: int = 9
75
+
76
+ encoder_config: VoxCPMEncoderConfig
77
+ dit_config: VoxCPMDitConfig
78
+ audio_vae_config: Optional[AudioVAEConfig] = None
79
+
80
+ max_length: int = 4096
81
+ device: str = "cuda"
82
+ dtype: str = "bfloat16"
83
+ dit_mean_mode: bool = False
84
+
85
+
86
+ class LoRAConfig(BaseModel):
87
+ enable_lm: bool = False # Apply LoRA to base_lm + residual_lm
88
+ enable_dit: bool = False # Apply LoRA to VoxCPMLocDiT
89
+ enable_proj: bool = False # Apply LoRA to projection Linear layers
90
+
91
+ r: int = 8
92
+ alpha: int = 16
93
+ dropout: float = 0.0
94
+
95
+ # Target linear layer names for LM & DiT (matched by attribute name)
96
+ target_modules_lm: list[str] = ["q_proj", "v_proj", "k_proj", "o_proj"]
97
+ target_modules_dit: list[str] = ["q_proj", "v_proj", "k_proj", "o_proj"]
98
+ # Projection layer attribute names to find on VoxCPMModel
99
+ target_proj_modules: list[str] = ["enc_to_lm_proj", "lm_to_dit_proj", "res_to_dit_proj"]
100
+
101
+
102
+ VoxCPMConfig.model_rebuild()
103
+
104
+
105
+ class VoxCPMModel(nn.Module):
106
+ def __init__(
107
+ self,
108
+ config: VoxCPMConfig,
109
+ tokenizer: LlamaTokenizerFast,
110
+ audio_vae: AudioVAE,
111
+ lora_config: LoRAConfig = None,
112
+ ):
113
+ super().__init__()
114
+ self.config = config
115
+ self.lora_config = lora_config
116
+ self.feat_dim = config.feat_dim
117
+ self.patch_size = config.patch_size
118
+ self.device = config.device
119
+ if not torch.cuda.is_available():
120
+ if torch.backends.mps.is_available():
121
+ self.device = "mps"
122
+ else:
123
+ self.device = "cpu"
124
+ print(f"Running on device: {self.device}, dtype: {self.config.dtype}", file=sys.stderr)
125
+
126
+ # Text-Semantic LM
127
+ self.base_lm = MiniCPMModel(config.lm_config)
128
+ self.base_lm.setup_cache(1, config.max_length, self.device, get_dtype(self.config.dtype))
129
+
130
+ self.text_tokenizer = mask_multichar_chinese_tokens(tokenizer)
131
+ self.audio_start_token = 101
132
+ self.audio_end_token = 102
133
+
134
+ # Residual Acoustic LM
135
+ residual_lm_config = config.lm_config.model_copy(deep=True)
136
+ residual_lm_config.num_hidden_layers = config.residual_lm_num_layers
137
+ residual_lm_config.vocab_size = 0
138
+ self.residual_lm = MiniCPMModel(residual_lm_config)
139
+ self.residual_lm.setup_cache(1, config.max_length, self.device, get_dtype(self.config.dtype))
140
+
141
+ # Local Encoder
142
+ encoder_config = config.lm_config.model_copy(deep=True)
143
+ encoder_config.hidden_size = config.encoder_config.hidden_dim
144
+ encoder_config.intermediate_size = config.encoder_config.ffn_dim
145
+ encoder_config.num_attention_heads = config.encoder_config.num_heads
146
+ encoder_config.num_hidden_layers = config.encoder_config.num_layers
147
+ encoder_config.kv_channels = config.encoder_config.kv_channels
148
+ encoder_config.vocab_size = 0
149
+ self.feat_encoder = VoxCPMLocEnc(encoder_config, input_dim=config.feat_dim)
150
+
151
+ # Local DiT
152
+ decoder_config = config.lm_config.model_copy(deep=True)
153
+ decoder_config.hidden_size = config.dit_config.hidden_dim
154
+ decoder_config.intermediate_size = config.dit_config.ffn_dim
155
+ decoder_config.num_attention_heads = config.dit_config.num_heads
156
+ decoder_config.num_hidden_layers = config.dit_config.num_layers
157
+ decoder_config.kv_channels = config.dit_config.kv_channels
158
+ decoder_config.vocab_size = 0
159
+ self.feat_decoder = UnifiedCFM(
160
+ in_channels=config.feat_dim,
161
+ cfm_params=config.dit_config.cfm_config,
162
+ estimator=VoxCPMLocDiT(decoder_config, in_channels=config.feat_dim),
163
+ mean_mode=config.dit_mean_mode,
164
+ )
165
+
166
+ # Projection layers
167
+ self.fsq_layer = ScalarQuantizationLayer(
168
+ config.lm_config.hidden_size,
169
+ config.lm_config.hidden_size,
170
+ config.scalar_quantization_latent_dim,
171
+ config.scalar_quantization_scale
172
+ )
173
+ self.enc_to_lm_proj = nn.Linear(config.encoder_config.hidden_dim, config.lm_config.hidden_size)
174
+ self.lm_to_dit_proj = nn.Linear(config.lm_config.hidden_size, config.dit_config.hidden_dim)
175
+ self.res_to_dit_proj = nn.Linear(config.lm_config.hidden_size, config.dit_config.hidden_dim)
176
+
177
+ # Stop Predictor
178
+ self.stop_proj = nn.Linear(config.lm_config.hidden_size, config.lm_config.hidden_size)
179
+ self.stop_actn = nn.SiLU()
180
+ self.stop_head = nn.Linear(config.lm_config.hidden_size, 2, bias=False)
181
+ self.stop_loss = nn.CrossEntropyLoss(reduction="none")
182
+
183
+ # Audio VAE
184
+ self.audio_vae = audio_vae
185
+ self.chunk_size = audio_vae.chunk_size
186
+ self.sample_rate = audio_vae.sample_rate
187
+
188
+ if self.lora_config is not None:
189
+ self._apply_lora()
190
+
191
+ def _apply_lora(self):
192
+ """注入 LoRA 到 LM / DiT / 投影层"""
193
+ cfg = self.lora_config
194
+ lora_kwargs = dict(r=cfg.r, alpha=cfg.alpha, dropout=cfg.dropout)
195
+
196
+ # LM: base_lm + residual_lm
197
+ if cfg.enable_lm:
198
+ for lm in [self.base_lm, self.residual_lm]:
199
+ apply_lora_to_named_linear_modules(
200
+ lm, target_submodule_names=cfg.target_modules_lm, **lora_kwargs
201
+ )
202
+
203
+ # DiT: feat_decoder.estimator
204
+ if cfg.enable_dit:
205
+ apply_lora_to_named_linear_modules(
206
+ self.feat_decoder.estimator, target_submodule_names=cfg.target_modules_dit, **lora_kwargs
207
+ )
208
+
209
+ # 投影层
210
+ if cfg.enable_proj:
211
+ from ..modules.layers.lora import LoRALinear
212
+ for attr_name in cfg.target_proj_modules:
213
+ module = getattr(self, attr_name, None)
214
+ if isinstance(module, nn.Linear):
215
+ setattr(self, attr_name, LoRALinear(base=module, **lora_kwargs))
216
+
217
+ def optimize(self, disable: bool = False):
218
+ if disable:
219
+ return self
220
+ try:
221
+ if self.device != "cuda":
222
+ raise ValueError("VoxCPMModel can only be optimized on CUDA device")
223
+ try:
224
+ import triton
225
+ except ImportError:
226
+ raise ValueError("triton is not installed")
227
+ self.base_lm.forward_step = torch.compile(self.base_lm.forward_step, mode="reduce-overhead", fullgraph=True)
228
+ self.residual_lm.forward_step = torch.compile(self.residual_lm.forward_step, mode="reduce-overhead", fullgraph=True)
229
+ self.feat_encoder = torch.compile(self.feat_encoder, mode="reduce-overhead", fullgraph=True)
230
+ self.feat_decoder.estimator = torch.compile(self.feat_decoder.estimator, mode="reduce-overhead", fullgraph=True)
231
+ except Exception as e:
232
+ print(f"Warning: torch.compile disabled - {e}", file=sys.stderr)
233
+ return self
234
+
235
+ def forward(
236
+ self,
237
+ text_tokens: torch.Tensor,
238
+ text_mask: torch.Tensor,
239
+ audio_feats: torch.Tensor,
240
+ audio_mask: torch.Tensor,
241
+ loss_mask: torch.Tensor,
242
+ position_ids: torch.Tensor,
243
+ labels: torch.Tensor,
244
+ *,
245
+ progress: float = 0.0,
246
+ sample_generate: bool = False,
247
+ ):
248
+ del position_ids # not used yet
249
+
250
+ text_tokens = text_tokens.to(self.device, dtype=torch.long)
251
+ text_mask = text_mask.to(self.device, dtype=self._dtype())
252
+ audio_feats = audio_feats.to(self.device, dtype=self._dtype())
253
+ audio_mask = audio_mask.to(self.device, dtype=self._dtype())
254
+ loss_mask = loss_mask.to(self.device, dtype=self._dtype())
255
+ labels = labels.to(self.device, dtype=torch.long)
256
+
257
+ B, T, P, D = audio_feats.shape
258
+ feat_embed = self.feat_encoder(audio_feats)
259
+ feat_embed = self.enc_to_lm_proj(feat_embed)
260
+
261
+ scale_emb = getattr(self.config.lm_config, "scale_emb", 1.0)
262
+ if not getattr(self.config.lm_config, "use_mup", False):
263
+ scale_emb = 1.0
264
+ text_embed = self.base_lm.embed_tokens(text_tokens) * scale_emb
265
+ combined_embed = text_mask.unsqueeze(-1) * text_embed + audio_mask.unsqueeze(-1) * feat_embed
266
+
267
+ enc_outputs, _ = self.base_lm(inputs_embeds=combined_embed, is_causal=True)
268
+ enc_outputs = enc_outputs.to(self._dtype())
269
+ enc_outputs = self.fsq_layer(enc_outputs) * audio_mask.unsqueeze(-1) + enc_outputs * text_mask.unsqueeze(-1)
270
+ lm_hidden = torch.cat((torch.zeros_like(enc_outputs[:, 0:1, :]), enc_outputs[:, :-1, :]), dim=1)
271
+
272
+ residual_inputs = enc_outputs + audio_mask.unsqueeze(-1) * feat_embed
273
+ residual_outputs, _ = self.residual_lm(inputs_embeds=residual_inputs, is_causal=True)
274
+ residual_outputs = residual_outputs.to(self._dtype())
275
+ residual_hidden = torch.cat(
276
+ (torch.zeros_like(residual_outputs[:, 0:1, :]), residual_outputs[:, :-1, :]),
277
+ dim=1,
278
+ )
279
+
280
+ dit_hidden = self.lm_to_dit_proj(lm_hidden) + self.res_to_dit_proj(residual_hidden)
281
+ dit_hidden = rearrange(dit_hidden, "b t c -> (b t) c")
282
+
283
+ # Keep diffusion inputs in the same dtype as the model (e.g., bfloat16)
284
+ target_dtype = self._dtype()
285
+
286
+ feat_gt = rearrange(audio_feats.to(target_dtype), "b t p d -> (b t) p d")
287
+ feat_cond = torch.cat(
288
+ (torch.zeros_like(audio_feats[:, 0:1, ...]), audio_feats[:, :-1, ...]),
289
+ dim=1,
290
+ )
291
+ feat_cond = rearrange(feat_cond.to(target_dtype), "b t p d -> (b t) p d")
292
+
293
+ loss_seq_mask = loss_mask.unsqueeze(-1).repeat(1, 1, self.patch_size)
294
+ loss_seq_mask = rearrange(loss_seq_mask, "b t p -> (b t) p 1").to(target_dtype)
295
+
296
+ diff_loss = self.feat_decoder.compute_loss(
297
+ feat_gt.transpose(1, 2).contiguous(),
298
+ dit_hidden,
299
+ cond=feat_cond.transpose(1, 2).contiguous(),
300
+ tgt_mask=loss_seq_mask.transpose(1, 2).contiguous(),
301
+ progress=progress,
302
+ )
303
+
304
+ stop_logits = self.stop_head(self.stop_actn(self.stop_proj(lm_hidden)))
305
+ stop_losses = self.stop_loss(stop_logits.transpose(1, 2), labels)
306
+ denom = torch.clamp(loss_mask.sum(), min=1.0)
307
+ stop_loss = (stop_losses * loss_mask).sum() / denom
308
+
309
+ feat_pred = None
310
+ if sample_generate:
311
+ feat_cond_for_sample = feat_cond.transpose(1, 2).contiguous()
312
+ feat_pred_seq = self.feat_decoder(
313
+ mu=dit_hidden,
314
+ patch_size=self.patch_size,
315
+ cond=feat_cond_for_sample,
316
+ n_timesteps=self.config.dit_config.cfm_config.inference_cfg_rate
317
+ if hasattr(self.config.dit_config.cfm_config, "inference_cfg_rate")
318
+ else 10,
319
+ )
320
+ feat_pred = rearrange(feat_pred_seq.transpose(1, 2), "(b t) d p -> b d (t p)", b=B, p=self.patch_size)
321
+
322
+ feat_gt_tensor = rearrange(feat_gt, "(b t) p d -> b d (t p)", b=B, p=self.patch_size)
323
+
324
+ return {
325
+ "loss/diff": diff_loss,
326
+ "loss/stop": stop_loss,
327
+ "feat_gt": feat_gt_tensor,
328
+ "feat_pred": feat_pred,
329
+ }
330
+
331
+ def _dtype(self):
332
+ return get_dtype(self.config.dtype)
333
+
334
+
335
+ def generate(self, *args, **kwargs) -> torch.Tensor:
336
+ return next(self._generate(*args, streaming=False, **kwargs))
337
+
338
+ def generate_streaming(self, *args, **kwargs) -> Generator[torch.Tensor, None, None]:
339
+ return self._generate(*args, streaming=True, **kwargs)
340
+
341
+ @torch.inference_mode()
342
+ def _generate(
343
+ self,
344
+ target_text: str,
345
+ prompt_text: str = "",
346
+ prompt_wav_path: str = "",
347
+ min_len: int = 2,
348
+ max_len: int = 2000,
349
+ inference_timesteps: int = 10,
350
+ cfg_value: float = 2.0,
351
+ retry_badcase: bool = False,
352
+ retry_badcase_max_times: int = 3,
353
+ retry_badcase_ratio_threshold: float = 6.0, # setting acceptable ratio of audio length to text length (for badcase detection)
354
+ streaming: bool = False,
355
+ ) -> Generator[torch.Tensor, None, None]:
356
+ if retry_badcase and streaming:
357
+ warnings.warn("Retry on bad cases is not supported in streaming mode, setting retry_badcase=False.")
358
+ retry_badcase = False
359
+ if len(prompt_wav_path) == 0:
360
+ text = target_text
361
+ text_token = torch.LongTensor(self.text_tokenizer(text))
362
+ text_token = torch.cat(
363
+ [
364
+ text_token,
365
+ torch.tensor(
366
+ [self.audio_start_token],
367
+ dtype=torch.int32,
368
+ device=text_token.device,
369
+ ),
370
+ ],
371
+ dim=-1,
372
+ )
373
+ text_length = text_token.shape[0]
374
+
375
+ audio_feat = torch.zeros(
376
+ (text_length, self.patch_size, self.audio_vae.latent_dim),
377
+ dtype=torch.float32,
378
+ device=text_token.device,
379
+ )
380
+ text_mask = torch.ones(text_length).type(torch.int32).to(text_token.device)
381
+ audio_mask = torch.zeros(text_length).type(torch.int32).to(text_token.device)
382
+
383
+ else:
384
+ text = prompt_text + target_text
385
+ text_token = torch.LongTensor(self.text_tokenizer(text))
386
+ text_token = torch.cat(
387
+ [
388
+ text_token,
389
+ torch.tensor([self.audio_start_token], dtype=torch.int32, device=text_token.device),
390
+ ],
391
+ dim=-1,
392
+ )
393
+ text_length = text_token.shape[0]
394
+
395
+ audio, sr = torchaudio.load(prompt_wav_path)
396
+ if audio.size(0) > 1:
397
+ audio = audio.mean(dim=0, keepdim=True)
398
+
399
+ if sr != self.sample_rate:
400
+ audio = torchaudio.functional.resample(audio, sr, self.sample_rate)
401
+
402
+ patch_len = self.patch_size * self.chunk_size
403
+
404
+ if audio.size(1) % patch_len != 0:
405
+ # 左填充:在音频开头填充,保持有效音频数据在序列末尾
406
+ padding_size = patch_len - audio.size(1) % patch_len
407
+ audio = torch.nn.functional.pad(audio, (padding_size, 0))
408
+
409
+ # (B, D, T)
410
+ audio_feat = self.audio_vae.encode(audio.to(self.device), self.sample_rate).cpu()
411
+ audio_feat = audio_feat.view(
412
+ self.audio_vae.latent_dim,
413
+ -1,
414
+ self.patch_size,
415
+ ).permute(1, 2, 0)
416
+ audio_length = audio_feat.size(0)
417
+ text_pad_token = torch.zeros(audio_length, dtype=torch.int32, device=text_token.device)
418
+ text_token = torch.cat([text_token, text_pad_token])
419
+ audio_pad_feat = torch.zeros(
420
+ (text_length, self.patch_size, self.audio_vae.latent_dim),
421
+ dtype=torch.float32,
422
+ device=text_token.device,
423
+ )
424
+ audio_feat = torch.cat([audio_pad_feat, audio_feat], dim=0)
425
+ text_mask = (
426
+ torch.cat([torch.ones(text_length), torch.zeros(audio_length)]).type(torch.int32).to(text_token.device)
427
+ )
428
+ audio_mask = (
429
+ torch.cat([torch.zeros(text_length), torch.ones(audio_length)]).type(torch.int32).to(text_token.device)
430
+ )
431
+
432
+ text_token = text_token.unsqueeze(0).to(self.device)
433
+ text_mask = text_mask.unsqueeze(0).to(self.device)
434
+ audio_feat = audio_feat.unsqueeze(0).to(self.device).to(get_dtype(self.config.dtype))
435
+ audio_mask = audio_mask.unsqueeze(0).to(self.device)
436
+
437
+ target_text_length = len(self.text_tokenizer(target_text))
438
+
439
+ retry_badcase_times = 0
440
+ while retry_badcase_times < retry_badcase_max_times:
441
+ inference_result = self._inference(
442
+ text_token,
443
+ text_mask,
444
+ audio_feat,
445
+ audio_mask,
446
+ min_len=min_len,
447
+ max_len=min(int(target_text_length * retry_badcase_ratio_threshold + 10), max_len), # avoid too long audio
448
+ inference_timesteps=inference_timesteps,
449
+ cfg_value=cfg_value,
450
+ streaming=streaming,
451
+ )
452
+ if streaming:
453
+ patch_len = self.patch_size * self.chunk_size
454
+ for latent_pred, _ in inference_result:
455
+ decode_audio = self.audio_vae.decode(latent_pred.to(torch.float32))
456
+ decode_audio = decode_audio[..., -patch_len:].squeeze(1).cpu()
457
+ yield decode_audio
458
+ break
459
+ else:
460
+ latent_pred, pred_audio_feat = next(inference_result)
461
+ if retry_badcase:
462
+ if pred_audio_feat.shape[0] >= target_text_length * retry_badcase_ratio_threshold:
463
+ print(f" Badcase detected, audio_text_ratio={pred_audio_feat.shape[0] / target_text_length}, retrying...", file=sys.stderr)
464
+ retry_badcase_times += 1
465
+ continue
466
+ else:
467
+ break
468
+ else:
469
+ break
470
+
471
+ if not streaming:
472
+ decode_audio = self.audio_vae.decode(latent_pred.to(torch.float32)).squeeze(1).cpu()
473
+ yield decode_audio
474
+
475
+ @torch.inference_mode()
476
+ def build_prompt_cache(
477
+ self,
478
+ prompt_text: str,
479
+ prompt_wav_path: str,
480
+ ):
481
+ """
482
+ Build prompt cache for subsequent fast generation.
483
+
484
+ Args:
485
+ prompt_text: prompt text (required)
486
+ prompt_wav_path: prompt audio path (required)
487
+
488
+ Returns:
489
+ prompt_cache: dict with prompt_text (raw text) and audio features.
490
+ Text tokenization will be done during generation for consistency.
491
+ """
492
+ if not prompt_text or not prompt_wav_path:
493
+ raise ValueError("prompt_text and prompt_wav_path are required")
494
+
495
+ # load audio
496
+ audio, sr = torchaudio.load(prompt_wav_path)
497
+ if audio.size(0) > 1:
498
+ audio = audio.mean(dim=0, keepdim=True)
499
+
500
+ if sr != self.sample_rate:
501
+ audio = torchaudio.functional.resample(audio, sr, self.sample_rate)
502
+
503
+ patch_len = self.patch_size * self.chunk_size
504
+
505
+ if audio.size(1) % patch_len != 0:
506
+ # Left padding: pad at the beginning of the audio to keep valid audio data at the end of the sequence
507
+ padding_size = patch_len - audio.size(1) % patch_len
508
+ audio = torch.nn.functional.pad(audio, (padding_size, 0))
509
+
510
+ # extract audio features
511
+ audio_feat = self.audio_vae.encode(audio.to(self.device), self.sample_rate).cpu()
512
+
513
+ audio_feat = audio_feat.view(
514
+ self.audio_vae.latent_dim,
515
+ -1,
516
+ self.patch_size,
517
+ ).permute(1, 2, 0) # (D, T, P)
518
+ # build prompt cache - only save raw text and audio features
519
+ prompt_cache = {
520
+ "prompt_text": prompt_text,
521
+ "audio_feat": audio_feat,
522
+ }
523
+
524
+ return prompt_cache
525
+
526
+
527
+ def merge_prompt_cache(
528
+ self,
529
+ original_cache: dict,
530
+ new_text: str,
531
+ new_audio_feat: torch.Tensor,
532
+ ):
533
+ """
534
+ Merge original prompt cache with newly generated content to stabilize voice.
535
+
536
+ Args:
537
+ original_cache: original prompt cache
538
+ new_text: newly generated text
539
+ new_audio_feat: newly generated audio features
540
+
541
+ Returns:
542
+ merged_cache: merged cache with prompt_text and audio_feat
543
+ """
544
+ if original_cache is None:
545
+ return {
546
+ "prompt_text": new_text,
547
+ "audio_feat": new_audio_feat,
548
+ }
549
+ original_prompt_text = original_cache["prompt_text"]
550
+ original_audio_feat = original_cache["audio_feat"]
551
+ # Merge text by concatenation
552
+ merged_prompt_text = original_prompt_text + new_text
553
+ merged_audio_feat = torch.cat([original_audio_feat, new_audio_feat], dim=0)
554
+
555
+ # build new cache
556
+ merged_cache = {
557
+ "prompt_text": merged_prompt_text,
558
+ "audio_feat": merged_audio_feat,
559
+ }
560
+
561
+ return merged_cache
562
+
563
+
564
+ def generate_with_prompt_cache(self, *args, **kwargs) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
565
+ return next(self._generate_with_prompt_cache(*args, streaming=False, **kwargs))
566
+
567
+
568
+ def generate_with_prompt_cache_streaming(
569
+ self, *args, **kwargs
570
+ ) -> Generator[Tuple[torch.Tensor, torch.Tensor, List[torch.Tensor]], None, None]:
571
+ return self._generate_with_prompt_cache(*args, streaming=True, **kwargs)
572
+
573
+
574
+ @torch.inference_mode()
575
+ def _generate_with_prompt_cache(
576
+ self,
577
+ target_text: str,
578
+ prompt_cache: dict,
579
+ min_len: int = 2,
580
+ max_len: int = 2000,
581
+ inference_timesteps: int = 10,
582
+ cfg_value: float = 2.0,
583
+ retry_badcase: bool = False,
584
+ retry_badcase_max_times: int = 3,
585
+ retry_badcase_ratio_threshold: float = 6.0,
586
+ streaming: bool = False,
587
+ streaming_prefix_len: int = 3,
588
+ ) -> Generator[Tuple[torch.Tensor, torch.Tensor, Union[torch.Tensor, List[torch.Tensor]]], None, None]:
589
+ """
590
+ Generate audio using pre-built prompt cache.
591
+
592
+ Args:
593
+ target_text: Text to convert to speech
594
+ prompt_cache: Cache built by build_prompt_cache (can be None)
595
+ min_len: Minimum audio length to avoid very short audio
596
+ max_len: Maximum audio length
597
+ inference_timesteps: Number of diffusion sampling steps
598
+ cfg_value: Classifier-free guidance value
599
+ retry_badcase: Whether to retry on bad cases
600
+ retry_badcase_max_times: Maximum retry attempts
601
+ retry_badcase_ratio_threshold: Threshold for audio-to-text ratio
602
+ streaming: Whether to return a generator of audio chunks
603
+ streaming_prefix_len: Number of prefix audio patches to use for streaming mode
604
+
605
+ Returns:
606
+ Generator of Tuple containing:
607
+ - Decoded audio tensor for the current step if ``streaming=True``, else final decoded audio tensor
608
+ - Tensor of new text tokens
609
+ - New audio features up to the current step as a List if ``streaming=True``, else as a concatenated Tensor
610
+ """
611
+ if retry_badcase and streaming:
612
+ warnings.warn("Retry on bad cases is not supported in streaming mode, setting retry_badcase=False.")
613
+ retry_badcase = False
614
+ # get prompt from cache
615
+ if prompt_cache is None:
616
+ prompt_audio_feat = torch.empty((0, self.patch_size, self.audio_vae.latent_dim), dtype=torch.float32)
617
+ text = target_text
618
+ else:
619
+ prompt_audio_feat = prompt_cache["audio_feat"]
620
+ prompt_text = prompt_cache["prompt_text"]
621
+ text = prompt_text + target_text
622
+
623
+ text_token = torch.LongTensor(self.text_tokenizer(text))
624
+ text_token = torch.cat(
625
+ [
626
+ text_token,
627
+ torch.tensor(
628
+ [self.audio_start_token],
629
+ dtype=torch.int32,
630
+ device=text_token.device,
631
+ ),
632
+ ],
633
+ dim=-1,
634
+ )
635
+
636
+ target_text_token = torch.LongTensor(self.text_tokenizer(target_text))
637
+
638
+ audio_length = prompt_audio_feat.size(0)
639
+ text_length = text_token.shape[0]
640
+ text_pad_token = torch.zeros(audio_length, dtype=torch.int32, device=text_token.device)
641
+ audio_pad_feat = torch.zeros(
642
+ (text_token.shape[0], self.patch_size, self.audio_vae.latent_dim),
643
+ dtype=torch.float32,
644
+ device=text_token.device,
645
+ )
646
+ text_token = torch.cat([text_token, text_pad_token])
647
+ audio_feat = torch.cat([audio_pad_feat, prompt_audio_feat], dim=0)
648
+ text_mask = torch.cat([torch.ones(text_length), torch.zeros(audio_length)]).type(torch.int32).to(text_token.device)
649
+ audio_mask = torch.cat([torch.zeros(text_length), torch.ones(audio_length)]).type(torch.int32).to(text_token.device)
650
+
651
+ text_token = text_token.unsqueeze(0).to(self.device)
652
+ text_mask = text_mask.unsqueeze(0).to(self.device)
653
+ audio_feat = audio_feat.unsqueeze(0).to(self.device).to(get_dtype(self.config.dtype))
654
+ audio_mask = audio_mask.unsqueeze(0).to(self.device)
655
+
656
+ # run inference
657
+ target_text_length = len(self.text_tokenizer(target_text))
658
+ retry_badcase_times = 0
659
+ while retry_badcase_times < retry_badcase_max_times:
660
+ inference_result = self._inference(
661
+ text_token,
662
+ text_mask,
663
+ audio_feat,
664
+ audio_mask,
665
+ min_len=min_len,
666
+ max_len=min(int(target_text_length * retry_badcase_ratio_threshold + 10), max_len), # avoid too long audio
667
+ inference_timesteps=inference_timesteps,
668
+ cfg_value=cfg_value,
669
+ streaming=streaming,
670
+ streaming_prefix_len=streaming_prefix_len,
671
+ )
672
+ if streaming:
673
+ patch_len = self.patch_size * self.chunk_size
674
+ for latent_pred, pred_audio_feat in inference_result:
675
+ decode_audio = self.audio_vae.decode(latent_pred.to(torch.float32))
676
+ decode_audio = decode_audio[..., -patch_len:].squeeze(1).cpu()
677
+ yield (
678
+ decode_audio,
679
+ target_text_token,
680
+ pred_audio_feat
681
+ )
682
+ break
683
+ else:
684
+ latent_pred, pred_audio_feat = next(inference_result)
685
+ if retry_badcase:
686
+ if pred_audio_feat.shape[0] >= target_text_length * retry_badcase_ratio_threshold:
687
+ print(f" Badcase detected, audio_text_ratio={pred_audio_feat.shape[0] / target_text_length}, retrying...", file=sys.stderr)
688
+ retry_badcase_times += 1
689
+ continue
690
+ else:
691
+ break
692
+ else:
693
+ break
694
+ if not streaming:
695
+ decode_audio = self.audio_vae.decode(latent_pred.to(torch.float32))
696
+ patch_len = self.patch_size * self.chunk_size
697
+ if audio_mask.sum().item() > 0:
698
+ decode_audio = decode_audio[..., patch_len * (streaming_prefix_len - 1):].squeeze(1).cpu()
699
+ else:
700
+ decode_audio = decode_audio[..., :].squeeze(1).cpu()
701
+ yield (
702
+ decode_audio,
703
+ target_text_token,
704
+ pred_audio_feat
705
+ )
706
+
707
+ def inference(self, *args, **kwargs) -> Tuple[torch.Tensor, torch.Tensor]:
708
+ return next(self._inference(*args, streaming=False, **kwargs))
709
+
710
+ def inference_streaming(self, *args, **kwargs) -> Generator[Tuple[torch.Tensor, List[torch.Tensor]], None, None]:
711
+ return self._inference(*args, streaming=True, **kwargs)
712
+
713
+ @torch.inference_mode()
714
+ def _inference(
715
+ self,
716
+ text: torch.Tensor,
717
+ text_mask: torch.Tensor,
718
+ feat: torch.Tensor,
719
+ feat_mask: torch.Tensor,
720
+ min_len: int = 2,
721
+ max_len: int = 2000,
722
+ inference_timesteps: int = 10,
723
+ cfg_value: float = 2.0,
724
+ streaming: bool = False,
725
+ streaming_prefix_len: int = 3,
726
+ ) -> Generator[Tuple[torch.Tensor, Union[torch.Tensor, List[torch.Tensor]]], None, None]:
727
+ """Core inference method for audio generation.
728
+
729
+ This is the main inference loop that generates audio features
730
+ using the language model and diffusion transformer.
731
+
732
+ Args:
733
+ text: Input text tokens
734
+ text_mask: Mask for text tokens
735
+ feat: Input audio features
736
+ feat_mask: Mask for audio features
737
+ min_len: Minimum generation length
738
+ max_len: Maximum generation length
739
+ inference_timesteps: Number of diffusion steps
740
+ cfg_value: Classifier-free guidance value
741
+ streaming: Whether to yield each step latent feature or just the final result
742
+
743
+ Returns:
744
+ Generator of Tuple containing:
745
+ - Predicted latent feature at the current step if ``streaming=True``, else final latent features
746
+ - Predicted audio feature sequence so far as a List if ``streaming=True``, else as a concatenated Tensor
747
+ """
748
+ B, T, P, D = feat.shape
749
+
750
+ feat_embed = self.feat_encoder(feat) # [b, t, h_feat]
751
+ feat_embed = self.enc_to_lm_proj(feat_embed)
752
+
753
+ if self.config.lm_config.use_mup:
754
+ scale_emb = self.config.lm_config.scale_emb
755
+ else:
756
+ scale_emb = 1.0
757
+
758
+ text_embed = self.base_lm.embed_tokens(text) * scale_emb
759
+ combined_embed = text_mask.unsqueeze(-1) * text_embed + feat_mask.unsqueeze(-1) * feat_embed
760
+
761
+ prefix_feat_cond = feat[:, -1, ...] # b, p, d
762
+ pred_feat_seq = [] # b, t, p, d
763
+ curr_embed = None
764
+
765
+ # Prepare prompt context patches for streaming mode
766
+ # When there's a prompt audio, use its last (streaming_prefix_len - 1) patches as initial context
767
+ prompt_context_patches = []
768
+ audio_patch_count = int(feat_mask.sum().item())
769
+ if audio_patch_count > 0:
770
+ context_len = min(streaming_prefix_len - 1, audio_patch_count)
771
+ # Take the last context_len patches from prompt audio as initial context
772
+ # Split into list of [b, 1, p, d] tensors to match pred_feat_seq format
773
+ prompt_context_patches = list(feat[:, -context_len:, :, :].split(1, dim=1))
774
+ pred_feat_seq = prompt_context_patches + pred_feat_seq
775
+
776
+ enc_outputs, kv_cache_tuple = self.base_lm(
777
+ inputs_embeds=combined_embed,
778
+ is_causal=True,
779
+ )
780
+ self.base_lm.kv_cache.fill_caches(kv_cache_tuple)
781
+
782
+ enc_outputs = self.fsq_layer(enc_outputs) * feat_mask.unsqueeze(-1) + enc_outputs * text_mask.unsqueeze(-1)
783
+ lm_hidden = enc_outputs[:, -1, :]
784
+
785
+
786
+ residual_enc_outputs, residual_kv_cache_tuple = self.residual_lm(
787
+ inputs_embeds=enc_outputs + feat_mask.unsqueeze(-1) * feat_embed,
788
+ is_causal=True,
789
+ )
790
+ self.residual_lm.kv_cache.fill_caches(residual_kv_cache_tuple)
791
+ residual_hidden = residual_enc_outputs[:, -1, :]
792
+
793
+
794
+ for i in tqdm(range(max_len)):
795
+ dit_hidden_1 = self.lm_to_dit_proj(lm_hidden) # [b, h_dit]
796
+ dit_hidden_2 = self.res_to_dit_proj(residual_hidden) # [b, h_dit]
797
+ dit_hidden = dit_hidden_1 + dit_hidden_2 # [b, h_dit]
798
+
799
+ pred_feat = self.feat_decoder(
800
+ mu=dit_hidden,
801
+ patch_size=self.patch_size,
802
+ cond=prefix_feat_cond.transpose(1, 2).contiguous(),
803
+ n_timesteps=inference_timesteps,
804
+ cfg_value=cfg_value,
805
+ ).transpose(
806
+ 1, 2
807
+ ) # [b, p, d]
808
+
809
+ curr_embed = self.feat_encoder(pred_feat.unsqueeze(1)) # b, 1, c
810
+ curr_embed = self.enc_to_lm_proj(curr_embed)
811
+
812
+ pred_feat_seq.append(pred_feat.unsqueeze(1)) # b, 1, p, d
813
+ prefix_feat_cond = pred_feat
814
+
815
+ if streaming:
816
+ # return the last three predicted latent features to provide enough context for smooth decoding
817
+ pred_feat_chunk = torch.cat(pred_feat_seq[-streaming_prefix_len:], dim=1)
818
+ feat_pred = rearrange(pred_feat_chunk, "b t p d -> b d (t p)", b=B, p=self.patch_size)
819
+
820
+ yield feat_pred, pred_feat_seq
821
+
822
+ stop_flag = self.stop_head(self.stop_actn(self.stop_proj(lm_hidden))).argmax(dim=-1)[0].cpu().item()
823
+ if i > min_len and stop_flag == 1:
824
+ break
825
+
826
+ lm_hidden = self.base_lm.forward_step(
827
+ curr_embed[:, 0, :], torch.tensor([self.base_lm.kv_cache.step()], device=curr_embed.device)
828
+ ).clone()
829
+
830
+
831
+ lm_hidden = self.fsq_layer(lm_hidden)
832
+ residual_hidden = self.residual_lm.forward_step(
833
+ lm_hidden + curr_embed[:, 0, :], torch.tensor([self.residual_lm.kv_cache.step()], device=curr_embed.device)
834
+ ).clone()
835
+
836
+ if not streaming:
837
+ pred_feat_seq = torch.cat(pred_feat_seq, dim=1) # b, t, p, d
838
+ feat_pred = rearrange(pred_feat_seq, "b t p d -> b d (t p)", b=B, p=self.patch_size)
839
+ yield feat_pred, pred_feat_seq.squeeze(0).cpu()
840
+
841
+
842
+ @classmethod
843
+ def from_local(cls, path: str, optimize: bool = True, training: bool = False, lora_config: LoRAConfig = None):
844
+ config = VoxCPMConfig.model_validate_json(open(os.path.join(path, "config.json")).read())
845
+ tokenizer = LlamaTokenizerFast.from_pretrained(path)
846
+ audio_vae_config = getattr(config, 'audio_vae_config', None)
847
+ audio_vae = AudioVAE(config=audio_vae_config) if audio_vae_config else AudioVAE()
848
+ vae_state_dict = torch.load(
849
+ os.path.join(path, "audiovae.pth"),
850
+ map_location="cpu",
851
+ weights_only=True,
852
+ )["state_dict"]
853
+ model = cls(config, tokenizer, audio_vae, lora_config)
854
+ if not training:
855
+ lm_dtype = get_dtype(model.config.dtype)
856
+ model = model.to(lm_dtype)
857
+ else: # training mode
858
+ for name, param in model.named_parameters():
859
+ if "audio_vae" in name: # freeze VAE weights
860
+ param.requires_grad = False
861
+ continue
862
+ if lora_config is not None:
863
+ if "lora" not in name: # freeze non-LoRA weights
864
+ param.requires_grad = False
865
+ model.audio_vae = model.audio_vae.to(torch.float32)
866
+
867
+ # Try to load from safetensors first, fallback to pytorch_model.bin
868
+ safetensors_path = os.path.join(path, "model.safetensors")
869
+ pytorch_model_path = os.path.join(path, "pytorch_model.bin")
870
+
871
+ if os.path.exists(safetensors_path) and SAFETENSORS_AVAILABLE:
872
+ print(f"Loading model from safetensors: {safetensors_path}", file=sys.stderr)
873
+ model_state_dict = load_file(safetensors_path)
874
+ elif os.path.exists(pytorch_model_path):
875
+ print(f"Loading model from pytorch_model.bin: {pytorch_model_path}", file=sys.stderr)
876
+ checkpoint = torch.load(
877
+ pytorch_model_path,
878
+ map_location="cpu",
879
+ weights_only=True,
880
+ )
881
+ model_state_dict = checkpoint.get("state_dict", checkpoint)
882
+ else:
883
+ raise FileNotFoundError(
884
+ f"Model file not found. Expected either {safetensors_path} or {pytorch_model_path}"
885
+ )
886
+
887
+ for kw, val in vae_state_dict.items():
888
+ model_state_dict[f"audio_vae.{kw}"] = val
889
+
890
+ # LoRALinear holds weight/bias directly, compatible with nn.Linear state_dict keys.
891
+ # Using strict=False since pretrained weights don't contain lora_A/lora_B.
892
+ model.load_state_dict(model_state_dict, strict=False)
893
+ if training:
894
+ return model
895
+ return model.to(model.device).eval().optimize(disable=not optimize)
896
+
897
+ # ------------------------------------------------------------------ #
898
+ # LoRA Weight Management
899
+ # ------------------------------------------------------------------ #
900
+ def _iter_lora_modules(self):
901
+ """Iterate over all LoRA modules."""
902
+ from ..modules.layers.lora import LoRALinear
903
+ for module in self.modules():
904
+ if isinstance(module, LoRALinear):
905
+ yield module
906
+
907
+ def load_lora_weights(self, lora_path: str, device: str = None):
908
+ """
909
+ Load LoRA weights from file, supports calling after torch.compile.
910
+ Uses named_parameters() to handle compile's _orig_mod wrapper.
911
+ Supports both safetensors and pytorch formats.
912
+
913
+ Args:
914
+ lora_path: Checkpoint path (directory or .safetensors/.ckpt file)
915
+ device: Target device, defaults to model's current device
916
+ Returns:
917
+ tuple: (loaded_keys, skipped_keys)
918
+ """
919
+ from pathlib import Path
920
+
921
+ device = device or self.device
922
+ lora_path = Path(lora_path)
923
+
924
+ # Try safetensors first, then fallback to .ckpt
925
+ if lora_path.is_dir():
926
+ safetensors_file = lora_path / "lora_weights.safetensors"
927
+ ckpt_file = lora_path / "lora_weights.ckpt"
928
+ else:
929
+ safetensors_file = lora_path if lora_path.suffix == ".safetensors" else None
930
+ ckpt_file = lora_path if lora_path.suffix in [".ckpt", ".pth"] else None
931
+
932
+ # Load from safetensors if available
933
+ if safetensors_file and safetensors_file.exists() and SAFETENSORS_AVAILABLE:
934
+ state_dict = load_file(str(safetensors_file), device=device)
935
+ elif ckpt_file and ckpt_file.exists():
936
+ ckpt = torch.load(ckpt_file, map_location=device, weights_only=False)
937
+ state_dict = ckpt.get("state_dict", ckpt)
938
+ else:
939
+ raise FileNotFoundError(
940
+ f"LoRA checkpoint not found. Expected either {safetensors_file} or {ckpt_file}"
941
+ )
942
+
943
+ # Build param mapping (handle torch.compile's _orig_mod prefix)
944
+ model_params = dict(self.named_parameters())
945
+ key_mapping = {k.replace("._orig_mod.", "."): k for k in model_params if "._orig_mod." in k}
946
+
947
+ loaded_keys, skipped_keys = [], []
948
+ for key, value in state_dict.items():
949
+ target_key = key if key in model_params else key_mapping.get(key)
950
+ if target_key:
951
+ model_params[target_key].data.copy_(value.to(device))
952
+ loaded_keys.append(key)
953
+ else:
954
+ skipped_keys.append(key)
955
+
956
+ return loaded_keys, skipped_keys
957
+
958
+ def set_lora_enabled(self, enabled: bool):
959
+ """Enable/disable all LoRA layers."""
960
+ for module in self._iter_lora_modules():
961
+ module.set_enabled(enabled)
962
+
963
+ def reset_lora_weights(self):
964
+ """Reset all LoRA weights (A: kaiming, B: zeros), effectively unloading LoRA."""
965
+ for module in self._iter_lora_modules():
966
+ module.reset_lora_parameters()
967
+
968
+ def get_lora_state_dict(self) -> dict:
969
+ """Get all LoRA parameters (lora_A/lora_B)."""
970
+ return {name: param.data.clone()
971
+ for name, param in self.named_parameters()
972
+ if "lora_" in name}
convert/src/voxcpm/modules/__init__.py ADDED
File without changes
convert/src/voxcpm/modules/audiovae/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .audio_vae import AudioVAE, AudioVAEConfig
convert/src/voxcpm/modules/audiovae/audio_vae.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Union, Optional
3
+
4
+ import numpy as np
5
+ import torch
6
+ from torch import nn
7
+ import torch.nn.functional as F
8
+ from torch.nn.utils import weight_norm
9
+ from pydantic import BaseModel
10
+
11
+
12
+ def WNConv1d(*args, **kwargs):
13
+ return weight_norm(nn.Conv1d(*args, **kwargs))
14
+
15
+
16
+ def WNConvTranspose1d(*args, **kwargs):
17
+ return weight_norm(nn.ConvTranspose1d(*args, **kwargs))
18
+
19
+
20
+ class CausalConv1d(nn.Conv1d):
21
+ def __init__(self, *args, padding: int = 0, **kwargs):
22
+ super().__init__(*args, **kwargs)
23
+ self.__padding = padding
24
+
25
+ def forward(self, x):
26
+ x_pad = F.pad(x, (self.__padding * 2, 0))
27
+ return super().forward(x_pad)
28
+
29
+
30
+ class CausalTransposeConv1d(nn.ConvTranspose1d):
31
+ def __init__(self, *args, padding: int = 0, output_padding: int = 0, **kwargs):
32
+ super().__init__(*args, **kwargs)
33
+ self.__padding = padding
34
+ self.__output_padding = output_padding
35
+
36
+ def forward(self, x):
37
+ return super().forward(x)[..., : -(self.__padding * 2 - self.__output_padding)]
38
+
39
+
40
+ def WNCausalConv1d(*args, **kwargs):
41
+ return weight_norm(CausalConv1d(*args, **kwargs))
42
+
43
+
44
+ def WNCausalTransposeConv1d(*args, **kwargs):
45
+ return weight_norm(CausalTransposeConv1d(*args, **kwargs))
46
+
47
+
48
+ # Scripting this brings model speed up 1.4x
49
+ @torch.jit.script
50
+ def snake(x, alpha):
51
+ shape = x.shape
52
+ x = x.reshape(shape[0], shape[1], -1)
53
+ x = x + (alpha + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2)
54
+ x = x.reshape(shape)
55
+ return x
56
+
57
+
58
+ class Snake1d(nn.Module):
59
+ def __init__(self, channels):
60
+ super().__init__()
61
+ self.alpha = nn.Parameter(torch.ones(1, channels, 1))
62
+
63
+ def forward(self, x):
64
+ return snake(x, self.alpha)
65
+
66
+
67
+ def init_weights(m):
68
+ if isinstance(m, nn.Conv1d):
69
+ nn.init.trunc_normal_(m.weight, std=0.02)
70
+ if m.bias is not None:
71
+ nn.init.constant_(m.bias, 0)
72
+
73
+
74
+ class CausalResidualUnit(nn.Module):
75
+ def __init__(self, dim: int = 16, dilation: int = 1, kernel: int = 7, groups: int = 1):
76
+ super().__init__()
77
+ pad = ((7 - 1) * dilation) // 2
78
+ self.block = nn.Sequential(
79
+ Snake1d(dim),
80
+ WNCausalConv1d(
81
+ dim,
82
+ dim,
83
+ kernel_size=kernel,
84
+ dilation=dilation,
85
+ padding=pad,
86
+ groups=groups,
87
+ ),
88
+ Snake1d(dim),
89
+ WNCausalConv1d(dim, dim, kernel_size=1),
90
+ )
91
+
92
+ def forward(self, x):
93
+ y = self.block(x)
94
+ pad = (x.shape[-1] - y.shape[-1]) // 2
95
+ assert pad == 0
96
+ if pad > 0:
97
+ x = x[..., pad:-pad]
98
+ return x + y
99
+
100
+
101
+ class CausalEncoderBlock(nn.Module):
102
+ def __init__(self, output_dim: int = 16, input_dim=None, stride: int = 1, groups=1):
103
+ super().__init__()
104
+ input_dim = input_dim or output_dim // 2
105
+ self.block = nn.Sequential(
106
+ CausalResidualUnit(input_dim, dilation=1, groups=groups),
107
+ CausalResidualUnit(input_dim, dilation=3, groups=groups),
108
+ CausalResidualUnit(input_dim, dilation=9, groups=groups),
109
+ Snake1d(input_dim),
110
+ WNCausalConv1d(
111
+ input_dim,
112
+ output_dim,
113
+ kernel_size=2 * stride,
114
+ stride=stride,
115
+ padding=math.ceil(stride / 2),
116
+ ),
117
+ )
118
+
119
+ def forward(self, x):
120
+ return self.block(x)
121
+
122
+
123
+ class CausalEncoder(nn.Module):
124
+ def __init__(
125
+ self,
126
+ d_model: int = 64,
127
+ latent_dim: int = 32,
128
+ strides: list = [2, 4, 8, 8],
129
+ depthwise: bool = False,
130
+ ):
131
+ super().__init__()
132
+ # Create first convolution
133
+ self.block = [WNCausalConv1d(1, d_model, kernel_size=7, padding=3)]
134
+
135
+ # Create EncoderBlocks that double channels as they downsample by `stride`
136
+ for stride in strides:
137
+ d_model *= 2
138
+ groups = d_model // 2 if depthwise else 1
139
+ self.block += [CausalEncoderBlock(output_dim=d_model, stride=stride, groups=groups)]
140
+
141
+ groups = d_model if depthwise else 1
142
+
143
+ # Create two convolution, for mu and logvar
144
+ self.fc_mu = WNCausalConv1d(d_model, latent_dim, kernel_size=3, padding=1)
145
+ self.fc_logvar = WNCausalConv1d(d_model, latent_dim, kernel_size=3, padding=1)
146
+
147
+ # Wrap black into nn.Sequential
148
+ self.block = nn.Sequential(*self.block)
149
+ self.enc_dim = d_model
150
+
151
+ def forward(self, x):
152
+ hidden_state = self.block(x)
153
+ return {
154
+ "hidden_state": hidden_state,
155
+ "mu": self.fc_mu(hidden_state),
156
+ "logvar": self.fc_logvar(hidden_state),
157
+ }
158
+
159
+
160
+ class NoiseBlock(nn.Module):
161
+ def __init__(self, dim):
162
+ super().__init__()
163
+ self.linear = WNCausalConv1d(dim, dim, kernel_size=1, bias=False)
164
+
165
+ def forward(self, x):
166
+ B, C, T = x.shape
167
+ noise = torch.randn((B, 1, T), device=x.device, dtype=x.dtype)
168
+ h = self.linear(x)
169
+ n = noise * h
170
+ x = x + n
171
+ return x
172
+
173
+
174
+ class CausalDecoderBlock(nn.Module):
175
+ def __init__(
176
+ self,
177
+ input_dim: int = 16,
178
+ output_dim: int = 8,
179
+ stride: int = 1,
180
+ groups=1,
181
+ use_noise_block: bool = False,
182
+ ):
183
+ super().__init__()
184
+ layers = [
185
+ Snake1d(input_dim),
186
+ WNCausalTransposeConv1d(
187
+ input_dim,
188
+ output_dim,
189
+ kernel_size=2 * stride,
190
+ stride=stride,
191
+ padding=math.ceil(stride / 2),
192
+ output_padding=stride % 2,
193
+ ),
194
+ ]
195
+ if use_noise_block:
196
+ layers.append(NoiseBlock(output_dim))
197
+ layers.extend(
198
+ [
199
+ CausalResidualUnit(output_dim, dilation=1, groups=groups),
200
+ CausalResidualUnit(output_dim, dilation=3, groups=groups),
201
+ CausalResidualUnit(output_dim, dilation=9, groups=groups),
202
+ ]
203
+ )
204
+ self.block = nn.Sequential(*layers)
205
+
206
+ def forward(self, x):
207
+ return self.block(x)
208
+
209
+
210
+ class TransposeLastTwoDim(torch.nn.Module):
211
+ def forward(self, x):
212
+ return torch.transpose(x, -1, -2)
213
+
214
+
215
+ class CausalDecoder(nn.Module):
216
+ def __init__(
217
+ self,
218
+ input_channel,
219
+ channels,
220
+ rates,
221
+ depthwise: bool = False,
222
+ d_out: int = 1,
223
+ use_noise_block: bool = False,
224
+ ):
225
+ super().__init__()
226
+
227
+ # Add first conv layer
228
+ if depthwise:
229
+ layers = [
230
+ WNCausalConv1d(
231
+ input_channel,
232
+ input_channel,
233
+ kernel_size=7,
234
+ padding=3,
235
+ groups=input_channel,
236
+ ),
237
+ WNCausalConv1d(input_channel, channels, kernel_size=1),
238
+ ]
239
+ else:
240
+ layers = [WNCausalConv1d(input_channel, channels, kernel_size=7, padding=3)]
241
+
242
+ # Add upsampling + MRF blocks
243
+ for i, stride in enumerate(rates):
244
+ input_dim = channels // 2**i
245
+ output_dim = channels // 2 ** (i + 1)
246
+ groups = output_dim if depthwise else 1
247
+ layers += [
248
+ CausalDecoderBlock(
249
+ input_dim,
250
+ output_dim,
251
+ stride,
252
+ groups=groups,
253
+ use_noise_block=use_noise_block,
254
+ )
255
+ ]
256
+
257
+ # Add final conv layer
258
+ layers += [
259
+ Snake1d(output_dim),
260
+ WNCausalConv1d(output_dim, d_out, kernel_size=7, padding=3),
261
+ nn.Tanh(),
262
+ ]
263
+
264
+ self.model = nn.Sequential(*layers)
265
+
266
+ def forward(self, x):
267
+ return self.model(x)
268
+
269
+
270
+ class AudioVAEConfig(BaseModel):
271
+ encoder_dim: int = 128
272
+ encoder_rates: List[int] = [2, 5, 8, 8]
273
+ latent_dim: int = 64
274
+ decoder_dim: int = 1536
275
+ decoder_rates: List[int] = [8, 8, 5, 2]
276
+ depthwise: bool = True
277
+ sample_rate: int = 16000
278
+ use_noise_block: bool = False
279
+
280
+
281
+ class AudioVAE(nn.Module):
282
+ """
283
+ Args:
284
+ """
285
+
286
+ def __init__(
287
+ self,
288
+ config: Optional[AudioVAEConfig] = None,
289
+ ):
290
+ # 如果没有传入config,使用默认配置
291
+ if config is None:
292
+ config = AudioVAEConfig()
293
+
294
+ super().__init__()
295
+
296
+ encoder_dim = config.encoder_dim
297
+ encoder_rates = config.encoder_rates
298
+ latent_dim = config.latent_dim
299
+ decoder_dim = config.decoder_dim
300
+ decoder_rates = config.decoder_rates
301
+ depthwise = config.depthwise
302
+ sample_rate = config.sample_rate
303
+ use_noise_block = config.use_noise_block
304
+
305
+ self.encoder_dim = encoder_dim
306
+ self.encoder_rates = encoder_rates
307
+ self.decoder_dim = decoder_dim
308
+ self.decoder_rates = decoder_rates
309
+ self.depthwise = depthwise
310
+
311
+ self.use_noise_block = use_noise_block
312
+
313
+ if latent_dim is None:
314
+ latent_dim = encoder_dim * (2 ** len(encoder_rates))
315
+
316
+ self.latent_dim = latent_dim
317
+ self.hop_length = np.prod(encoder_rates)
318
+ self.encoder = CausalEncoder(
319
+ encoder_dim,
320
+ latent_dim,
321
+ encoder_rates,
322
+ depthwise=depthwise,
323
+ )
324
+
325
+ self.decoder = CausalDecoder(
326
+ latent_dim,
327
+ decoder_dim,
328
+ decoder_rates,
329
+ depthwise=depthwise,
330
+ use_noise_block=use_noise_block,
331
+ )
332
+ self.sample_rate = sample_rate
333
+ self.chunk_size = math.prod(encoder_rates)
334
+
335
+ def preprocess(self, audio_data, sample_rate):
336
+ if sample_rate is None:
337
+ sample_rate = self.sample_rate
338
+ assert sample_rate == self.sample_rate
339
+ pad_to = self.hop_length
340
+ length = audio_data.shape[-1]
341
+ right_pad = math.ceil(length / pad_to) * pad_to - length
342
+ audio_data = nn.functional.pad(audio_data, (0, right_pad))
343
+
344
+ return audio_data
345
+
346
+ def decode(self, z: torch.Tensor):
347
+ """Decode given latent codes and return audio data
348
+
349
+ Parameters
350
+ ----------
351
+ z : Tensor[B x D x T]
352
+ Quantized continuous representation of input
353
+ length : int, optional
354
+ Number of samples in output audio, by default None
355
+
356
+ Returns
357
+ -------
358
+ dict
359
+ A dictionary with the following keys:
360
+ "audio" : Tensor[B x 1 x length]
361
+ Decoded audio data.
362
+ """
363
+ return self.decoder(z)
364
+
365
+ def encode(self, audio_data: torch.Tensor, sample_rate: int):
366
+ """
367
+ Args:
368
+ audio_data: Tensor[B x 1 x T]
369
+ sample_rate: int
370
+ Returns:
371
+ z: Tensor[B x D x T]
372
+ """
373
+ if audio_data.ndim == 2:
374
+ audio_data = audio_data.unsqueeze(1)
375
+
376
+ audio_data = self.preprocess(audio_data, sample_rate)
377
+ return self.encoder(audio_data)["mu"]
convert/src/voxcpm/modules/layers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .scalar_quantization_layer import ScalarQuantizationLayer
convert/src/voxcpm/modules/layers/lora.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+
9
+ class LoRALinear(nn.Module):
10
+ """
11
+ LoRA 线性层:直接持有 weight/bias,保持与 nn.Linear 相同的 state_dict key 结构。
12
+
13
+ state_dict 结构:
14
+ - weight: 原始权重(与 nn.Linear 一致)
15
+ - bias: 原始偏置(与 nn.Linear 一致)
16
+ - lora_A: LoRA 低秩矩阵 A
17
+ - lora_B: LoRA 低秩矩阵 B
18
+
19
+ 这样设计的好处:加载预训练权重时无需做 key 转换。
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ base: nn.Linear,
25
+ r: int,
26
+ alpha: float = 1.0,
27
+ dropout: float = 0.0,
28
+ ):
29
+ super().__init__()
30
+ assert isinstance(base, nn.Linear), "LoRALinear only supports wrapping nn.Linear."
31
+
32
+ self.in_features = base.in_features
33
+ self.out_features = base.out_features
34
+ self.r = r
35
+ self.alpha = alpha
36
+ self._base_scaling = alpha / r if r > 0 else 0.0
37
+
38
+ # 使用 buffer 存储 scaling,这样修改值不会触发 torch.compile 重编译
39
+ # persistent=False 表示不保存到 state_dict,避免加载时 missing key
40
+ self.register_buffer("scaling", torch.tensor(self._base_scaling), persistent=False)
41
+
42
+ # 直接持有 weight 和 bias(从原始 Linear 转移过来)
43
+ self.weight = base.weight
44
+ self.bias = base.bias # 可能是 None
45
+
46
+ # LoRA 参数
47
+ if r > 0:
48
+ self.lora_A = nn.Parameter(torch.zeros(r, self.in_features))
49
+ self.lora_B = nn.Parameter(torch.zeros(self.out_features, r))
50
+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
51
+ nn.init.zeros_(self.lora_B)
52
+ else:
53
+ self.register_parameter("lora_A", None)
54
+ self.register_parameter("lora_B", None)
55
+
56
+ self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
57
+
58
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
59
+ # 基础 Linear 计算
60
+ result = F.linear(x, self.weight, self.bias)
61
+ if self.r <= 0 or self.lora_A is None:
62
+ return result
63
+ # LoRA: result + dropout(x @ A^T @ B^T) * scaling
64
+ lora_out = F.linear(F.linear(x, self.lora_A), self.lora_B)
65
+ return result + self.dropout(lora_out) * self.scaling
66
+
67
+ def reset_lora_parameters(self):
68
+ """重置 LoRA 参数到初始状态"""
69
+ if self.r > 0 and self.lora_A is not None:
70
+ nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
71
+ nn.init.zeros_(self.lora_B)
72
+
73
+ def set_enabled(self, enabled: bool):
74
+ """启用/禁用 LoRA(通过 scaling 控制,兼容 torch.compile)"""
75
+ # 使用 fill_ 原地修改 buffer 值,不会触发重编译
76
+ self.scaling.fill_(self._base_scaling if enabled else 0.0)
77
+
78
+ @property
79
+ def enabled(self) -> bool:
80
+ return self.scaling.item() != 0.0
81
+
82
+
83
+ def _get_parent_module(root: nn.Module, name: str) -> Optional[nn.Module]:
84
+ """
85
+ 根据类似 'layers.0.self_attn.q_proj' 的全名,返回 parent module(即 q_proj 的上一级)。
86
+ """
87
+ parts = name.split(".")
88
+ if len(parts) == 1:
89
+ return root
90
+ parent = root
91
+ for p in parts[:-1]:
92
+ if not hasattr(parent, p):
93
+ return None
94
+ parent = getattr(parent, p)
95
+ return parent
96
+
97
+
98
+ def apply_lora_to_named_linear_modules(
99
+ root: nn.Module,
100
+ *,
101
+ target_submodule_names: list[str],
102
+ r: int,
103
+ alpha: float,
104
+ dropout: float,
105
+ ) -> None:
106
+ """
107
+ 在给定模块及其子模块中,对名字以 target_submodule_names 结尾的 Linear 层注入 LoRA。
108
+
109
+ 例如 target_submodule_names=["q_proj", "v_proj"] 时,
110
+ 会在所有名为 *.q_proj / *.v_proj 的 nn.Linear 上替换为 LoRALinear。
111
+ """
112
+ for full_name, module in list(root.named_modules()):
113
+ if not isinstance(module, nn.Linear):
114
+ continue
115
+ short_name = full_name.split(".")[-1]
116
+ if short_name not in target_submodule_names:
117
+ continue
118
+
119
+ parent = _get_parent_module(root, full_name)
120
+ if parent is None:
121
+ continue
122
+
123
+ # 用 LoRALinear 替换原始 Linear
124
+ lora_layer = LoRALinear(
125
+ base=module,
126
+ r=r,
127
+ alpha=alpha,
128
+ dropout=dropout,
129
+ )
130
+ setattr(parent, short_name, lora_layer)
131
+
132
+
133
+
convert/src/voxcpm/modules/layers/scalar_quantization_layer.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class ScalarQuantizationLayer(nn.Module):
6
+ def __init__(self, in_dim, out_dim, latent_dim: int = 64, scale: int = 9):
7
+ super().__init__()
8
+ self.in_dim = in_dim
9
+ self.out_dim = out_dim
10
+ self.latent_dim = latent_dim
11
+ self.scale = scale
12
+
13
+ self.in_proj = nn.Linear(in_dim, latent_dim)
14
+ self.out_proj = nn.Linear(latent_dim, out_dim)
15
+
16
+ def forward(self, hidden):
17
+ hidden = self.in_proj(hidden)
18
+ hidden = torch.tanh(hidden)
19
+
20
+ if self.training:
21
+ quantized = torch.round(hidden * self.scale) / self.scale
22
+ hidden = hidden + (quantized - hidden).detach()
23
+ else:
24
+ hidden = torch.round(hidden * self.scale) / self.scale
25
+
26
+ return self.out_proj(hidden)
convert/src/voxcpm/modules/locdit/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .unified_cfm import UnifiedCFM, CfmConfig
2
+ from .local_dit import VoxCPMLocDiT
convert/src/voxcpm/modules/locdit/local_dit.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from ..minicpm4 import MiniCPMModel, MiniCPM4Config
3
+ import torch.nn as nn
4
+ import math
5
+
6
+
7
+ class SinusoidalPosEmb(torch.nn.Module):
8
+ def __init__(self, dim):
9
+ super().__init__()
10
+ self.dim = dim
11
+ assert self.dim % 2 == 0, "SinusoidalPosEmb requires dim to be even"
12
+
13
+ def forward(self, x, scale=1000):
14
+ if x.ndim < 1:
15
+ x = x.unsqueeze(0)
16
+ device = x.device
17
+ half_dim = self.dim // 2
18
+ emb = math.log(10000) / (half_dim - 1)
19
+ emb = torch.exp(torch.arange(half_dim, dtype=x.dtype, device=device) * -emb)
20
+ emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
21
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
22
+ return emb
23
+
24
+
25
+ class TimestepEmbedding(nn.Module):
26
+ def __init__(
27
+ self,
28
+ in_channels: int,
29
+ time_embed_dim: int,
30
+ out_dim: int = None,
31
+ ):
32
+ super().__init__()
33
+
34
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim, bias=True)
35
+ self.act = nn.SiLU()
36
+ if out_dim is not None:
37
+ time_embed_dim_out = out_dim
38
+ else:
39
+ time_embed_dim_out = time_embed_dim
40
+
41
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out, bias=True)
42
+
43
+ def forward(self, sample):
44
+ sample = self.linear_1(sample)
45
+ sample = self.act(sample)
46
+ sample = self.linear_2(sample)
47
+ return sample
48
+
49
+
50
+ class VoxCPMLocDiT(nn.Module):
51
+ """
52
+ Diffusion model with a Transformer backbone.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ config: MiniCPM4Config,
58
+ in_channels: int = 64,
59
+ ):
60
+ super().__init__()
61
+ self.in_channels = in_channels
62
+ self.out_channels = in_channels
63
+ self.config = config
64
+
65
+ self.in_proj = nn.Linear(in_channels, config.hidden_size, bias=True)
66
+ self.cond_proj = nn.Linear(in_channels, config.hidden_size, bias=True)
67
+ self.out_proj = nn.Linear(config.hidden_size, self.out_channels, bias=True)
68
+
69
+ self.time_embeddings = SinusoidalPosEmb(config.hidden_size)
70
+ self.time_mlp = TimestepEmbedding(
71
+ in_channels=config.hidden_size,
72
+ time_embed_dim=config.hidden_size,
73
+ )
74
+ self.delta_time_mlp = TimestepEmbedding(
75
+ in_channels=config.hidden_size,
76
+ time_embed_dim=config.hidden_size,
77
+ )
78
+
79
+ assert config.vocab_size == 0, "vocab_size must be 0 for local DiT"
80
+ self.decoder = MiniCPMModel(config)
81
+
82
+ def forward(
83
+ self,
84
+ x: torch.Tensor,
85
+ mu: torch.Tensor,
86
+ t: torch.Tensor,
87
+ cond: torch.Tensor,
88
+ dt: torch.Tensor,
89
+ ):
90
+ """
91
+ Forward pass of DiT.
92
+ x: (N, C, T) tensor of inputs
93
+ mu: (N, C) tensor of hidden embedding
94
+ t: (N,) tensor of diffusion timesteps
95
+ cond: (N, C, T') tensor of prefix conditions
96
+ dt: (N,) used for mean velocity (may be supported in the future...)
97
+ """
98
+ x = self.in_proj(x.transpose(1, 2).contiguous())
99
+
100
+ cond = self.cond_proj(cond.transpose(1, 2).contiguous())
101
+ prefix = cond.size(1)
102
+
103
+ t = self.time_embeddings(t).to(x.dtype)
104
+ t = self.time_mlp(t)
105
+ dt = self.time_embeddings(dt).to(x.dtype)
106
+ dt = self.delta_time_mlp(dt)
107
+ t = t + dt
108
+
109
+ x = torch.cat([(mu + t).unsqueeze(1), cond, x], dim=1)
110
+ hidden, _ = self.decoder(x, is_causal=False)
111
+ hidden = hidden[:, prefix + 1 :, :]
112
+ hidden = self.out_proj(hidden)
113
+
114
+ return hidden.transpose(1, 2).contiguous()
convert/src/voxcpm/modules/locdit/unified_cfm.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch.func import jvp
6
+ from pydantic import BaseModel
7
+
8
+ from .local_dit import VoxCPMLocDiT
9
+
10
+
11
+ class CfmConfig(BaseModel):
12
+ sigma_min: float = 1e-6
13
+ solver: str = "euler"
14
+ t_scheduler: str = "log-norm"
15
+ training_cfg_rate: float = 0.1
16
+ inference_cfg_rate: float = 1.0
17
+ reg_loss_type: str = "l1"
18
+ ratio_r_neq_t_range: Tuple[float, float] = (0.25, 0.75)
19
+ noise_cond_prob_range: Tuple[float, float] = (0.0, 0.0)
20
+ noise_cond_scale: float = 0.0
21
+
22
+
23
+ class UnifiedCFM(torch.nn.Module):
24
+ def __init__(
25
+ self,
26
+ in_channels: int,
27
+ cfm_params: CfmConfig,
28
+ estimator: VoxCPMLocDiT,
29
+ mean_mode: bool = False,
30
+ ):
31
+ super().__init__()
32
+ self.solver = cfm_params.solver
33
+ self.sigma_min = cfm_params.sigma_min
34
+ self.t_scheduler = cfm_params.t_scheduler
35
+ self.training_cfg_rate = cfm_params.training_cfg_rate
36
+ self.inference_cfg_rate = cfm_params.inference_cfg_rate
37
+ self.reg_loss_type = cfm_params.reg_loss_type
38
+ self.ratio_r_neq_t_range = cfm_params.ratio_r_neq_t_range
39
+ self.noise_cond_prob_range = cfm_params.noise_cond_prob_range
40
+ self.noise_cond_scale = cfm_params.noise_cond_scale
41
+
42
+ self.in_channels = in_channels
43
+ self.mean_mode = mean_mode
44
+
45
+ self.estimator = estimator
46
+
47
+ # ------------------------------------------------------------------ #
48
+ # Inference
49
+ # ------------------------------------------------------------------ #
50
+ @torch.inference_mode()
51
+ def forward(
52
+ self,
53
+ mu: torch.Tensor,
54
+ n_timesteps: int,
55
+ patch_size: int,
56
+ cond: torch.Tensor,
57
+ temperature: float = 1.0,
58
+ cfg_value: float = 1.0,
59
+ sway_sampling_coef: float = 1.0,
60
+ use_cfg_zero_star: bool = True,
61
+ ):
62
+ b, _ = mu.shape
63
+ t = patch_size
64
+ z = torch.randn((b, self.in_channels, t), device=mu.device, dtype=mu.dtype) * temperature
65
+
66
+ t_span = torch.linspace(1, 0, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
67
+ t_span = t_span + sway_sampling_coef * (torch.cos(torch.pi / 2 * t_span) - 1 + t_span)
68
+
69
+ return self.solve_euler(
70
+ x=z,
71
+ t_span=t_span,
72
+ mu=mu,
73
+ cond=cond,
74
+ cfg_value=cfg_value,
75
+ use_cfg_zero_star=use_cfg_zero_star,
76
+ )
77
+
78
+ def optimized_scale(self, positive_flat: torch.Tensor, negative_flat: torch.Tensor):
79
+ dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)
80
+ squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
81
+ st_star = dot_product / squared_norm
82
+ return st_star
83
+
84
+ def solve_euler(
85
+ self,
86
+ x: torch.Tensor,
87
+ t_span: torch.Tensor,
88
+ mu: torch.Tensor,
89
+ cond: torch.Tensor,
90
+ cfg_value: float = 1.0,
91
+ use_cfg_zero_star: bool = True,
92
+ ):
93
+ t, _, dt = t_span[0], t_span[-1], t_span[0] - t_span[1]
94
+
95
+ sol = []
96
+ zero_init_steps = max(1, int(len(t_span) * 0.04))
97
+ for step in range(1, len(t_span)):
98
+ if use_cfg_zero_star and step <= zero_init_steps:
99
+ dphi_dt = torch.zeros_like(x)
100
+ else:
101
+ # Classifier-Free Guidance inference introduced in VoiceBox
102
+ b = x.size(0)
103
+ x_in = torch.zeros([2 * b, self.in_channels, x.size(2)], device=x.device, dtype=x.dtype)
104
+ mu_in = torch.zeros([2 * b, mu.size(1)], device=x.device, dtype=x.dtype)
105
+ t_in = torch.zeros([2 * b], device=x.device, dtype=x.dtype)
106
+ dt_in = torch.zeros([2 * b], device=x.device, dtype=x.dtype)
107
+ cond_in = torch.zeros([2 * b, self.in_channels, cond.size(2)], device=x.device, dtype=x.dtype)
108
+ x_in[:b], x_in[b:] = x, x
109
+ mu_in[:b] = mu
110
+ t_in[:b], t_in[b:] = t.unsqueeze(0), t.unsqueeze(0)
111
+ dt_in[:b], dt_in[b:] = dt.unsqueeze(0), dt.unsqueeze(0)
112
+ # not used now
113
+ if not self.mean_mode:
114
+ dt_in = torch.zeros_like(dt_in)
115
+ cond_in[:b], cond_in[b:] = cond, cond
116
+
117
+ dphi_dt = self.estimator(x_in, mu_in, t_in, cond_in, dt_in)
118
+ dphi_dt, cfg_dphi_dt = torch.split(dphi_dt, [x.size(0), x.size(0)], dim=0)
119
+
120
+ if use_cfg_zero_star:
121
+ positive_flat = dphi_dt.view(b, -1)
122
+ negative_flat = cfg_dphi_dt.view(b, -1)
123
+ st_star = self.optimized_scale(positive_flat, negative_flat)
124
+ st_star = st_star.view(b, *([1] * (len(dphi_dt.shape) - 1)))
125
+ else:
126
+ st_star = 1.0
127
+
128
+ dphi_dt = cfg_dphi_dt * st_star + cfg_value * (dphi_dt - cfg_dphi_dt * st_star)
129
+
130
+ x = x - dt * dphi_dt
131
+ t = t - dt
132
+ sol.append(x)
133
+ if step < len(t_span) - 1:
134
+ dt = t - t_span[step + 1]
135
+
136
+ return sol[-1]
137
+
138
+ # ------------------------------------------------------------------ #
139
+ # Training loss
140
+ # ------------------------------------------------------------------ #
141
+ def adaptive_loss_weighting(self, losses: torch.Tensor, mask: torch.Tensor | None = None, p: float = 0.0, epsilon: float = 1e-3):
142
+ weights = 1.0 / ((losses + epsilon).pow(p))
143
+ if mask is not None:
144
+ weights = weights * mask
145
+ return weights.detach()
146
+
147
+ def sample_r_t(self, x: torch.Tensor, mu: float = -0.4, sigma: float = 1.0, ratio_r_neq_t: float = 0.0):
148
+ batch_size = x.shape[0]
149
+ if self.t_scheduler == "log-norm":
150
+ s_r = torch.randn(batch_size, device=x.device, dtype=x.dtype) * sigma + mu
151
+ s_t = torch.randn(batch_size, device=x.device, dtype=x.dtype) * sigma + mu
152
+ r = torch.sigmoid(s_r)
153
+ t = torch.sigmoid(s_t)
154
+ elif self.t_scheduler == "uniform":
155
+ r = torch.rand(batch_size, device=x.device, dtype=x.dtype)
156
+ t = torch.rand(batch_size, device=x.device, dtype=x.dtype)
157
+ else:
158
+ raise ValueError(f"Unsupported t_scheduler: {self.t_scheduler}")
159
+
160
+ mask = torch.rand(batch_size, device=x.device, dtype=x.dtype) < ratio_r_neq_t
161
+ r, t = torch.where(
162
+ mask,
163
+ torch.stack([torch.min(r, t), torch.max(r, t)], dim=0),
164
+ torch.stack([t, t], dim=0),
165
+ )
166
+
167
+ return r.squeeze(), t.squeeze()
168
+
169
+ def compute_loss(
170
+ self,
171
+ x1: torch.Tensor,
172
+ mu: torch.Tensor,
173
+ cond: torch.Tensor | None = None,
174
+ tgt_mask: torch.Tensor | None = None,
175
+ progress: float = 0.0,
176
+ ):
177
+ b, _, _ = x1.shape
178
+
179
+ if self.training_cfg_rate > 0:
180
+ cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate
181
+ mu = mu * cfg_mask.view(-1, 1)
182
+
183
+ if cond is None:
184
+ cond = torch.zeros_like(x1)
185
+
186
+ noisy_mask = torch.rand(b, device=x1.device) > (
187
+ 1.0
188
+ - (
189
+ self.noise_cond_prob_range[0]
190
+ + progress * (self.noise_cond_prob_range[1] - self.noise_cond_prob_range[0])
191
+ )
192
+ )
193
+ cond = cond + noisy_mask.view(-1, 1, 1) * torch.randn_like(cond) * self.noise_cond_scale
194
+
195
+ ratio_r_neq_t = (
196
+ self.ratio_r_neq_t_range[0]
197
+ + progress * (self.ratio_r_neq_t_range[1] - self.ratio_r_neq_t_range[0])
198
+ if self.mean_mode
199
+ else 0.0
200
+ )
201
+
202
+ r, t = self.sample_r_t(x1, ratio_r_neq_t=ratio_r_neq_t)
203
+ r_ = r.detach().clone()
204
+ t_ = t.detach().clone()
205
+ z = torch.randn_like(x1)
206
+ y = (1 - t_.view(-1, 1, 1)) * x1 + t_.view(-1, 1, 1) * z
207
+ v = z - x1
208
+
209
+ def model_fn(z_sample, r_sample, t_sample):
210
+ return self.estimator(z_sample, mu, t_sample, cond, dt=t_sample - r_sample)
211
+
212
+ if self.mean_mode:
213
+ v_r = torch.zeros_like(r)
214
+ v_t = torch.ones_like(t)
215
+ from torch.backends.cuda import sdp_kernel
216
+
217
+ with sdp_kernel(enable_flash=False, enable_mem_efficient=False):
218
+ u_pred, dudt = jvp(model_fn, (y, r, t), (v, v_r, v_t))
219
+ u_tgt = v - (t_ - r_).view(-1, 1, 1) * dudt
220
+ else:
221
+ u_pred = model_fn(y, r, t)
222
+ u_tgt = v
223
+
224
+ losses = F.mse_loss(u_pred, u_tgt.detach(), reduction="none").mean(dim=1)
225
+ if tgt_mask is not None:
226
+ weights = self.adaptive_loss_weighting(losses, tgt_mask.squeeze(1))
227
+ loss = (weights * losses).sum() / torch.sum(tgt_mask)
228
+ else:
229
+ loss = losses.mean()
230
+
231
+ return loss
convert/src/voxcpm/modules/locenc/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .local_encoder import VoxCPMLocEnc
convert/src/voxcpm/modules/locenc/local_encoder.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from ..minicpm4 import MiniCPMModel, MiniCPM4Config
4
+ from einops import rearrange
5
+
6
+
7
+ class VoxCPMLocEnc(nn.Module):
8
+ def __init__(self, config: MiniCPM4Config, input_dim: int = 64):
9
+ super().__init__()
10
+ self.config = config
11
+ self.special_token = nn.Parameter(torch.randn(1, 1, 1, config.hidden_size))
12
+ self.in_proj = nn.Linear(input_dim, config.hidden_size, bias=True)
13
+
14
+ assert config.vocab_size == 0, "vocab_size must be 0 for local encoder"
15
+ self.encoder = MiniCPMModel(config)
16
+
17
+ def forward(self, x):
18
+ """
19
+ x: [B, T, P, D]
20
+ """
21
+ B, T, P, D = x.shape
22
+
23
+ x = self.in_proj(x)
24
+ special_tokens = self.special_token.expand(B, T, 1, -1)
25
+ x = torch.cat([special_tokens, x], dim=2)
26
+ x = rearrange(x, "b t p c -> (b t) p c")
27
+ outputs, _ = self.encoder(x, is_causal=False)
28
+ cls_output = outputs[:, 0, :]
29
+
30
+ return rearrange(cls_output, "(b t) c -> b t c", b=B)
convert/src/voxcpm/modules/minicpm4/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .config import MiniCPM4Config
2
+ from .model import MiniCPMModel
3
+ from .cache import StaticKVCache
convert/src/voxcpm/modules/minicpm4/cache.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple
2
+ import torch
3
+
4
+
5
+ class StaticKVCache:
6
+ def __init__(
7
+ self,
8
+ num_layers: int,
9
+ num_kv_heads: int,
10
+ dim_kv_head: int,
11
+ batch_size: int,
12
+ device: torch.device,
13
+ dtype: torch.dtype,
14
+ max_length: int = 8192,
15
+ ):
16
+ self.max_length = max_length
17
+ self.num_layers = num_layers
18
+
19
+ self.kv_cache = torch.zeros(
20
+ 2,
21
+ num_layers,
22
+ batch_size,
23
+ num_kv_heads,
24
+ max_length,
25
+ dim_kv_head,
26
+ device=device,
27
+ dtype=dtype,
28
+ )
29
+ self.current_length = 0
30
+
31
+ def get_layer_cache(self, layer_idx: int) -> Tuple[torch.Tensor, torch.Tensor]:
32
+ return self.kv_cache[0, layer_idx], self.kv_cache[1, layer_idx]
33
+
34
+ def step(self) -> int:
35
+ if self.current_length >= self.max_length:
36
+ raise ValueError("KV cache is full")
37
+
38
+ ret = self.current_length
39
+ self.current_length += 1
40
+ return ret
41
+
42
+ def fill_caches(self, kv_caches: List[Tuple[torch.Tensor, torch.Tensor]]):
43
+ self.current_length = kv_caches[0][0].size(2)
44
+ self.kv_cache.zero_()
45
+ for i in range(self.num_layers):
46
+ self.kv_cache[0, i, :, :, : self.current_length, :] = kv_caches[i][0]
47
+ self.kv_cache[1, i, :, :, : self.current_length, :] = kv_caches[i][1]
convert/src/voxcpm/modules/minicpm4/config.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from typing import List
3
+
4
+
5
+ class RopeScalingConfig(BaseModel):
6
+ type: str
7
+ long_factor: List[float]
8
+ short_factor: List[float]
9
+ original_max_position_embeddings: int
10
+
11
+
12
+ class MiniCPM4Config(BaseModel):
13
+ bos_token_id: int
14
+ eos_token_id: int
15
+ hidden_size: int
16
+ intermediate_size: int
17
+ max_position_embeddings: int
18
+ num_attention_heads: int
19
+ num_hidden_layers: int
20
+ num_key_value_heads: int
21
+ rms_norm_eps: float
22
+ rope_scaling: RopeScalingConfig
23
+ vocab_size: int
24
+ use_mup: bool = True
25
+ scale_emb: float
26
+ dim_model_base: int
27
+ scale_depth: float
28
+ rope_theta: float
29
+ kv_channels: int = None
convert/src/voxcpm/modules/minicpm4/model.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .config import MiniCPM4Config
2
+ import torch
3
+ import torch.nn as nn
4
+ from typing import List, Tuple
5
+ import math
6
+ from .cache import StaticKVCache
7
+
8
+
9
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
10
+ old_dtype = hidden.dtype
11
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
12
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
13
+ return hidden * weight
14
+
15
+
16
+ class MiniCPMRMSNorm(nn.Module):
17
+ def __init__(self, hidden_size, eps=1e-6):
18
+ """
19
+ MiniCPMRMSNorm is equivalent to T5LayerNorm
20
+ """
21
+ super().__init__()
22
+ self.weight = nn.Parameter(torch.ones(hidden_size))
23
+ self.variance_epsilon = eps
24
+
25
+ def forward(self, hidden_states):
26
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
27
+
28
+
29
+ def rotate_half(x):
30
+ """Rotates half the hidden dims of the input."""
31
+ x1, x2 = x.chunk(2, dim=-1)
32
+ return torch.cat((-x2, x1), dim=-1)
33
+
34
+
35
+ def apply_rotary_pos_emb(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
36
+ """
37
+ Args:
38
+ q: Tensor(batch_size, num_heads, seq_len, head_dim)
39
+ k: Tensor(batch_size, num_key_value_heads, seq_len, head_dim)
40
+ cos: Tensor(seq_len, head_dim)
41
+ sin: Tensor(seq_len, head_dim)
42
+ Returns:
43
+ Tensor(batch_size, num_heads, seq_len, head_dim), Tensor(batch_size, num_key_value_heads, seq_len, head_dim)
44
+ """
45
+ orig_dtype = q.dtype
46
+ q = q.to(torch.float32)
47
+ k = k.to(torch.float32)
48
+ q_embed = (q * cos) + (rotate_half(q) * sin)
49
+ k_embed = (k * cos) + (rotate_half(k) * sin)
50
+ return q_embed.to(orig_dtype), k_embed.to(orig_dtype)
51
+
52
+
53
+ def scaled_dot_product_attention_gqa_compat(
54
+ query: torch.Tensor,
55
+ key: torch.Tensor,
56
+ value: torch.Tensor,
57
+ *,
58
+ attn_mask: torch.Tensor | None = None,
59
+ is_causal: bool = False,
60
+ enable_gqa: bool = False,
61
+ ) -> torch.Tensor:
62
+ """ONNX-export friendly fallback for scaled_dot_product_attention(enable_gqa=True)."""
63
+ orig_dtype = query.dtype
64
+ query = query.to(torch.float32)
65
+ key = key.to(torch.float32)
66
+ value = value.to(torch.float32)
67
+
68
+ if enable_gqa and query.shape[-3] != key.shape[-3]:
69
+ repeat_factor = query.shape[-3] // key.shape[-3]
70
+ key = key.repeat_interleave(repeat_factor, dim=-3)
71
+ value = value.repeat_interleave(repeat_factor, dim=-3)
72
+
73
+ scale = 1.0 / math.sqrt(query.size(-1))
74
+ attn_scores = torch.matmul(query, key.transpose(-2, -1)) * scale
75
+
76
+ if is_causal:
77
+ q_len = query.size(-2)
78
+ k_len = key.size(-2)
79
+ q_pos = torch.arange(q_len, device=query.device).unsqueeze(-1)
80
+ k_pos = torch.arange(k_len, device=query.device).unsqueeze(0)
81
+ causal_mask = k_pos <= (q_pos + k_len - q_len)
82
+ attn_scores = attn_scores.masked_fill(~causal_mask, torch.finfo(attn_scores.dtype).min)
83
+
84
+ if attn_mask is not None:
85
+ if attn_mask.dtype == torch.bool:
86
+ while attn_mask.ndim < attn_scores.ndim:
87
+ attn_mask = attn_mask.unsqueeze(0)
88
+ attn_scores = attn_scores.masked_fill(~attn_mask, torch.finfo(attn_scores.dtype).min)
89
+ else:
90
+ attn_scores = attn_scores + attn_mask.to(attn_scores.dtype)
91
+
92
+ attn_probs = torch.softmax(attn_scores, dim=-1)
93
+ return torch.matmul(attn_probs, value).to(orig_dtype)
94
+
95
+
96
+ class MiniCPMLongRoPE(nn.Module):
97
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
98
+
99
+ def __init__(self, config: MiniCPM4Config):
100
+ super().__init__()
101
+ self.config = config
102
+ self.dim = config.kv_channels if config.kv_channels else config.hidden_size // config.num_attention_heads
103
+ self.base = config.rope_theta
104
+ self.max_position_embeddings = config.max_position_embeddings
105
+
106
+ self.short_factor = config.rope_scaling.short_factor
107
+ self.long_factor = config.rope_scaling.long_factor
108
+ self.original_max_position_embeddings = config.rope_scaling.original_max_position_embeddings
109
+
110
+ scale = (self.max_position_embeddings / self.original_max_position_embeddings)
111
+ self.scaling_factor = math.sqrt(
112
+ 1 + math.log(scale) / math.log(self.original_max_position_embeddings)
113
+ )
114
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float() / self.dim))
115
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
116
+
117
+ self.max_seq_len_cached = 0
118
+
119
+ self.register_buffer("cos_cached", torch.empty(0), persistent=False)
120
+ self.register_buffer("sin_cached", torch.empty(0), persistent=False)
121
+
122
+ self._set_cos_sin_cache(
123
+ seq_len=self.max_position_embeddings,
124
+ device=self.inv_freq.device,
125
+ dtype=torch.float32
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ """设置cos和sin缓存"""
130
+ self.max_seq_len_cached = seq_len
131
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
132
+
133
+ if seq_len > self.original_max_position_embeddings:
134
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=device)
135
+ else:
136
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=device)
137
+
138
+ freqs = torch.mul(
139
+ torch.outer(t, 1.0 / ext_factors).to(device=device),
140
+ self.inv_freq.to(device=device).to(dtype)
141
+ )
142
+
143
+ # 创建embeddings
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+
146
+ self.cos_cached = emb.cos().to(dtype) * self.scaling_factor
147
+ self.sin_cached = emb.sin().to(dtype) * self.scaling_factor
148
+
149
+ def forward(self, position_ids: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
150
+ """
151
+ Args:
152
+ position_ids: Tensor(seq_len) 或 Tensor(batch_size, seq_len)
153
+ Returns:
154
+ Tensor(seq_len, head_dim), Tensor(seq_len, head_dim)
155
+ """
156
+ cos = self.cos_cached[position_ids]
157
+ sin = self.sin_cached[position_ids]
158
+
159
+ return cos, sin
160
+
161
+
162
+ class MiniCPMAttention(nn.Module):
163
+ def __init__(self, config: MiniCPM4Config, layer_idx: int):
164
+ super().__init__()
165
+ self.config = config
166
+ self.layer_idx = layer_idx
167
+ self.hidden_size = config.hidden_size
168
+ self.num_heads = config.num_attention_heads
169
+ self.head_dim = config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
170
+ self.num_key_value_heads = config.num_key_value_heads
171
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
172
+ self.max_position_embeddings = config.max_position_embeddings
173
+ self.rope_theta = 10000.0
174
+
175
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
176
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
177
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
178
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
179
+
180
+ def forward(
181
+ self,
182
+ hidden_states: torch.Tensor,
183
+ position_emb: Tuple[torch.Tensor, torch.Tensor],
184
+ is_causal: bool,
185
+ ) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
186
+ bsz, q_len, _ = hidden_states.size()
187
+
188
+ query_states = self.q_proj(hidden_states)
189
+ key_states = self.k_proj(hidden_states)
190
+ value_states = self.v_proj(hidden_states)
191
+
192
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
193
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
194
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
195
+
196
+ cos, sin = position_emb
197
+
198
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
199
+
200
+ # ref: https://github.com/pytorch/pytorch/issues/163597
201
+ # there is a bug in MPS for non-contiguous tensors, so we need to make them contiguous
202
+ query_states = query_states.contiguous()
203
+ key_states = key_states.contiguous()
204
+ value_states = value_states.contiguous()
205
+ if torch.onnx.is_in_onnx_export():
206
+ attn_output = scaled_dot_product_attention_gqa_compat(
207
+ query_states,
208
+ key_states,
209
+ value_states,
210
+ is_causal=is_causal,
211
+ enable_gqa=True,
212
+ )
213
+ else:
214
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
215
+ query_states,
216
+ key_states,
217
+ value_states,
218
+ is_causal=is_causal,
219
+ enable_gqa=True,
220
+ )
221
+
222
+ attn_output = attn_output.transpose(1, 2).contiguous()
223
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.head_dim)
224
+
225
+ attn_output = self.o_proj(attn_output)
226
+
227
+ past_key_value = (key_states, value_states)
228
+ return attn_output, past_key_value
229
+
230
+ def forward_step(
231
+ self,
232
+ hidden_states: torch.Tensor,
233
+ position_emb: Tuple[torch.Tensor, torch.Tensor],
234
+ position_id: int,
235
+ kv_cache: Tuple[torch.Tensor, torch.Tensor],
236
+ ) -> torch.Tensor:
237
+ bsz, _ = hidden_states.size()
238
+
239
+ query_states = self.q_proj(hidden_states)
240
+ key_states = self.k_proj(hidden_states)
241
+ value_states = self.v_proj(hidden_states)
242
+
243
+ query_states = query_states.view(bsz, 1, self.num_heads, self.head_dim).transpose(1, 2)
244
+ key_states = key_states.view(bsz, 1, self.num_key_value_heads, self.head_dim).transpose(1, 2)
245
+ value_states = value_states.view(bsz, 1, self.num_key_value_heads, self.head_dim).transpose(1, 2)
246
+
247
+ cos, sin = position_emb
248
+
249
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
250
+
251
+ key_cache, value_cache = kv_cache
252
+
253
+ key_cache[:, :, position_id, :] = key_states
254
+ value_cache[:, :, position_id, :] = value_states
255
+
256
+ attn_mask = torch.arange(key_cache.size(2), device=key_cache.device) <= position_id
257
+
258
+ # ref: https://github.com/pytorch/pytorch/issues/163597
259
+ # there is a bug in MPS for non-contiguous tensors, so we need to make them contiguous
260
+ query_states = query_states.unsqueeze(0)
261
+ key_cache = key_cache.unsqueeze(0)
262
+ value_cache = value_cache.unsqueeze(0)
263
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
264
+ query_states,
265
+ key_cache,
266
+ value_cache,
267
+ attn_mask=attn_mask,
268
+ enable_gqa=True,
269
+ )
270
+
271
+ attn_output = attn_output.transpose(1, 2).contiguous()
272
+ attn_output = attn_output.reshape(bsz, self.num_heads * self.head_dim)
273
+ attn_output = self.o_proj(attn_output)
274
+
275
+ return attn_output
276
+
277
+
278
+ class MiniCPMMLP(nn.Module):
279
+ def __init__(self, config):
280
+ super().__init__()
281
+ self.config = config
282
+ self.hidden_size = config.hidden_size
283
+ self.intermediate_size = config.intermediate_size
284
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
285
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
286
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
287
+ self.act_fn = nn.SiLU()
288
+
289
+ def forward(self, x):
290
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
291
+
292
+
293
+ class MiniCPMDecoderLayer(nn.Module):
294
+ def __init__(self, config: MiniCPM4Config, layer_idx: int):
295
+ super().__init__()
296
+ self.hidden_size = config.hidden_size
297
+ self.self_attn = MiniCPMAttention(config=config, layer_idx=layer_idx)
298
+
299
+ self.mlp = MiniCPMMLP(config)
300
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
301
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
302
+
303
+ self.scale_depth = config.scale_depth
304
+ self.num_hidden_layers = config.num_hidden_layers
305
+ self.use_mup = config.use_mup
306
+
307
+ def forward(
308
+ self,
309
+ hidden_states: torch.Tensor,
310
+ position_emb: Tuple[torch.Tensor, torch.Tensor],
311
+ is_causal: bool,
312
+ ) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
313
+ """
314
+ Args:
315
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
316
+ position_ids (`torch.LongTensor`): position ids of shape `(batch_size, seq_len)`
317
+ is_causal (`bool`): whether the attention mask is causal
318
+ """
319
+ residual = hidden_states
320
+ hidden_states = self.input_layernorm(hidden_states)
321
+ # Self Attention
322
+ hidden_states, present_key_value = self.self_attn(
323
+ hidden_states=hidden_states,
324
+ position_emb=position_emb,
325
+ is_causal=is_causal,
326
+ )
327
+
328
+ if self.use_mup:
329
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
330
+ else:
331
+ hidden_states = residual + hidden_states
332
+
333
+ # Fully Connected
334
+ residual = hidden_states
335
+ hidden_states = self.post_attention_layernorm(hidden_states)
336
+
337
+ hidden_states = self.mlp(hidden_states)
338
+ if self.use_mup:
339
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
340
+ else:
341
+ hidden_states = residual + hidden_states
342
+
343
+ return hidden_states, present_key_value
344
+
345
+ def forward_step(
346
+ self,
347
+ hidden_states: torch.Tensor,
348
+ position_emb: Tuple[torch.Tensor, torch.Tensor],
349
+ position_id: torch.Tensor,
350
+ kv_cache: Tuple[torch.Tensor, torch.Tensor],
351
+ ) -> torch.Tensor:
352
+ residual = hidden_states
353
+ hidden_states = self.input_layernorm(hidden_states)
354
+ # Self Attention
355
+ hidden_states = self.self_attn.forward_step(
356
+ hidden_states=hidden_states,
357
+ position_emb=position_emb,
358
+ position_id=position_id,
359
+ kv_cache=kv_cache,
360
+ )
361
+
362
+ if self.use_mup:
363
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
364
+ else:
365
+ hidden_states = residual + hidden_states
366
+
367
+ # Fully Connected
368
+ residual = hidden_states
369
+ hidden_states = self.post_attention_layernorm(hidden_states)
370
+
371
+ hidden_states = self.mlp(hidden_states)
372
+ if self.use_mup:
373
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
374
+ else:
375
+ hidden_states = residual + hidden_states
376
+
377
+ return hidden_states
378
+
379
+
380
+ class MiniCPMModel(nn.Module):
381
+ """
382
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
383
+
384
+ Args:
385
+ config: MiniCPMConfig
386
+ """
387
+
388
+ def __init__(self, config: MiniCPM4Config):
389
+ super().__init__()
390
+ self.vocab_size = config.vocab_size
391
+ self.config = config
392
+
393
+ if config.vocab_size > 0:
394
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
395
+ else:
396
+ self.embed_tokens = nn.Identity()
397
+
398
+ self.layers = nn.ModuleList(
399
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
400
+ )
401
+
402
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
403
+ self.rope_emb = MiniCPMLongRoPE(config)
404
+
405
+ self.kv_cache = None
406
+
407
+ def forward(
408
+ self,
409
+ inputs_embeds: torch.Tensor,
410
+ is_causal: bool = True,
411
+ ) -> Tuple[torch.Tensor, List[Tuple[torch.Tensor, torch.Tensor]]]:
412
+ """
413
+ Args:
414
+ inputs_embeds: Tensor(batch_size, seq_length, hidden_size)
415
+ is_causal: bool, whether the attention mask is causal
416
+ Returns:
417
+ hidden_states: Tensor(batch_size, seq_length, hidden_size)
418
+ next_decoder_cache: List[(batch_size, num_heads, seq_length, head_dim), (batch_size, num_heads, seq_length, head_dim)]
419
+ """
420
+ position_ids = torch.arange(0, inputs_embeds.size(1), dtype=torch.long, device=inputs_embeds.device)
421
+ position_emb = self.rope_emb(position_ids)
422
+ hidden_states = inputs_embeds
423
+
424
+ next_decoder_cache = []
425
+
426
+ for decoder_layer in self.layers:
427
+
428
+ hidden_states, this_cache = decoder_layer(
429
+ hidden_states,
430
+ position_emb,
431
+ is_causal,
432
+ )
433
+ next_decoder_cache.append(this_cache)
434
+ hidden_states = self.norm(hidden_states)
435
+ return hidden_states, next_decoder_cache
436
+
437
+ def forward_step(
438
+ self,
439
+ inputs_embeds: torch.Tensor,
440
+ position_id: torch.Tensor,
441
+ ) -> torch.Tensor:
442
+ """
443
+ Args:
444
+ inputs_embeds: Tensor(batch_size, hidden_size)
445
+ Returns:
446
+ hidden_states: Tensor(batch_size, hidden_size)
447
+ """
448
+ assert self.kv_cache is not None, "KV cache is not setup"
449
+
450
+ position_emb = self.rope_emb(position_id)
451
+ hidden_states = inputs_embeds
452
+
453
+ for i, decoder_layer in enumerate(self.layers):
454
+ hidden_states = decoder_layer.forward_step(
455
+ hidden_states,
456
+ position_emb,
457
+ position_id,
458
+ self.kv_cache.get_layer_cache(i),
459
+ )
460
+
461
+ hidden_states = self.norm(hidden_states)
462
+ return hidden_states
463
+
464
+ def setup_cache(self, batch_size: int, max_length: int, device, dtype: torch.dtype):
465
+ self.kv_cache = StaticKVCache(
466
+ num_layers=self.config.num_hidden_layers,
467
+ num_kv_heads=self.config.num_key_value_heads,
468
+ dim_kv_head=self.config.hidden_size // self.config.num_attention_heads if self.config.kv_channels is None else self.config.kv_channels,
469
+ batch_size=batch_size,
470
+ device=device,
471
+ dtype=dtype,
472
+ max_length=max_length,
473
+ )
convert/src/voxcpm/training/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Training utilities for VoxCPM fine-tuning.
3
+
4
+ This package mirrors the training mechanics used in the minicpm-audio
5
+ tooling while relying solely on local audio-text datasets managed via
6
+ the HuggingFace ``datasets`` library.
7
+ """
8
+
9
+ from .accelerator import Accelerator
10
+ from .tracker import TrainingTracker
11
+ from .data import (
12
+ load_audio_text_datasets,
13
+ HFVoxCPMDataset,
14
+ build_dataloader,
15
+ BatchProcessor,
16
+ )
17
+ from .state import TrainingState
18
+
19
+ __all__ = [
20
+ "Accelerator",
21
+ "TrainingTracker",
22
+ "HFVoxCPMDataset",
23
+ "BatchProcessor",
24
+ "TrainingState",
25
+ "load_audio_text_datasets",
26
+ "build_dataloader",
27
+ ]
28
+
convert/src/voxcpm/training/accelerator.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import os
5
+ import random
6
+ import typing
7
+
8
+ import numpy as np
9
+ import torch
10
+ import torch.distributed as dist
11
+ import torch.utils.data
12
+ from torch.nn.parallel import DistributedDataParallel
13
+
14
+
15
+ class Accelerator:
16
+ """
17
+ Simplified accelerator that mirrors the behaviour of the minicpm-audio
18
+ training utilities. It initializes a distributed process group when
19
+ ``torchrun`` is used and exposes helpers for AMP, gradient scaling and
20
+ preparing models/dataloaders for DDP.
21
+ """
22
+
23
+ def __init__(self, amp: bool = False, seed: int = 42):
24
+ self.world_size = int(os.getenv("WORLD_SIZE", "1"))
25
+
26
+ if self.world_size > 1 and not dist.is_initialized():
27
+ dist.init_process_group("nccl", init_method="env://")
28
+
29
+ self.rank = dist.get_rank() if dist.is_initialized() else 0
30
+ self.local_rank = int(os.environ.get("LOCAL_RANK", "0"))
31
+ self.amp = amp
32
+
33
+ # Set random seed to ensure model initialization consistency
34
+ self._set_seed(seed)
35
+
36
+ class DummyScaler:
37
+ def step(self, optimizer):
38
+ optimizer.step()
39
+
40
+ def scale(self, loss):
41
+ return loss
42
+
43
+ def unscale_(self, optimizer):
44
+ return optimizer
45
+
46
+ def update(self):
47
+ pass
48
+
49
+ self.scaler = torch.amp.GradScaler("cuda") if (amp and torch.cuda.is_available()) else DummyScaler()
50
+ self.device_ctx = (
51
+ torch.cuda.device(self.local_rank) if torch.cuda.is_available() else None
52
+ )
53
+ self._ddp_model = None # For no_sync support
54
+
55
+ def _set_seed(self, seed: int):
56
+ """Set random seed to ensure model initialization consistency across multiple GPUs"""
57
+ torch.manual_seed(seed)
58
+ np.random.seed(seed)
59
+ random.seed(seed)
60
+ if torch.cuda.is_available():
61
+ torch.cuda.manual_seed_all(seed)
62
+
63
+ def __enter__(self):
64
+ if self.device_ctx is not None:
65
+ self.device_ctx.__enter__()
66
+ return self
67
+
68
+ def __exit__(self, exc_type, exc_value, traceback):
69
+ if self.device_ctx is not None:
70
+ self.device_ctx.__exit__(exc_type, exc_value, traceback)
71
+
72
+ def barrier(self):
73
+ """Synchronize all processes"""
74
+ if dist.is_initialized():
75
+ dist.barrier()
76
+
77
+ def all_reduce(self, tensor: torch.Tensor, op=dist.ReduceOp.AVG):
78
+ """All-reduce tensor across processes"""
79
+ if dist.is_initialized():
80
+ dist.all_reduce(tensor, op=op)
81
+ return tensor
82
+
83
+ # ------------------------------------------------------------------ #
84
+ # Model helpers
85
+ # ------------------------------------------------------------------ #
86
+ def prepare_model(self, model: torch.nn.Module, **kwargs):
87
+ if hasattr(model, 'device'): # make sure the matrix will be moved to the correct device
88
+ model.device = self.device
89
+ model = model.to(self.device)
90
+ if self.world_size > 1:
91
+ model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
92
+ model = DistributedDataParallel(model, device_ids=[self.local_rank], **kwargs)
93
+ self._ddp_model = model # Save DDP model reference for no_sync support
94
+ return model
95
+
96
+ @contextlib.contextmanager
97
+ def no_sync(self):
98
+ """
99
+ Context manager to skip gradient synchronization during gradient accumulation.
100
+ Only used outside the last micro-batch.
101
+ """
102
+ if self._ddp_model is not None:
103
+ with self._ddp_model.no_sync():
104
+ yield
105
+ else:
106
+ yield
107
+
108
+ @property
109
+ def device(self):
110
+ if torch.cuda.is_available():
111
+ return torch.device("cuda", self.local_rank)
112
+ if torch.backends.mps.is_available():
113
+ return torch.device("mps")
114
+ return torch.device("cpu")
115
+
116
+ # ------------------------------------------------------------------ #
117
+ # AMP helpers
118
+ # ------------------------------------------------------------------ #
119
+ def autocast(self, *args, **kwargs):
120
+ return torch.amp.autocast("cuda", enabled=self.amp, *args, **kwargs)
121
+
122
+ def backward(self, loss: torch.Tensor):
123
+ self.scaler.scale(loss).backward()
124
+
125
+ def step(self, optimizer: torch.optim.Optimizer):
126
+ self.scaler.step(optimizer)
127
+
128
+ def update(self):
129
+ self.scaler.update()
130
+
131
+ # ------------------------------------------------------------------ #
132
+ # Data helpers
133
+ # ------------------------------------------------------------------ #
134
+ def prepare_dataloader(
135
+ self,
136
+ dataset: typing.Iterable,
137
+ *,
138
+ batch_size: int,
139
+ num_workers: int = 0,
140
+ shuffle: bool = True,
141
+ collate_fn=None,
142
+ drop_last: bool = False,
143
+ ) -> torch.utils.data.DataLoader:
144
+ if self.world_size > 1:
145
+ sampler = torch.utils.data.distributed.DistributedSampler(
146
+ dataset, num_replicas=self.world_size, rank=self.rank, shuffle=shuffle
147
+ )
148
+ shuffle = False
149
+ else:
150
+ sampler = None
151
+
152
+ return torch.utils.data.DataLoader(
153
+ dataset,
154
+ batch_size=batch_size,
155
+ shuffle=shuffle if sampler is None else False,
156
+ sampler=sampler,
157
+ num_workers=num_workers,
158
+ collate_fn=collate_fn,
159
+ drop_last=drop_last,
160
+ pin_memory=True,
161
+ )
162
+
163
+ @staticmethod
164
+ def unwrap(model: torch.nn.Module) -> torch.nn.Module:
165
+ return model.module if hasattr(model, "module") else model
166
+
convert/src/voxcpm/training/config.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argbind
4
+ import yaml
5
+ from pathlib import Path
6
+ from typing import Dict, Any
7
+
8
+
9
+ def load_yaml_config(path: str | Path) -> Dict[str, Any]:
10
+ """
11
+ Load a YAML configuration file into a dictionary suitable for argbind.
12
+ """
13
+ path = Path(path)
14
+ with path.open("r", encoding="utf-8") as f:
15
+ data = yaml.safe_load(f)
16
+ if not isinstance(data, dict):
17
+ raise ValueError(f"Configuration file {path} must contain a top-level mapping.")
18
+ return data
19
+
20
+
21
+ def parse_args_with_config(config_path: str | Path | None = None):
22
+ """
23
+ Helper to unify CLI arguments and YAML configuration.
24
+
25
+ Usage mirrors minicpm-audio:
26
+ args = parse_args_with_config("conf/voxcpm/finetune.yml")
27
+ with argbind.scope(args):
28
+ ...
29
+ """
30
+ cli_args = argbind.parse_args()
31
+ if config_path is None:
32
+ return cli_args
33
+
34
+ yaml_args = load_yaml_config(config_path)
35
+ with argbind.scope(cli_args):
36
+ yaml_args = argbind.parse_args(yaml_args=yaml_args, argv=[])
37
+ cli_args.update(yaml_args)
38
+ return cli_args
39
+
40
+
convert/src/voxcpm/training/data.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Dict, List, Optional, Tuple
4
+
5
+ import argbind
6
+ import torch
7
+ from datasets import Audio, Dataset, DatasetDict, load_dataset
8
+ from torch.utils.data import Dataset as TorchDataset
9
+
10
+ from ..model.voxcpm import VoxCPMConfig
11
+ from ..modules.audiovae import AudioVAE
12
+ from .packers import AudioFeatureProcessingPacker
13
+
14
+
15
+ DEFAULT_TEXT_COLUMN = "text"
16
+ DEFAULT_AUDIO_COLUMN = "audio"
17
+ DEFAULT_ID_COLUMN = "dataset_id"
18
+
19
+
20
+ @argbind.bind()
21
+ def load_audio_text_datasets(
22
+ train_manifest: str,
23
+ val_manifest: str = "",
24
+ text_column: str = DEFAULT_TEXT_COLUMN,
25
+ audio_column: str = DEFAULT_AUDIO_COLUMN,
26
+ dataset_id_column: str = DEFAULT_ID_COLUMN,
27
+ sample_rate: int = 16_000,
28
+ num_proc: int = 1,
29
+ ) -> Tuple[Dataset, Optional[Dataset]]:
30
+ data_files = {"train": train_manifest}
31
+ if val_manifest:
32
+ data_files["validation"] = val_manifest
33
+
34
+ dataset_dict: DatasetDict = load_dataset("json", data_files=data_files)
35
+
36
+ def prepare(ds: Dataset) -> Dataset:
37
+ if audio_column not in ds.column_names:
38
+ raise ValueError(f"Expected '{audio_column}' column in manifest.")
39
+ # We cast to Audio to ensure proper handling during training,
40
+ # but for length calculation we might need raw path or duration if available.
41
+ # HF datasets usually don't compute duration automatically for 'Audio' column.
42
+ ds = ds.cast_column(audio_column, Audio(sampling_rate=sample_rate))
43
+ if audio_column != DEFAULT_AUDIO_COLUMN:
44
+ ds = ds.rename_column(audio_column, DEFAULT_AUDIO_COLUMN)
45
+ if text_column != DEFAULT_TEXT_COLUMN:
46
+ ds = ds.rename_column(text_column, DEFAULT_TEXT_COLUMN)
47
+ if dataset_id_column and dataset_id_column in ds.column_names:
48
+ if dataset_id_column != DEFAULT_ID_COLUMN:
49
+ ds = ds.rename_column(dataset_id_column, DEFAULT_ID_COLUMN)
50
+ else:
51
+ ds = ds.add_column(DEFAULT_ID_COLUMN, [0] * len(ds))
52
+ return ds
53
+
54
+ train_ds = prepare(dataset_dict["train"])
55
+ val_ds = prepare(dataset_dict["validation"]) if "validation" in dataset_dict else None
56
+ return train_ds, val_ds
57
+
58
+
59
+ def compute_sample_lengths(
60
+ ds: Dataset,
61
+ audio_vae_fps: int = 25,
62
+ patch_size: int = 1,
63
+ ) -> List[int]:
64
+ """
65
+ 预估每个样本经过 packer 之后的大致序列长度(text+audio),用于过滤超长样本。
66
+
67
+ 逻辑与 AudioFeatureProcessingPacker / AudioVAE 一致:
68
+ - 文本长度: len(text_ids)
69
+ - 音频长度:
70
+ duration(s) * audio_vae_fps -> 近似 VAE 帧数 t_vae
71
+ t_seq = ceil(t_vae / patch_size)
72
+ - 序列总长约为: text_len + t_seq + 2
73
+
74
+ Optimized: Use batch column access instead of iterating item by item.
75
+ """
76
+ # Batch access columns - much faster than per-item access
77
+ text_ids_list = ds["text_ids"]
78
+ text_lens = [len(t) for t in text_ids_list]
79
+
80
+ has_duration = "duration" in ds.column_names
81
+ if has_duration:
82
+ durations = ds["duration"]
83
+ else:
84
+ # Fallback: need to compute from audio (slow, but unavoidable without duration column)
85
+ durations = []
86
+ for i in range(len(ds)):
87
+ audio = ds[i][DEFAULT_AUDIO_COLUMN]
88
+ durations.append(len(audio["array"]) / float(audio["sampling_rate"]))
89
+
90
+ # Vectorized length computation
91
+ lengths = []
92
+ for text_len, duration in zip(text_lens, durations):
93
+ t_vae = math.ceil(float(duration) * audio_vae_fps)
94
+ t_seq = math.ceil(t_vae / patch_size)
95
+ total_len = text_len + t_seq + 2
96
+ lengths.append(total_len)
97
+
98
+ return lengths
99
+
100
+
101
+ class HFVoxCPMDataset(TorchDataset):
102
+ """
103
+ Thin wrapper around a tokenized HuggingFace dataset that returns
104
+ PyTorch-friendly samples.
105
+ """
106
+
107
+ def __init__(self, dataset: Dataset):
108
+ self.dataset = dataset
109
+
110
+ def __len__(self):
111
+ return len(self.dataset)
112
+
113
+ def __getitem__(self, idx: int):
114
+ item = self.dataset[idx]
115
+ audio = item[DEFAULT_AUDIO_COLUMN]
116
+ return {
117
+ "text_ids": item["text_ids"],
118
+ "audio_array": audio["array"],
119
+ "audio_sampling_rate": audio["sampling_rate"],
120
+ "dataset_id": item.get(DEFAULT_ID_COLUMN, 0),
121
+ "is_prompt": item.get("is_prompt", False),
122
+ }
123
+
124
+ @staticmethod
125
+ def pad_sequences(seqs: List[torch.Tensor], pad_value: float):
126
+ if not seqs:
127
+ return torch.empty(0)
128
+ max_len = max(seq.shape[0] for seq in seqs)
129
+ padded = []
130
+ for seq in seqs:
131
+ if seq.shape[0] < max_len:
132
+ pad_width = (0, max_len - seq.shape[0])
133
+ seq = torch.nn.functional.pad(seq, pad_width, value=pad_value)
134
+ padded.append(seq)
135
+ return torch.stack(padded)
136
+
137
+ @classmethod
138
+ def collate_fn(cls, batch: List[Dict]):
139
+ text_tensors = [torch.tensor(sample["text_ids"], dtype=torch.int32) for sample in batch]
140
+ audio_tensors = [torch.tensor(sample["audio_array"], dtype=torch.float32) for sample in batch]
141
+ dataset_ids = torch.tensor([sample["dataset_id"] for sample in batch], dtype=torch.int32)
142
+ is_prompts = [bool(sample.get("is_prompt", False)) for sample in batch]
143
+
144
+ text_padded = cls.pad_sequences(text_tensors, pad_value=-100)
145
+ audio_padded = cls.pad_sequences(audio_tensors, pad_value=-100.0)
146
+ task_ids = torch.ones(text_padded.size(0), dtype=torch.int32)
147
+
148
+ return {
149
+ "text_tokens": text_padded,
150
+ "audio_tokens": audio_padded,
151
+ "task_ids": task_ids,
152
+ "dataset_ids": dataset_ids,
153
+ "is_prompts": is_prompts,
154
+ }
155
+
156
+
157
+ class BatchProcessor:
158
+ """
159
+ Wraps ``AudioFeatureProcessingPacker`` so the training loop can mirror
160
+ the minicpm-audio mechanics.
161
+ """
162
+
163
+ def __init__(
164
+ self,
165
+ *,
166
+ config: VoxCPMConfig,
167
+ audio_vae: AudioVAE,
168
+ dataset_cnt: int,
169
+ device: torch.device,
170
+ ):
171
+ self.device = device
172
+ self.dataset_cnt = dataset_cnt
173
+ self.audio_vae = audio_vae
174
+ self.audio_vae.to(device)
175
+ self.packer = AudioFeatureProcessingPacker(
176
+ dataset_cnt=dataset_cnt,
177
+ max_len=config.max_length,
178
+ patch_size=config.patch_size,
179
+ feat_dim=config.feat_dim,
180
+ audio_vae=self.audio_vae,
181
+ )
182
+
183
+ def __call__(self, batch: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
184
+ audio_tokens = batch["audio_tokens"].to(self.device)
185
+ text_tokens = batch["text_tokens"].to(self.device)
186
+ task_ids = batch["task_ids"].to(self.device)
187
+ dataset_ids = batch["dataset_ids"].to(self.device)
188
+
189
+ packed = self.packer(
190
+ audio_tokens=audio_tokens,
191
+ text_tokens=text_tokens,
192
+ task_ids=task_ids,
193
+ dataset_ids=dataset_ids,
194
+ is_prompts=batch["is_prompts"],
195
+ )
196
+ return packed
197
+
198
+
199
+ def build_dataloader(
200
+ hf_dataset: Dataset,
201
+ *,
202
+ accelerator,
203
+ batch_size: int,
204
+ num_workers: int,
205
+ drop_last: bool = False,
206
+ ) -> torch.utils.data.DataLoader:
207
+ torch_dataset = HFVoxCPMDataset(hf_dataset)
208
+ # Standard padding-based batching; Accelerator will attach DistributedSampler if needed.
209
+ return accelerator.prepare_dataloader(
210
+ torch_dataset,
211
+ batch_size=batch_size,
212
+ num_workers=num_workers,
213
+ shuffle=True,
214
+ collate_fn=HFVoxCPMDataset.collate_fn,
215
+ drop_last=drop_last,
216
+ )
convert/src/voxcpm/training/packers.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from typing import Dict, List, Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from einops import rearrange
7
+
8
+
9
+ class AudioFeatureProcessingPacker:
10
+ """
11
+ Adapted from the minicpm-audio training utilities. It converts raw text and
12
+ audio tokens into the packed multimodal representation required by VoxCPM.
13
+ """
14
+
15
+ def __init__(self, dataset_cnt: int, max_len: int, patch_size: int, feat_dim: int, audio_vae: nn.Module):
16
+ self.audio_start_id = 101
17
+ self.audio_end_id = 102
18
+ # unused now
19
+ self.audio_prompt_start_id = 103
20
+ self.audio_prompt_end_id = 104
21
+ self.text_eos_token_id = 2
22
+
23
+ self.patch_size = patch_size
24
+ self.patch_len = audio_vae.hop_length * self.patch_size
25
+ self.feat_dim = feat_dim
26
+ self.dataset_cnt = max(dataset_cnt, 1)
27
+ self.max_len = max_len
28
+
29
+ self.audio_vae = audio_vae
30
+
31
+ self.process_functions = {"tts": self.process_tts_data}
32
+ self.task_id_map = {"tts": 1}
33
+ self.id_to_task = {idx: usage for usage, idx in self.task_id_map.items()}
34
+
35
+ # ------------------------------------------------------------------ #
36
+ # Helpers
37
+ # ------------------------------------------------------------------ #
38
+ @staticmethod
39
+ def _first_pad_position(tokens: torch.Tensor):
40
+ positions = (tokens == -100).nonzero(as_tuple=True)
41
+ if positions[0].numel() == 0:
42
+ return None
43
+ return int(positions[0][0])
44
+
45
+ def unpad_text_tokens(self, tokens: torch.Tensor):
46
+ pad_pos = self._first_pad_position(tokens)
47
+ return tokens if pad_pos is None else tokens[:pad_pos]
48
+
49
+ def unpad_audio_tokens(self, tokens: torch.Tensor):
50
+ pad_pos = self._first_pad_position(tokens)
51
+ return tokens if pad_pos is None else tokens[:pad_pos]
52
+
53
+ def encode_audio(self, wav: torch.Tensor):
54
+ """
55
+ Encode raw waveform into latent features using AudioVAE.
56
+
57
+ AudioVAE.encode expects shape [B, 1, T'] and returns [B, D, T].
58
+ We then transpose to [B, T, D] to match downstream expectations.
59
+ """
60
+ wav = wav.unsqueeze(0) # [1, T]
61
+ wav = wav.unsqueeze(1) # [1, 1, T]
62
+ wav_len = wav.size(-1)
63
+ if wav_len % self.patch_len != 0:
64
+ padding_size = self.patch_len - wav_len % self.patch_len
65
+ wav = torch.nn.functional.pad(wav, (0, padding_size))
66
+
67
+ with torch.no_grad():
68
+ z = self.audio_vae.encode(wav, self.audio_vae.sample_rate) # [1, D, T']
69
+ feat = z.transpose(1, 2) # [1, T', D]
70
+ return feat
71
+
72
+ # ------------------------------------------------------------------ #
73
+ # Main entry point
74
+ # ------------------------------------------------------------------ #
75
+ def __call__(
76
+ self,
77
+ audio_tokens: torch.Tensor,
78
+ text_tokens: torch.Tensor,
79
+ task_ids: torch.Tensor,
80
+ dataset_ids: torch.Tensor,
81
+ is_prompts: List[bool],
82
+ ) -> Dict[str, torch.Tensor]:
83
+ """
84
+ Padding-based batching: each sample in the input batch is processed
85
+ independently and then padded to a common length (capped by ``max_len``).
86
+ The result tensors all have shape [B, T, ...].
87
+ """
88
+ device = audio_tokens.device
89
+ max_dataset_id = int(dataset_ids.max().item()) if dataset_ids.numel() > 0 else -1
90
+ dataset_cnt = max(self.dataset_cnt, max_dataset_id + 1)
91
+
92
+ text_tokens_list: List[torch.Tensor] = []
93
+ audio_feats_list: List[torch.Tensor] = []
94
+ text_mask_list: List[torch.Tensor] = []
95
+ audio_mask_list: List[torch.Tensor] = []
96
+ loss_mask_list: List[torch.Tensor] = []
97
+ labels_list: List[torch.Tensor] = []
98
+ audio_task_ids_list: List[torch.Tensor] = []
99
+ audio_dataset_ids_list: List[torch.Tensor] = []
100
+ lengths: List[int] = []
101
+
102
+ audio_duration_consumed = torch.zeros(dataset_cnt, dtype=torch.float32, device=device)
103
+ text_token_consumed = torch.zeros(dataset_cnt, dtype=torch.float32, device=device)
104
+
105
+ for audio_token, text_token, task_id, dataset_idx, is_prompt in zip(
106
+ audio_tokens, text_tokens, task_ids.tolist(), dataset_ids.tolist(), is_prompts
107
+ ):
108
+ unpad_audio_token = self.unpad_audio_tokens(audio_token).to(torch.float32)
109
+ unpad_text_token = self.unpad_text_tokens(text_token)
110
+ usage = self.id_to_task[task_id]
111
+
112
+ (
113
+ packed_text,
114
+ audio_feat,
115
+ text_mask,
116
+ audio_mask,
117
+ loss_mask,
118
+ labels,
119
+ audio_duration,
120
+ text_token_count,
121
+ ) = self.process_functions[usage](unpad_audio_token, unpad_text_token, is_prompt)
122
+
123
+ audio_duration_consumed[dataset_idx] += audio_duration
124
+ text_token_consumed[dataset_idx] += text_token_count
125
+
126
+ audio_task_id = torch.zeros_like(audio_mask)
127
+ audio_task_id[audio_mask == 1] = self.task_id_map[usage]
128
+
129
+ audio_dataset_id = torch.zeros_like(audio_mask)
130
+ audio_dataset_id[audio_mask == 1] = dataset_idx + 1
131
+
132
+ text_tokens_list.append(packed_text)
133
+ text_mask_list.append(text_mask)
134
+ audio_feats_list.append(audio_feat)
135
+ audio_mask_list.append(audio_mask)
136
+ loss_mask_list.append(loss_mask)
137
+ labels_list.append(labels)
138
+ audio_task_ids_list.append(audio_task_id)
139
+ audio_dataset_ids_list.append(audio_dataset_id)
140
+ lengths.append(packed_text.shape[0])
141
+
142
+ # Determine padded length per batch (cap by self.max_len)
143
+ if lengths:
144
+ max_len = min(self.max_len, max(lengths))
145
+ else:
146
+ max_len = self.max_len
147
+
148
+ def pad_1d(x: torch.Tensor, pad_value: int = 0) -> torch.Tensor:
149
+ if x.size(0) >= max_len:
150
+ return x[: max_len]
151
+ pad = torch.full((max_len - x.size(0),), pad_value, dtype=x.dtype, device=x.device)
152
+ return torch.cat([x, pad], dim=0)
153
+
154
+ def pad_3d(x: torch.Tensor) -> torch.Tensor:
155
+ # x: [T, P, D]
156
+ if x.size(0) >= max_len:
157
+ return x[: max_len]
158
+ pad = torch.zeros(
159
+ (max_len - x.size(0),) + x.shape[1:], dtype=x.dtype, device=x.device
160
+ )
161
+ return torch.cat([x, pad], dim=0)
162
+ if lengths:
163
+ text_tokens_batch = torch.stack([pad_1d(t, pad_value=0) for t in text_tokens_list], dim=0)
164
+ text_mask_batch = torch.stack([pad_1d(m, pad_value=0) for m in text_mask_list], dim=0)
165
+ audio_feats_batch = torch.stack([pad_3d(f) for f in audio_feats_list], dim=0)
166
+ audio_mask_batch = torch.stack([pad_1d(m, pad_value=0) for m in audio_mask_list], dim=0)
167
+ loss_mask_batch = torch.stack([pad_1d(m, pad_value=0) for m in loss_mask_list], dim=0)
168
+ labels_batch = torch.stack([pad_1d(l, pad_value=0) for l in labels_list], dim=0)
169
+ audio_task_ids_batch = torch.stack(
170
+ [pad_1d(t, pad_value=0) for t in audio_task_ids_list], dim=0
171
+ )
172
+ audio_dataset_ids_batch = torch.stack(
173
+ [pad_1d(d, pad_value=0) for d in audio_dataset_ids_list], dim=0
174
+ )
175
+
176
+ # Position ids: [B, T], simple 0..L_i-1 then padded with 0
177
+ position_ids_list = []
178
+ for L in lengths:
179
+ L_clip = min(L, max_len)
180
+ pos = torch.arange(0, L_clip, device=device)
181
+ if L_clip < max_len:
182
+ pad = torch.zeros(max_len - L_clip, dtype=pos.dtype, device=device)
183
+ pos = torch.cat([pos, pad], dim=0)
184
+ position_ids_list.append(pos)
185
+ position_ids = torch.stack(position_ids_list, dim=0)
186
+ else:
187
+ # Empty batch fallback (shouldn't really happen)
188
+ text_tokens_batch = torch.zeros((0, self.max_len), dtype=torch.int32, device=device)
189
+ text_mask_batch = torch.zeros_like(text_tokens_batch)
190
+ audio_feats_batch = torch.zeros(
191
+ (0, self.max_len, self.patch_size, self.feat_dim), dtype=torch.float32, device=device
192
+ )
193
+ audio_mask_batch = torch.zeros_like(text_tokens_batch)
194
+ loss_mask_batch = torch.zeros_like(text_tokens_batch)
195
+ labels_batch = torch.zeros_like(text_tokens_batch)
196
+ audio_task_ids_batch = torch.zeros_like(text_tokens_batch)
197
+ audio_dataset_ids_batch = torch.zeros_like(text_tokens_batch)
198
+ position_ids = torch.zeros_like(text_tokens_batch)
199
+
200
+ audio_duration_consumed = audio_duration_consumed.to(torch.long)
201
+ text_token_consumed = text_token_consumed.to(torch.long)
202
+
203
+ return {
204
+ "text_tokens": text_tokens_batch,
205
+ "audio_feats": audio_feats_batch,
206
+ "text_mask": text_mask_batch,
207
+ "audio_mask": audio_mask_batch,
208
+ "loss_mask": loss_mask_batch,
209
+ "position_ids": position_ids,
210
+ "labels": labels_batch,
211
+ "audio_task_ids": audio_task_ids_batch,
212
+ "audio_dataset_ids": audio_dataset_ids_batch,
213
+ "audio_duration_consumed": audio_duration_consumed,
214
+ "text_token_consumed": text_token_consumed,
215
+ }
216
+
217
+ # ------------------------------------------------------------------ #
218
+ # Feature extraction helpers
219
+ # ------------------------------------------------------------------ #
220
+ def extract_audio_feats(self, audio_data: torch.Tensor):
221
+ audio_feats = self.encode_audio(audio_data)
222
+ if audio_feats.size(1) % self.patch_size != 0:
223
+ audio_feats_ = audio_feats.transpose(1, 2)
224
+ padding = nn.functional.pad(audio_feats_, (0, self.patch_size - audio_feats.size(1) % self.patch_size))
225
+ audio_feats = padding.transpose(1, 2)
226
+
227
+ audio_duration = audio_feats.size(1) / 25
228
+ audio_feats = rearrange(audio_feats, "b (t p) c -> b t p c", p=self.patch_size)
229
+ return audio_feats, audio_duration
230
+
231
+ def process_tts_data(self, audio_token: torch.Tensor, text_token: torch.Tensor, is_prompt: bool = False):
232
+ text_token_info = torch.cat(
233
+ [
234
+ text_token,
235
+ torch.tensor(
236
+ [self.audio_prompt_start_id if is_prompt else self.audio_start_id],
237
+ dtype=torch.int32,
238
+ device=text_token.device,
239
+ ),
240
+ ],
241
+ dim=-1,
242
+ )
243
+ text_token_count = len(text_token)
244
+ text_length = text_token_info.shape[0]
245
+ audio_feat_info, audio_duration = self.extract_audio_feats(audio_token)
246
+ audio_feat_info = audio_feat_info.squeeze(0)
247
+ audio_length = audio_feat_info.shape[0]
248
+
249
+ text_pad_token = torch.zeros(audio_length, dtype=torch.int32, device=text_token.device)
250
+ text_token_info = torch.cat(
251
+ [
252
+ text_token_info,
253
+ text_pad_token,
254
+ torch.tensor(
255
+ [self.audio_prompt_end_id if is_prompt else self.audio_end_id],
256
+ dtype=torch.int32,
257
+ device=text_token.device,
258
+ ),
259
+ ]
260
+ )
261
+ audio_pad_feat = torch.zeros(
262
+ (text_length, self.patch_size, audio_feat_info.size(-1)),
263
+ dtype=torch.float32,
264
+ device=text_token.device,
265
+ )
266
+ audio_feat_info = torch.cat([audio_pad_feat, audio_feat_info, audio_pad_feat[0:1, ...]], dim=0)
267
+
268
+ text_mask = torch.cat([torch.ones(text_length), torch.zeros(audio_length), torch.ones(1)]).type(torch.int32).to(
269
+ text_token.device
270
+ )
271
+ audio_mask = torch.cat([torch.zeros(text_length), torch.ones(audio_length), torch.zeros(1)]).type(
272
+ torch.int32
273
+ ).to(text_token.device)
274
+ loss_mask = torch.cat([torch.zeros(text_length), torch.zeros(audio_length) if is_prompt else torch.ones(audio_length), torch.zeros(1)]).type(torch.int32).to(text_token.device)
275
+
276
+ labels = torch.zeros(text_length + audio_length + 1).type(torch.int32).to(text_token.device)
277
+ labels[-2] = 1
278
+
279
+ return (
280
+ text_token_info,
281
+ audio_feat_info,
282
+ text_mask,
283
+ audio_mask,
284
+ loss_mask,
285
+ labels,
286
+ audio_duration,
287
+ text_token_count,
288
+ )
289
+
convert/src/voxcpm/training/state.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass
7
+ class TrainingState:
8
+ """
9
+ Container that mirrors the object returned in the minicpm-audio training
10
+ loop. It holds persistent references to the model, optimizer, scheduler,
11
+ dataloaders and tracker.
12
+ """
13
+
14
+ generator: object
15
+ optimizer: object
16
+ scheduler: object
17
+ train_loader: object
18
+ val_loader: object
19
+ tracker: object
20
+ batch_processor: object
21
+
convert/src/voxcpm/training/tracker.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import sys
5
+ import time
6
+ from pathlib import Path
7
+ from typing import Dict, Optional
8
+
9
+
10
+ class TrainingTracker:
11
+ """
12
+ Lightweight tracker inspired by the minimcpm-audio training workflow.
13
+
14
+ It keeps track of the current global step, prints rank-aware messages,
15
+ optionally writes to TensorBoard via a provided writer, and stores progress
16
+ in a logfile for later inspection.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ *,
22
+ writer=None,
23
+ log_file: Optional[str] = None,
24
+ rank: int = 0,
25
+ ):
26
+ self.writer = writer
27
+ self.log_file = Path(log_file) if log_file else None
28
+ if self.log_file:
29
+ self.log_file.parent.mkdir(parents=True, exist_ok=True)
30
+ self.rank = rank
31
+ self.step = 0
32
+ # Record the time of the last log to calculate the interval
33
+ self._last_log_time: float | None = None
34
+
35
+ # ------------------------------------------------------------------ #
36
+ # Logging helpers
37
+ # ------------------------------------------------------------------ #
38
+ def print(self, message: str):
39
+ if self.rank == 0:
40
+ print(message, flush=True, file=sys.stderr)
41
+ if self.log_file:
42
+ with self.log_file.open("a", encoding="utf-8") as f:
43
+ f.write(message + "\n")
44
+
45
+ def log_metrics(self, metrics: Dict[str, float], split: str):
46
+ if self.rank == 0:
47
+ now = time.time()
48
+ dt_str = ""
49
+ if self._last_log_time is not None:
50
+ dt = now - self._last_log_time
51
+ dt_str = f", log interval: {dt:.2f}s"
52
+ self._last_log_time = now
53
+
54
+ formatted = ", ".join(f"{k}: {v:.6f}" for k, v in metrics.items())
55
+ self.print(f"[{split}] step {self.step}: {formatted}{dt_str}")
56
+ if self.writer is not None:
57
+ for key, value in metrics.items():
58
+ if isinstance(value, (int, float)):
59
+ self.writer.add_scalar(f"{split}/{key}", value, self.step)
60
+
61
+ def done(self, split: str, message: str):
62
+ self.print(f"[{split}] {message}")
63
+
64
+ # ------------------------------------------------------------------ #
65
+ # State dict
66
+ # ------------------------------------------------------------------ #
67
+ def state_dict(self):
68
+ return {"step": self.step}
69
+
70
+ def load_state_dict(self, state):
71
+ self.step = int(state.get("step", 0))
72
+
73
+ # ------------------------------------------------------------------ #
74
+ # Context manager compatibility (for parity with minicpm-audio code)
75
+ # ------------------------------------------------------------------ #
76
+ @contextlib.contextmanager
77
+ def live(self):
78
+ yield
79
+
convert/src/voxcpm/utils/text_normalize.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # some functions are copied from https://github.com/FunAudioLLM/CosyVoice/blob/main/cosyvoice/utils/frontend_utils.py
2
+ import re
3
+ import regex
4
+ import inflect
5
+ from functools import partial
6
+ from wetext import Normalizer
7
+
8
+ chinese_char_pattern = re.compile(r'[\u4e00-\u9fff]+')
9
+
10
+ # whether contain chinese character
11
+ def contains_chinese(text):
12
+ return bool(chinese_char_pattern.search(text))
13
+
14
+
15
+ # replace special symbol
16
+ def replace_corner_mark(text):
17
+ text = text.replace('²', '平方')
18
+ text = text.replace('³', '立方')
19
+ text = text.replace('√', '根号')
20
+ text = text.replace('≈', '约等于')
21
+ text = text.replace('<', '小于')
22
+ return text
23
+
24
+
25
+ # remove meaningless symbol
26
+ def remove_bracket(text):
27
+ text = text.replace('(', ' ').replace(')', ' ')
28
+ text = text.replace('【', ' ').replace('】', ' ')
29
+ text = text.replace('`', '').replace('`', '')
30
+ text = text.replace("——", " ")
31
+ return text
32
+
33
+
34
+ # spell Arabic numerals
35
+ def spell_out_number(text: str, inflect_parser):
36
+ new_text = []
37
+ st = None
38
+ for i, c in enumerate(text):
39
+ if not c.isdigit():
40
+ if st is not None:
41
+ num_str = inflect_parser.number_to_words(text[st: i])
42
+ new_text.append(num_str)
43
+ st = None
44
+ new_text.append(c)
45
+ else:
46
+ if st is None:
47
+ st = i
48
+ if st is not None and st < len(text):
49
+ num_str = inflect_parser.number_to_words(text[st:])
50
+ new_text.append(num_str)
51
+ return ''.join(new_text)
52
+
53
+
54
+ # split paragrah logic:
55
+ # 1. per sentence max len token_max_n, min len token_min_n, merge if last sentence len less than merge_len
56
+ # 2. cal sentence len according to lang
57
+ # 3. split sentence according to puncatation
58
+ def split_paragraph(text: str, tokenize, lang="zh", token_max_n=80, token_min_n=60, merge_len=20, comma_split=False):
59
+ def calc_utt_length(_text: str):
60
+ if lang == "zh":
61
+ return len(_text)
62
+ else:
63
+ return len(tokenize(_text))
64
+
65
+ def should_merge(_text: str):
66
+ if lang == "zh":
67
+ return len(_text) < merge_len
68
+ else:
69
+ return len(tokenize(_text)) < merge_len
70
+
71
+ if lang == "zh":
72
+ pounc = ['。', '?', '!', ';', ':', '、', '.', '?', '!', ';']
73
+ else:
74
+ pounc = ['.', '?', '!', ';', ':']
75
+ if comma_split:
76
+ pounc.extend([',', ','])
77
+ st = 0
78
+ utts = []
79
+ for i, c in enumerate(text):
80
+ if c in pounc:
81
+ if len(text[st: i]) > 0:
82
+ utts.append(text[st: i] + c)
83
+ if i + 1 < len(text) and text[i + 1] in ['"', '”']:
84
+ tmp = utts.pop(-1)
85
+ utts.append(tmp + text[i + 1])
86
+ st = i + 2
87
+ else:
88
+ st = i + 1
89
+ if len(utts) == 0:
90
+ if lang == "zh":
91
+ utts.append(text + '。')
92
+ else:
93
+ utts.append(text + '.')
94
+ final_utts = []
95
+ cur_utt = ""
96
+ for utt in utts:
97
+ if calc_utt_length(cur_utt + utt) > token_max_n and calc_utt_length(cur_utt) > token_min_n:
98
+ final_utts.append(cur_utt)
99
+ cur_utt = ""
100
+ cur_utt = cur_utt + utt
101
+ if len(cur_utt) > 0:
102
+ if should_merge(cur_utt) and len(final_utts) != 0:
103
+ final_utts[-1] = final_utts[-1] + cur_utt
104
+ else:
105
+ final_utts.append(cur_utt)
106
+
107
+ return final_utts
108
+
109
+
110
+ # remove blank between chinese character
111
+ def replace_blank(text: str):
112
+ out_str = []
113
+ for i, c in enumerate(text):
114
+ if c == " ":
115
+ if ((text[i + 1].isascii() and text[i + 1] != " ") and
116
+ (text[i - 1].isascii() and text[i - 1] != " ")):
117
+ out_str.append(c)
118
+ else:
119
+ out_str.append(c)
120
+ return "".join(out_str)
121
+
122
+ def clean_markdown(md_text: str) -> str:
123
+ # 去除代码块 ``` ```(包括多行)
124
+ md_text = re.sub(r"```.*?```", "", md_text, flags=re.DOTALL)
125
+
126
+ # 去除内联代码 `code`
127
+ md_text = re.sub(r"`[^`]*`", "", md_text)
128
+
129
+ # 去除图片语法 ![alt](url)
130
+ md_text = re.sub(r"!\[[^\]]*\]\([^\)]+\)", "", md_text)
131
+
132
+ # 去除链接但保留文本 [text](url) -> text
133
+ md_text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", md_text)
134
+
135
+ # 替换无序列表符号
136
+ md_text = re.sub(r'^(\s*)-\s+', r'\1', md_text, flags=re.MULTILINE)
137
+
138
+ # 去除HTML标签
139
+ md_text = re.sub(r"<[^>]+>", "", md_text)
140
+
141
+ # 去除标题符号(#)
142
+ md_text = re.sub(r"^#{1,6}\s*", "", md_text, flags=re.MULTILINE)
143
+
144
+ # 去除多余空格和空行
145
+ md_text = re.sub(r"\n\s*\n", "\n", md_text) # 多余空行
146
+ md_text = md_text.strip()
147
+
148
+ return md_text
149
+
150
+
151
+ def clean_text(text):
152
+ # 去除 Markdown 语法
153
+ text = clean_markdown(text)
154
+ # 匹配并移除表情符号
155
+ text = regex.compile(r'\p{Emoji_Presentation}|\p{Emoji}\uFE0F', flags=regex.UNICODE).sub("",text)
156
+ # 去除换行符
157
+ text = text.replace("\n", " ")
158
+ text = text.replace("\t", " ")
159
+ text = text.replace('"', "\“")
160
+ return text
161
+
162
+ class TextNormalizer:
163
+ def __init__(self, tokenizer=None):
164
+ self.tokenizer = tokenizer
165
+ self.zh_tn_model = Normalizer(lang="zh", operator="tn", remove_erhua=True)
166
+ self.en_tn_model = Normalizer(lang="en", operator="tn")
167
+ self.inflect_parser = inflect.engine()
168
+
169
+ def normalize(self, text, split=False):
170
+ # 去除 Markdown 语法,去除表情符号,去除换行符
171
+ lang = "zh" if contains_chinese(text) else "en"
172
+ text = clean_text(text)
173
+ if lang == "zh":
174
+ text = text.replace("=", "等于") # 修复 ”550 + 320 等于 870 千卡。“ 被错误正则为 ”五百五十加三百二十等于八七十千卡.“
175
+ if re.search(r'([\d$%^*_+≥≤≠×÷?=])', text): # 避免 英文连字符被错误正则为减
176
+ text = re.sub(r'(?<=[a-zA-Z0-9])-(?=\d)', ' - ', text) # 修复 x-2 被正则为 x负2
177
+ text = self.zh_tn_model.normalize(text)
178
+ text = replace_blank(text)
179
+ text = replace_corner_mark(text)
180
+ text = remove_bracket(text)
181
+ else:
182
+ text = self.en_tn_model.normalize(text)
183
+ text = spell_out_number(text, self.inflect_parser)
184
+ if split is False:
185
+ return text