finalf0 commited on
Commit
0893f10
·
1 Parent(s): e1245d6
README.md ADDED
@@ -0,0 +1,1402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pipeline_tag: image-text-to-text
3
+ datasets:
4
+ - openbmb/RLAIF-V-Dataset
5
+ library_name: transformers
6
+ language:
7
+ - multilingual
8
+ tags:
9
+ - minicpm-o
10
+ - omni
11
+ - vision
12
+ - ocr
13
+ - multi-image
14
+ - video
15
+ - custom_code
16
+ ---
17
+
18
+ <h1>A GPT-4o Level MLLM for Vision, Speech and Multimodal Live Streaming on Your Phone</h1>
19
+
20
+ [GitHub](https://github.com/OpenBMB/MiniCPM-V) | [Online Demo](https://minicpm-omni-webdemo-us.modelbest.cn)</a>
21
+
22
+
23
+ ## MiniCPM-o 2.6
24
+
25
+ **MiniCPM-o 2.6** is the latest and most capable model in the MiniCPM-o series. The model is built in an end-to-end fashion based on SigLip-400M, Whisper-medium-300M, ChatTTS-200M, and Qwen2.5-7B with a total of 8B parameters. It exhibits a significant performance improvement over MiniCPM-V 2.6, and introduces new features for realtime speech conversation and multimodal live streaming. Notable features of MiniCPM-o 2.6 include:
26
+
27
+ - 🔥 **Leading Visual Capability.**
28
+ MiniCPM-o 2.6 achieves an average score of 70.2 on OpenCompass, a comprehensive evaluation over 8 popular benchmarks. **With only 8B parameters, it surpasses widely used proprietary models like GPT-4o-202405, Gemini 1.5 Pro, and Claude 3.5 Sonnet** for single image understanding. It also **outperforms GPT-4V and Claude 3.5 Sonnet** in mutli-image and video understanding, and shows promising in-context learning capability.
29
+
30
+ - 🎙 **State-of-the-art Speech Capability.** MiniCPM-o 2.6 supports **bilingual realtime speech conversation with configurable voices** in English and Chinese. It **outperforms GPT-4o-realtime on audio understanding tasks** such as ASR and STT translation, and shows **state-of-the-art performance on speech conversation in both semantic and acoustic evaluations in the open-source community**. It also allows for fun features such as emotion/speed/style control, voice cloning, role play, etc.
31
+
32
+ - 🎬 **Strong Multimodal Live Streaming Capability.** As a new feature, MiniCPM-o 2.6 can **accept continous video and audio streams independent of user queries, and support realtime speech interaction**. It **outperforms GPT-4o-realtime and Claude 3.5 Sonnet and shows state-of-art performance in open-source community on StreamingBench**, a comprehensive benchmark for real-time video understanding, omni-source (video & audio) understanding , and multimodal contextual understanding.
33
+
34
+ - 💪 **Strong OCR Capability and Others.**
35
+ Advancing popular visual capabilites from MiniCPM-V series, MiniCPM-o 2.6 can process images with any aspect ratio and up to 1.8 million pixels (e.g., 1344x1344). It achieves **state-of-the-art performance on OCRBench for models under 25B, surpassing proprietary models such as GPT-4o-202405**.
36
+ Based on the the latest [RLAIF-V](https://github.com/RLHF-V/RLAIF-V/) and [VisCPM](https://github.com/OpenBMB/VisCPM) techniques, it features **trustworthy behaviors**, outperforming GPT-4o and Claude 3.5 Sonnet on MMHal-Bench, and supports **multilingual capabilities** on more than 30 languages.
37
+
38
+
39
+ - 🚀 **Superior Efficiency.**
40
+ In addition to its friendly size, MiniCPM-o 2.6 also shows **state-of-the-art token density** (i.e., number of pixels encoded into each visual token). **It produces only 640 tokens when processing a 1.8M pixel image, which is 75% fewer than most models**. This directly improves the inference speed, first-token latency, memory usage, and power consumption. As a result, MiniCPM-o 2.6 can efficiently support **multimodal live streaming** on end-side devices such as iPad.
41
+
42
+ - 💫 **Easy Usage.**
43
+ MiniCPM-o 2.6 can be easily used in various ways: (1) [llama.cpp](XXX) support for efficient CPU inference on local devices, (2) [int4](https://huggingface.co/openbmb/MiniCPM-o-2_6-int4) and [GGUF](https://huggingface.co/openbmb/MiniCPM-o-2_6-gguf) format quantized models in 16 sizes, (3) [vLLM](#efficient-inference-with-llamacpp-ollama-vllm) support for high-throughput and memory-efficient inference, (4) fine-tuning on new domains and tasks with [LLaMA-Factory](./docs/llamafactory_train.md), (5) quick local WebUI demo setup with [Gradio](#chat-with-our-demo-on-gradio), and (6) online web demo on [CN](https://minicpm-omni-webdemo.modelbest.cn/
44
+ ) server and [US](https://minicpm-omni-webdemo-us.modelbest.cn/) server.
45
+
46
+
47
+ **Model Architecture.**
48
+
49
+ - **End-to-end Omni-modal Architecture.** Different modality encoder/decoders are connected and trained in an end-to-end fashion to fully exploit rich multimodal knowledge.
50
+ - **Omni-modal Live Streaming Mechanism.** (1) We change the offline modality encoder/decoders into online ones for streaminig inputs/outputs. (2) We devise a time-division multiplexing (TDM) mechanism for omni-modality streaminig processing in the LLM backbone. It divides parallel omni-modality streams into sequential info within small periodic time slices.
51
+ - **Configurable Speech Modeling Design.** We devise a multimodal system prompt, including traditional text system prompt, and a new audio system prompt to determine the assistant voice. This enables flexible voice configurations in inference time, and also facilitates voice cloning and description-based voice creation.
52
+
53
+ <div align="center">
54
+ <img src="https://github.com/yiranyyu/MiniCPM-V-private/blob/main/assets/minicpm-o-26-framework.png" , width=80%>
55
+ </div>
56
+
57
+ ### Evaluation <!-- omit in toc -->
58
+
59
+ <div align="center">
60
+ <img src="https://github.com/OpenBMB/MiniCPM-V/raw/main/assets/radar.png" width=66% />
61
+ </div>
62
+
63
+ <details>
64
+ <summary>Click to view visual understanding results.</summary>
65
+
66
+ **Image Understanding**
67
+
68
+ <div align="center">
69
+ <table style="margin: 0px auto;">
70
+ <thead>
71
+ <tr>
72
+ <th align="left">Model</th>
73
+ <th>Size</th>
74
+ <th>Token Density<sup>+</sup></th>
75
+ <th>OpenCompass</th>
76
+ <th>OCRBench</th>
77
+ <th>MathVista mini</th>
78
+ <th>ChartQA</th>
79
+ <th>MMVet</th>
80
+ <th>MMStar</th>
81
+ <th>MME</th>
82
+ <th>MMB1.1 test</th>
83
+ <th>AI2D</th>
84
+ <th>MMMU val</th>
85
+ <th>HallusionBench</th>
86
+ <th>TextVQA val</th>
87
+ <th>DocVQA test</th>
88
+ <th>MathVerse mini</th>
89
+ <th>MathVision</th>
90
+ <th>MMHal Score</th>
91
+ </tr>
92
+ </thead>
93
+ <tbody align="center">
94
+ <tr>
95
+ <td colspan="19" align="left"><strong>Proprietary</strong></td>
96
+ </tr>
97
+ <tr>
98
+ <td nowrap="nowrap" align="left">GPT-4o-20240513</td>
99
+ <td>-</td>
100
+ <td>1088</td>
101
+ <td><u>69.9</u></td>
102
+ <td>736</td>
103
+ <td>61.3</td>
104
+ <td>85.7</td>
105
+ <td><strong>69.1</strong></td>
106
+ <td>63.9</td>
107
+ <td>2328.7</td>
108
+ <td>82.2</td>
109
+ <td>84.6</td>
110
+ <td><strong>69.2</strong></td>
111
+ <td><strong>55.0</strong></td>
112
+ <td>-</td>
113
+ <td>92.8</td>
114
+ <td><strong>50.2</strong></td>
115
+ <td><strong>30.4</strong></td>
116
+ <td><u>3.6</u></td>
117
+ </tr>
118
+ <tr>
119
+ <td nowrap="nowrap" align="left">Claude3.5-Sonnet</td>
120
+ <td>-</td>
121
+ <td>750</td>
122
+ <td>67.9</td>
123
+ <td>788</td>
124
+ <td>61.6</td>
125
+ <td><strong>90.8</strong></td>
126
+ <td>66.0</td>
127
+ <td>62.2</td>
128
+ <td>1920.0</td>
129
+ <td>78.5</td>
130
+ <td>80.2</td>
131
+ <td><u>65.9</u></td>
132
+ <td>49.9</td>
133
+ <td>-</td>
134
+ <td><strong>95.2</strong></td>
135
+ <td>-</td>
136
+ <td>-</td>
137
+ <td>3.4</td>
138
+ </tr>
139
+ <tr>
140
+ <td nowrap="nowrap" align="left">Gemini-1.5-Pro</td>
141
+ <td>-</td>
142
+ <td>-</td>
143
+ <td>64.4</td>
144
+ <td>754</td>
145
+ <td>57.7</td>
146
+ <td>81.3</td>
147
+ <td>64.0</td>
148
+ <td>59.1</td>
149
+ <td>2110.6</td>
150
+ <td>73.9</td>
151
+ <td>79.1</td>
152
+ <td>60.6</td>
153
+ <td>45.6</td>
154
+ <td>73.5</td>
155
+ <td>86.5</td>
156
+ <td>-</td>
157
+ <td>19.2</td>
158
+ <td>-</td>
159
+ </tr>
160
+ <tr>
161
+ <td nowrap="nowrap" align="left">GPT-4o-mini-20240718</td>
162
+ <td>-</td>
163
+ <td>1088</td>
164
+ <td>64.1</td>
165
+ <td>785</td>
166
+ <td>52.4</td>
167
+ <td>-</td>
168
+ <td>66.9</td>
169
+ <td>54.8</td>
170
+ <td>2003.4</td>
171
+ <td>76.0</td>
172
+ <td>77.8</td>
173
+ <td>60.0</td>
174
+ <td>46.1</td>
175
+ <td>-</td>
176
+ <td>-</td>
177
+ <td>-</td>
178
+ <td>-</td>
179
+ <td>3.3</td>
180
+ </tr>
181
+ <tr>
182
+ <td colspan="19" align="left"><strong>Open Source</strong></td>
183
+ </tr>
184
+ <tr>
185
+ <td nowrap="nowrap" align="left">Cambrian-34B</td>
186
+ <td>34B</td>
187
+ <td><u>1820</u></td>
188
+ <td>58.3</td>
189
+ <td>591</td>
190
+ <td>50.3</td>
191
+ <td>75.6</td>
192
+ <td>53.2</td>
193
+ <td>54.2</td>
194
+ <td>2049.9</td>
195
+ <td>77.8</td>
196
+ <td>79.5</td>
197
+ <td>50.4</td>
198
+ <td>41.6</td>
199
+ <td>76.7</td>
200
+ <td>75.5</td>
201
+ <td>-</td>
202
+ <td>-</td>
203
+ <td>-</td>
204
+ </tr>
205
+ <tr>
206
+ <td nowrap="nowrap" align="left">GLM-4V-9B</td>
207
+ <td>13B</td>
208
+ <td>784</td>
209
+ <td>59.1</td>
210
+ <td>776</td>
211
+ <td>51.1</td>
212
+ <td>-</td>
213
+ <td>58.0</td>
214
+ <td>54.8</td>
215
+ <td>2018.8</td>
216
+ <td>67.9</td>
217
+ <td>71.2</td>
218
+ <td>46.9</td>
219
+ <td>45.0</td>
220
+ <td>-</td>
221
+ <td>-</td>
222
+ <td>-</td>
223
+ <td>-</td>
224
+ <td>-</td>
225
+ </tr>
226
+ <tr>
227
+ <td nowrap="nowrap" align="left">Pixtral-12B</td>
228
+ <td>12B</td>
229
+ <td>256</td>
230
+ <td>61.0</td>
231
+ <td>685</td>
232
+ <td>56.9</td>
233
+ <td>81.8</td>
234
+ <td>58.5</td>
235
+ <td>54.5</td>
236
+ <td>-</td>
237
+ <td>72.7</td>
238
+ <td>79.0</td>
239
+ <td>51.1</td>
240
+ <td>47.0</td>
241
+ <td>75.7</td>
242
+ <td>90.7</td>
243
+ <td>-</td>
244
+ <td>-</td>
245
+ <td>-</td>
246
+ </tr>
247
+ <tr>
248
+ <td nowrap="nowrap" align="left">DeepSeek-VL2-27B (4B)</td>
249
+ <td>27B</td>
250
+ <td>672</td>
251
+ <td>66.4</td>
252
+ <td>809</td>
253
+ <td>63.9</td>
254
+ <td>86.0</td>
255
+ <td>60.0</td>
256
+ <td>61.9</td>
257
+ <td>2253.0</td>
258
+ <td>81.2</td>
259
+ <td>83.8</td>
260
+ <td>54.0</td>
261
+ <td>45.3</td>
262
+ <td><u>84.2</u></td>
263
+ <td>93.3</td>
264
+ <td>-</td>
265
+ <td>-</td>
266
+ <td>3.0</td>
267
+ </tr>
268
+ <tr>
269
+ <td nowrap="nowrap" align="left">Qwen2-VL-7B</td>
270
+ <td>8B</td>
271
+ <td>784</td>
272
+ <td>67.1</td>
273
+ <td><u>866</u></td>
274
+ <td>58.2</td>
275
+ <td>83.0</td>
276
+ <td>62.0</td>
277
+ <td>60.7</td>
278
+ <td>2326.0</td>
279
+ <td>81.8</td>
280
+ <td>83.0</td>
281
+ <td>54.1</td>
282
+ <td>50.6</td>
283
+ <td><strong>84.3</strong></td>
284
+ <td><u>94.5</u></td>
285
+ <td>31.9</td>
286
+ <td>16.3</td>
287
+ <td>3.2</td>
288
+ </tr>
289
+ <tr>
290
+ <td nowrap="nowrap" align="left">LLaVA-OneVision-72B</td>
291
+ <td>72B</td>
292
+ <td>182</td>
293
+ <td>68.1</td>
294
+ <td>741</td>
295
+ <td>67.5</td>
296
+ <td>83.7</td>
297
+ <td>60.6</td>
298
+ <td><strong>65.8</strong></td>
299
+ <td>2261.0</td>
300
+ <td><strong>85.0</strong></td>
301
+ <td><u>85.6</u></td>
302
+ <td>56.8</td>
303
+ <td>49.0</td>
304
+ <td>80.5</td>
305
+ <td>91.3</td>
306
+ <td>39.1</td>
307
+ <td>-</td>
308
+ <td>3.5</td>
309
+ </tr>
310
+ <tr>
311
+ <td nowrap="nowrap" align="left">InternVL-2.5-8B</td>
312
+ <td>8B</td>
313
+ <td>706</td>
314
+ <td>68.3</td>
315
+ <td>822</td>
316
+ <td><u>64.4</u></td>
317
+ <td>84.8</td>
318
+ <td>62.8</td>
319
+ <td>62.8</td>
320
+ <td>2344.0</td>
321
+ <td><u>83.6</u></td>
322
+ <td>84.5</td>
323
+ <td>56.0</td>
324
+ <td>50.1</td>
325
+ <td>79.1</td>
326
+ <td>93.0</td>
327
+ <td>39.5</td>
328
+ <td>19.7</td>
329
+ <td>3.4</td>
330
+ </tr>
331
+ <tr>
332
+ <td nowrap="nowrap" align="left">MiniCPM-V 2.6</td>
333
+ <td>8B</td>
334
+ <td><strong>2822</strong></td>
335
+ <td>65.2</td>
336
+ <td>852*</td>
337
+ <td>60.6</td>
338
+ <td>79.4</td>
339
+ <td>60.0</td>
340
+ <td>57.5</td>
341
+ <td><u>2348.4*</u></td>
342
+ <td>78.0</td>
343
+ <td>82.1</td>
344
+ <td>49.8*</td>
345
+ <td>48.1*</td>
346
+ <td>80.1</td>
347
+ <td>90.8</td>
348
+ <td>25.7</td>
349
+ <td>18.3</td>
350
+ <td>3.6</td>
351
+ </tr>
352
+ <tr>
353
+ <td nowrap="nowrap" align="left">MiniCPM-o 2.6</td>
354
+ <td>8B</td>
355
+ <td><strong>2822</strong></td>
356
+ <td><strong>70.2</strong></td>
357
+ <td><strong>897*</strong></td>
358
+ <td><strong>71.9*</strong></td>
359
+ <td><u>86.9*</u></td>
360
+ <td><u>67.5</u></td>
361
+ <td><u>64.0</u></td>
362
+ <td><strong>2372.0*</strong></td>
363
+ <td>80.5</td>
364
+ <td><strong>85.8</strong></td>
365
+ <td>50.4*</td>
366
+ <td><u>51.9</u></td>
367
+ <td>82.0</td>
368
+ <td>93.5</td>
369
+ <td><u>41.4*</u></td>
370
+ <td><u>23.1*</u></td>
371
+ <td><strong>3.8</strong></td>
372
+ </tr>
373
+ </tbody>
374
+ </table>
375
+ </div>
376
+ * We evaluate this benchmark using chain-of-thought prompting. Specifically, for MME, we used this technique only for the Cognition set.
377
+
378
+
379
+ <sup>+</sup> Token Density: number of pixels encoded into each visual token at maximum resolution, i.e., # pixels at maximum resolution / # visual tokens.
380
+
381
+ Note: For proprietary models, we calculate token density based on the image encoding charging strategy defined in the official API documentation, which provides an upper-bound estimation.
382
+
383
+
384
+ **Multi-image and Video Understanding**
385
+
386
+ <div align="center">
387
+
388
+ <table style="margin: 0px auto;">
389
+ <thead>
390
+ <tr>
391
+ <th align="left">Model</th>
392
+ <th>Size</th>
393
+ <th>BLINK-val</th>
394
+ <th>Mantis-Eval</th>
395
+ <th>MIRB</th>
396
+ <th>Video-MME (wo / w subs)</th>
397
+ </tr>
398
+ </thead>
399
+ <tbody align="center">
400
+ <tr>
401
+ <td colspan="6" align="left"><strong>Proprietary</strong></td>
402
+ </tr>
403
+ <tr>
404
+ <td nowrap="nowrap" align="left">GPT-4o-20240513</td>
405
+ <td>-</td>
406
+ <td><strong>68</strong></td>
407
+ <td>-</td>
408
+ <td>-</td>
409
+ <td><strong>71.9/77.2<strong></td>
410
+ </tr>
411
+ <tr>
412
+ <td nowrap="nowrap" align="left">GPT4V</td>
413
+ <td>-</td>
414
+ <td>54.6</td>
415
+ <td>62.7</td>
416
+ <td>53.1</td>
417
+ <td>59.9/63.3</td>
418
+ </tr>
419
+ <tr>
420
+ <td colspan="6" align="left"><strong>Open-source</strong></td>
421
+ </tr>
422
+ <tr>
423
+ <td nowrap="nowrap" align="left">LLaVA-NeXT-Interleave 14B</td>
424
+ <td>14B</td>
425
+ <td>52.6</td>
426
+ <td>66.4</td>
427
+ <td>30.2</td>
428
+ <td>-</td>
429
+ </tr>
430
+ <tr>
431
+ <td nowrap="nowrap" align="left">LLaVA-One-Vision-72B</td>
432
+ <td>72B</td>
433
+ <td>55.4</td>
434
+ <td><strong>77.6</strong></td>
435
+ <td>-</td>
436
+ <td><u>66.2/69.5</u></td>
437
+ </tr>
438
+ <tr>
439
+ <td nowrap="nowrap" align="left">MANTIS 8B</td>
440
+ <td>8B</td>
441
+ <td>49.1</td>
442
+ <td>59.5</td>
443
+ <td>34.8</td>
444
+ <td>-</td>
445
+ </tr>
446
+ <tr>
447
+ <td nowrap="nowrap" align="left">Qwen2-VL-7B</td>
448
+ <td>8B</td>
449
+ <td>53.2</td>
450
+ <td>69.6*</td>
451
+ <td><strong>67.6*</strong></td>
452
+ <td>63.3/69.0</td>
453
+ </tr>
454
+ <tr>
455
+ <td nowrap="nowrap" align="left">InternVL-2.5-8B</td>
456
+ <td>8B</td>
457
+ <td>54.8</td>
458
+ <td>67.7</td>
459
+ <td>52.5</td>
460
+ <td>64.2/66.9</td>
461
+ </tr>
462
+ <tr>
463
+ <td nowrap="nowrap" align="left">MiniCPM-V 2.6</td>
464
+ <td>8B</td>
465
+ <td>53</td>
466
+ <td>69.1</td>
467
+ <td>53.8</td>
468
+ <td>60.9/63.6</td>
469
+ </tr>
470
+ <tr>
471
+ <td nowrap="nowrap" align="left">MiniCPM-o 2.6</td>
472
+ <td>8B</td>
473
+ <td><u>56.7</u></td>
474
+ <td><u>71.9</u></td>
475
+ <td><u>58.6</u></td>
476
+ <td>63.9/67.9</td>
477
+ </tr>
478
+ </tbody>
479
+ </table>
480
+
481
+ </div>
482
+ * We evaluate officially released checkpoints by ourselves.
483
+
484
+ </details>
485
+
486
+
487
+ <details>
488
+ <summary>Click to view audio understanding and speech conversation results.</summary>
489
+
490
+ **Audio Understanding**
491
+
492
+ <div align="center">
493
+ <table style="margin: 0px auto;">
494
+ <thead>
495
+ <tr>
496
+ <th align="left">Task</th>
497
+ <th>Size</th>
498
+ <th colspan="3">ASR (zh)</th>
499
+ <th colspan="3">ASR (en)</th>
500
+ <th colspan="2">ASR</th>
501
+ <th>Emotion</th>
502
+ </tr>
503
+ <tr>
504
+ <th align="left">Metric</th>
505
+ <td></td>
506
+ <th colspan="3">CER↓</th>
507
+ <th colspan="3">WER↓</th>
508
+ <th colspan="2">BLEU↑</th>
509
+ <th>ACC↑</th>
510
+ </tr>
511
+ <tr>
512
+ <th align="left">Dataset</th>
513
+ <td></td>
514
+ <th>AISHELL-1</th>
515
+ <th>Fleurs zh</th>
516
+ <th>WenetSpeech test-net</th>
517
+ <th>LibriSpeech test-clean</th>
518
+ <th>GigaSpeech</th>
519
+ <th>TED-LIUM</th>
520
+ <th>CoVoST en2zh</th>
521
+ <th>CoVoST zh2en</th>
522
+ <th>MELD emotion</th>
523
+ </tr>
524
+ </thead>
525
+ <tbody align="center">
526
+ <tr>
527
+ <td colspan="11" align="left"><strong>Proprietary</strong></td>
528
+ </tr>
529
+ <tr>
530
+ <td nowrap="nowrap" align="left">GPT-4o-Realtime</td>
531
+ <td>-</td>
532
+ <td>7.3*</td>
533
+ <td><u>5.4*</u></td>
534
+ <td>28.9*</td>
535
+ <td>2.6*</td>
536
+ <td>12.9*</td>
537
+ <td>4.8*</td>
538
+ <td>37.1*</td>
539
+ <td>15.7*</td>
540
+ <td>33.2*</td>
541
+ </tr>
542
+ <tr>
543
+ <td nowrap="nowrap" align="left">Gemini-1.5-Pro</td>
544
+ <td>-</td>
545
+ <td>4.5*</td>
546
+ <td>5.9*</td>
547
+ <td>14.3*</td>
548
+ <td>2.9*</td>
549
+ <td>10.6*</td>
550
+ <td><strong>3.0*</strong></td>
551
+ <td><u>47.3*</u></td>
552
+ <td>22.6*</td>
553
+ <td>48.4*</td>
554
+ </tr>
555
+ <tr>
556
+ <td colspan="11" align="left"><strong>Open-Source</strong></td>
557
+ </tr>
558
+ <tr>
559
+ <td nowrap="nowrap" align="left">Qwen2-Audio</td>
560
+ <td>8B</td>
561
+ <td>-</td>
562
+ <td>7.5</td>
563
+ <td>-</td>
564
+ <td><strong>1.6</strong></td>
565
+ <td>-</td>
566
+ <td>-</td>
567
+ <td>45.2</td>
568
+ <td><u>24.4</u></td>
569
+ <td><strong>55.3</strong></td>
570
+ </tr>
571
+ <tr>
572
+ <td nowrap="nowrap" align="left">Qwen2-Audio-Instruction</td>
573
+ <td>8B</td>
574
+ <td>2.6*</td>
575
+ <td>6.9*</td>
576
+ <td><u>10.3*</u></td>
577
+ <td>3.1*</td>
578
+ <td><u>9.7</u>*</td>
579
+ <td>5.9*</td>
580
+ <td>39.5*</td>
581
+ <td>22.9*</td>
582
+ <td>17.4*</td>
583
+ </tr>
584
+ <tr>
585
+ <td nowrap="nowrap" align="left">GLM-4-Voice-Base</td>
586
+ <td>9B</td>
587
+ <td><u>2.5</u></td>
588
+ <td>-</td>
589
+ <td>-</td>
590
+ <td>2.8</td>
591
+ <td>-</td>
592
+ <td>-</td>
593
+ <td>-</td>
594
+ <td>-</td>
595
+ </tr>
596
+ <tr style="background-color: #e6f2ff;">
597
+ <td nowrap="nowrap" align="left">MiniCPM-o 2.6</td>
598
+ <td>8B</td>
599
+ <td><strong>1.6</strong></td>
600
+ <td><strong>4.4</strong></td>
601
+ <td><strong>6.9</strong></td>
602
+ <td><u>1.7</u></td>
603
+ <td><strong>8.7</strong></td>
604
+ <td><strong>3.0</strong></td>
605
+ <td><strong>48.2</strong></td>
606
+ <td><strong>27.2</strong></td>
607
+ <td><u>52.4</u></td>
608
+ </tr>
609
+ </tbody>
610
+ </table>
611
+ </div>
612
+ * We evaluate officially released checkpoints by ourselves.<br><br>
613
+
614
+ **Speech Generation**
615
+
616
+ <div align="center">
617
+ <table style="margin: 0px auto;">
618
+ <thead>
619
+ <tr>
620
+ <th align="left">Task</th>
621
+ <th>Size</th>
622
+ <th colspan="9">SpeechQA</th>
623
+ </tr>
624
+ <tr>
625
+ <th align="left">Metric</th>
626
+ <th></th>
627
+ <th colspan="3">ACC↑</th>
628
+ <th>G-Eval (10 point)↑</th>
629
+ <th>Semantic ELO score↑</th>
630
+ <th>Acoustic ELO score↑</th>
631
+ <th>Overall ELO score↑</th>
632
+ <th>UTMOS↑</th>
633
+ <th>ASR-WER↓</th>
634
+ </tr>
635
+ <tr>
636
+ <th align="left">Dataset</th>
637
+ <th></th>
638
+ <th>Speech Llama Q.</th>
639
+ <th>Speech Web Q.</th>
640
+ <th>Speech Trivia QA</th>
641
+ <th>Speech AlpacaEval</th>
642
+ <th colspan="5">AudioArena</th>
643
+ </tr>
644
+ </thead>
645
+ <tbody align="center">
646
+ <tr>
647
+ <td colspan="11" align="left"><strong>Proprietary</strong></td>
648
+ </tr>
649
+ <tr>
650
+ <td nowrap="nowrap" align="left">GPT-4o-Realtime</td>
651
+ <td></td>
652
+ <td><strong>71.7</strong></td>
653
+ <td><strong>51.6</strong></td>
654
+ <td><strong>69.7</strong></td>
655
+ <td><strong>7.4</strong></td>
656
+ <td><strong>1157</strong></td>
657
+ <td><strong>1203</strong></td>
658
+ <td><strong>1200</strong></td>
659
+ <td><strong>4.2</strong></td>
660
+ <td><strong>2.3</strong></td>
661
+ </tr>
662
+ <tr>
663
+ <td colspan="11" align="left"><strong>Open-Source</strong></td>
664
+ </tr>
665
+ <tr>
666
+ <td nowrap="nowrap" align="left">GLM-4-Voice</td>
667
+ <td>9B</td>
668
+ <td>50.0</td>
669
+ <td>32.0</td>
670
+ <td>36.4</td>
671
+ <td><u>5.1</u></td>
672
+ <td>999</td>
673
+ <td>1147</td>
674
+ <td>1035</td>
675
+ <td><u>4.1</u></td>
676
+ <td><u>11.7</u></td>
677
+ </tr>
678
+ <tr>
679
+ <td nowrap="nowrap" align="left">Llama-Omni</td>
680
+ <td>8B</td>
681
+ <td>45.3</td>
682
+ <td>22.9</td>
683
+ <td>10.7</td>
684
+ <td>3.9</td>
685
+ <td>960</td>
686
+ <td>878</td>
687
+ <td>897</td>
688
+ <td>3.2</td>
689
+ <td>24.3</td>
690
+ </tr>
691
+ <tr>
692
+ <td nowrap="nowrap" align="left">Moshi</td>
693
+ <td>7B</td>
694
+ <td>43.7</td>
695
+ <td>23.8</td>
696
+ <td>16.7</td>
697
+ <td>2.4</td>
698
+ <td>871</td>
699
+ <td>808</td>
700
+ <td>875</td>
701
+ <td>2.8</td>
702
+ <td>8.2</td>
703
+ </tr>
704
+ <tr>
705
+ <td nowrap="nowrap" align="left">Mini-Omni</td>
706
+ <td>1B</td>
707
+ <td>22.0</td>
708
+ <td>12.8</td>
709
+ <td>6.9</td>
710
+ <td>2.5</td>
711
+ <td>926</td>
712
+ <td>803</td>
713
+ <td>865</td>
714
+ <td>3.4</td>
715
+ <td>10.0</td>
716
+ </tr>
717
+ <tr style="background-color: #e6f2ff;">
718
+ <td nowrap="nowrap" align="left">MiniCPM-o 2.6</td>
719
+ <td>8B</td>
720
+ <td><u>61.0</u></td>
721
+ <td><u>40.0</u></td>
722
+ <td><u>40.2</u></td>
723
+ <td><u>5.1</u></td>
724
+ <td><u>1088</u></td>
725
+ <td><u>1163</u></td>
726
+ <td><u>1131</u></td>
727
+ <td><strong>4.2</strong></td>
728
+ <td>9.8</td>
729
+ </tr>
730
+ </tbody>
731
+ </table>
732
+ </div>
733
+ All results are from AudioEvals, and the evaluation methods along with further details can be found in <a href="https://github.com/OpenBMB/UltraEval-Audio" target="_blank">AudioEvals</a>.<br><br>
734
+
735
+ **Voice Cloning**
736
+
737
+ <div align="center">
738
+ <table style="margin: 0px auto;">
739
+ <thead>
740
+ <tr>
741
+ <th align="left">Task</th>
742
+ <th colspan="2">Voice cloning</th>
743
+ </tr>
744
+ <tr>
745
+ <th align="left">Metric</th>
746
+ <th>SIMO↑</th>
747
+ <th>SIMO↑</th>
748
+ </tr>
749
+ <tr>
750
+ <th align="left">Dataset</th>
751
+ <th>Seed-TTS test-zh</th>
752
+ <th>Seed-TTS test-en</th>
753
+ </tr>
754
+ </thead>
755
+ <tbody align="center">
756
+ <tr>
757
+ <td nowrap="nowrap" align="left">F5-TTS</td>
758
+ <td><strong>76</strong></td>
759
+ <td><strong>67</strong></td>
760
+ </tr>
761
+ <tr>
762
+ <td nowrap="nowrap" align="left">CosyVoice</td>
763
+ <td><u>75</u></td>
764
+ <td><u>64</u></td>
765
+ </tr>
766
+ <tr>
767
+ <td nowrap="nowrap" align="left">FireRedTTS</td>
768
+ <td>63</td>
769
+ <td>46</td>
770
+ </tr>
771
+ <tr style="background-color: #e6f2ff;">
772
+ <td nowrap="nowrap" align="left">MiniCPM-o 2.6</td>
773
+ <td>57</td>
774
+ <td>47</td>
775
+ </tr>
776
+ </tbody>
777
+ </table>
778
+ </div>
779
+ Note: Mimick Task: Takes audio input, and outputs both an ASR transcription and a voice imitation (TTS)
780
+
781
+ </details>
782
+
783
+ <details>
784
+ <summary>Click to view multimodal live streaming results.</summary>
785
+
786
+ **Multimodal Live Streaming**: results on StreamingBench
787
+
788
+ <table style="margin: 0px auto;">
789
+ <thead>
790
+ <tr>
791
+ <th align="left">Model</th>
792
+ <th>Size</th>
793
+ <th>Real-Time Video Understanding</th>
794
+ <th>Omni-Source Understanding</th>
795
+ <th>Contextual Understanding</th>
796
+ <th>Overall</th>
797
+ </tr>
798
+ </thead>
799
+ <tbody align="center">
800
+ <tr>
801
+ <td colspan="7" align="left"><strong>Proprietary</strong></td>
802
+ </tr>
803
+ <tr>
804
+ <td nowrap="nowrap" align="left">Gemini 1.5 Pro</td>
805
+ <td>-</td>
806
+ <td><u>77.4</u></td>
807
+ <td><strong>67.8</strong></td>
808
+ <td><strong>51.1</strong></td>
809
+ <td><strong>70.3</strong></td>
810
+ </tr>
811
+ <tr>
812
+ <td nowrap="nowrap" align="left">GPT-4o</td>
813
+ <td>-</td>
814
+ <td>74.5</td>
815
+ <td>51.0</td>
816
+ <td><u>48.0</u></td>
817
+ <td>64.1</td>
818
+ </tr>
819
+ <tr>
820
+ <td nowrap="nowrap" align="left">Claude-3.5-Sonnet</td>
821
+ <td>-</td>
822
+ <td>74.0</td>
823
+ <td>41.4</td>
824
+ <td>37.8</td>
825
+ <td>59.7</td>
826
+ </tr>
827
+ <tr>
828
+ <td colspan="9" align="left"><strong>Open-source</strong></td>
829
+ </tr>
830
+ <tr>
831
+ <td nowrap="nowrap" align="left">VILA-1.5</td>
832
+ <td>8B</td>
833
+ <td>61.5</td>
834
+ <td>37.5</td>
835
+ <td>26.7</td>
836
+ <td>49.5</td>
837
+ </tr>
838
+ <tr>
839
+ <td nowrap="nowrap" align="left">LongVA</td>
840
+ <td>7B</td>
841
+ <td>63.1</td>
842
+ <td>35.9</td>
843
+ <td>30.2</td>
844
+ <td>50.7</td>
845
+ </tr>
846
+ <tr>
847
+ <td nowrap="nowrap" align="left">LLaVA-Next-Video-34B</td>
848
+ <td>34B</td>
849
+ <td>69.8</td>
850
+ <td>41.7</td>
851
+ <td>34.3</td>
852
+ <td>56.7</td>
853
+ </tr>
854
+ <tr>
855
+ <td nowrap="nowrap" align="left">Qwen2-VL-7B</td>
856
+ <td>8B</td>
857
+ <td>71.2</td>
858
+ <td>40.7</td>
859
+ <td>33.1</td>
860
+ <td>57.0</td>
861
+ </tr>
862
+ <tr>
863
+ <td nowrap="nowrap" align="left">InternVL2-8B</td>
864
+ <td>8B</td>
865
+ <td>70.1</td>
866
+ <td>42.7</td>
867
+ <td>34.1</td>
868
+ <td>57.0</td>
869
+ </tr>
870
+ <tr>
871
+ <td nowrap="nowrap" align="left">VITA-1.5</td>
872
+ <td>8B</td>
873
+ <td>70.9</td>
874
+ <td>40.8</td>
875
+ <td>35.8</td>
876
+ <td>57.4</td>
877
+ </tr>
878
+ <tr>
879
+ <td nowrap="nowrap" align="left">LLaVA-OneVision-7B</td>
880
+ <td>8B</td>
881
+ <td>74.3</td>
882
+ <td>40.8</td>
883
+ <td>31.0</td>
884
+ <td>58.4</td>
885
+ </tr>
886
+ <tr>
887
+ <td nowrap="nowrap" align="left">InternLM-XC2.5-OL-7B</td>
888
+ <td>8B</td>
889
+ <td>75.4</td>
890
+ <td>46.2</td>
891
+ <td>33.6</td>
892
+ <td>60.8</td>
893
+ </tr>
894
+ <tr>
895
+ <td nowrap="nowrap" align="left">MiniCPM-V 2.6</td>
896
+ <td>8B</td>
897
+ <td>72.4</td>
898
+ <td>40.2</td>
899
+ <td>33.4</td>
900
+ <td>57.7</td>
901
+ </tr>
902
+ <tr style="background-color: #e6f2ff;">
903
+ <td nowrap="nowrap" align="left">MiniCPM-o 2.6</td>
904
+ <td>8B</td>
905
+ <td><strong>79.9</strong></td>
906
+ <td><u>53.4</u></td>
907
+ <td>38.5</td>
908
+ <td><u>66.0</u></td>
909
+ </tr>
910
+ </tbody>
911
+ </table>
912
+
913
+ </details>
914
+
915
+
916
+ ### Examples <!-- omit in toc -->
917
+
918
+ We deploy MiniCPM-o 2.6 on end devices. The demo video is the raw screen recording on a iPad Pro without edition.
919
+
920
+
921
+ <div style="display: flex; flex-direction: column; align-items: center;">
922
+ <img src="https://github.com/yiranyyu/MiniCPM-V-private/blob/main/assets/minicpmo2_6/minicpmo2_6_math_intersect.png" alt="math" style="margin-bottom: 5px;">
923
+ <img src="https://github.com/yiranyyu/MiniCPM-V-private/blob/main/assets/minicpmo2_6/minicpmo2_6_diagram_train_NN.png" alt="diagram" style="margin-bottom: 5px;">
924
+ <img src="https://github.com/yiranyyu/MiniCPM-V-private/blob/main/assets/minicpmo2_6/minicpmo2_6_multi-image_bike.png" alt="bike" style="margin-bottom: 5px;">
925
+ </div>
926
+
927
+
928
+
929
+
930
+ ## Online Demo
931
+ Click here to try the online demo of **MiniCPM-o 2.6** on [CN](https://minicpm-omni-webdemo.modelbest.cn/) server and [US](https://minicpm-omni-webdemo-us.modelbest.cn) server.
932
+
933
+
934
+ ## Usage
935
+ Inference using Huggingface transformers on NVIDIA GPUs. Requirements tested on python 3.10:
936
+ ```
937
+ Pillow==10.1.0
938
+ torch==2.2.0
939
+ torchaudio==2.2.0
940
+ torchvision==0.17.0
941
+ transformers==4.44.2
942
+ librosa==0.9.0
943
+ soundfile==0.12.1
944
+ vector-quantize-pytorch==1.18.5
945
+ vocos==0.1.0
946
+ decord
947
+ moviepy
948
+ ```
949
+
950
+
951
+ ### Model initialization
952
+ ```python
953
+
954
+ import torch
955
+ from PIL import Image
956
+ from transformers import AutoModel, AutoTokenizer
957
+
958
+ # load omni model default, the default init_vision/init_audio/init_tts is True
959
+ # if load vision-only model, please set init_audio=False and init_tts=False
960
+ # if load audio-only model, please set init_vision=False
961
+ model = AutoModel.from_pretrained(
962
+ 'openbmb/MiniCPM-o-2_6',
963
+ trust_remote_code=True,
964
+ attn_implementation='sdpa', # sdpa or flash_attention_2
965
+ torch_dtype=torch.bfloat16,
966
+ init_vision=True,
967
+ init_audio=True,
968
+ init_tts=True
969
+ )
970
+
971
+
972
+ model = model.eval().cuda()
973
+ tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-o-2_6', trust_remote_code=True)
974
+
975
+ # In addition to vision-only mode, tts processor and vocos also needs to be initialized
976
+ model.init_tts()
977
+ model.tts.float()
978
+ ```
979
+ ### Omni mode
980
+ we provide two inference modes: chat and streaming
981
+
982
+ #### chat inference
983
+ ```python
984
+ import math
985
+ import numpy as np
986
+ from PIL import Image
987
+ from moviepy.editor import VideoFileClip
988
+ import tempfile
989
+ import librosa
990
+ import soundfile as sf
991
+
992
+ def get_video_chunk_content(video_path, flatten=True):
993
+ video = VideoFileClip(video_path)
994
+ print('video_duration:', video.duration)
995
+
996
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=True) as temp_audio_file:
997
+ temp_audio_file_path = temp_audio_file.name
998
+ video.audio.write_audiofile(temp_audio_file_path, codec="pcm_s16le", fps=16000)
999
+ audio_np, sr = librosa.load(temp_audio_file_path, sr=16000, mono=True)
1000
+ num_units = math.ceil(video.duration)
1001
+
1002
+ # 1 frame + 1s audio chunk
1003
+ contents= []
1004
+ for i in range(num_units):
1005
+ frame = video.get_frame(i+1)
1006
+ image = Image.fromarray((frame).astype(np.uint8))
1007
+ audio = audio_np[sr*i:sr*(i+1)]
1008
+ if flatten:
1009
+ contents.extend(["<unit>", image, audio])
1010
+ else:
1011
+ contents.append(["<unit>", image, audio])
1012
+
1013
+ return contents
1014
+
1015
+ video_path="/path/to/video"
1016
+ sys_msg = model.get_sys_prompt(mode='omni', language='en')
1017
+ # if use voice clone prompt, please set ref_audio
1018
+ # ref_audio_path = '/path/to/ref_audio'
1019
+ # ref_audio, _ = librosa.load(ref_audio_path, sr=16000, mono=True)
1020
+ # sys_msg = model.get_sys_prompt(ref_audio=ref_audio, mode='omni', language='en')
1021
+
1022
+ contents = get_video_chunk_content(video_path)
1023
+ msg = {"role":"user", "content": contents}
1024
+ msgs = [sys_msg, msg]
1025
+
1026
+ # please set generate_audio=True and output_audio_path to save the tts result
1027
+ generate_audio = True
1028
+ output_audio_path = 'output.wav'
1029
+
1030
+ res = model.chat(
1031
+ msgs=msgs,
1032
+ tokenizer=tokenizer,
1033
+ sampling=True,
1034
+ temperature=0.5,
1035
+ max_new_tokens=4096,
1036
+ omni_input=True, # please set omni_input=True when omni inference
1037
+ use_tts_template=True,
1038
+ generate_audio=generate_audio,
1039
+ output_audio_path=output_audio_path,
1040
+ max_slice_nums=1,
1041
+ use_image_id=False,
1042
+ return_dict=True
1043
+ )
1044
+ print(res)
1045
+ ```
1046
+ #### streaming inference
1047
+ ```python
1048
+ # a new conversation need reset session first, it will reset the kv-cache
1049
+ model.reset_session()
1050
+
1051
+ contents = get_video_chunk_content(video_path, flatten=False)
1052
+ session_id = '123'
1053
+ generate_audio = True
1054
+
1055
+ # 1. prefill system prompt
1056
+ res = model.streaming_prefill(
1057
+ session_id=session_id,
1058
+ msgs=[sys_msg],
1059
+ tokenizer=tokenizer
1060
+ )
1061
+
1062
+ # 2. prefill video/audio chunks
1063
+ for content in contents:
1064
+ msgs = [{"role":"user", "content": content}]
1065
+ res = model.streaming_prefill(
1066
+ session_id=session_id,
1067
+ msgs=msgs,
1068
+ tokenizer=tokenizer
1069
+ )
1070
+
1071
+ # 3. generate
1072
+ res = model.streaming_generate(
1073
+ session_id=session_id,
1074
+ tokenizer=tokenizer,
1075
+ temperature=0.5,
1076
+ generate_audio=generate_audio
1077
+ )
1078
+
1079
+ audios = []
1080
+ text = ""
1081
+
1082
+ if generate_audio:
1083
+ for r in res:
1084
+ audio_wav = r.audio_wav
1085
+ sampling_rate = r.sampling_rate
1086
+ txt = r.text
1087
+
1088
+ audios.append(audio_wav)
1089
+ text += txt
1090
+
1091
+ res = np.concatenate(audios)
1092
+ sf.write("output.wav", res, samplerate=sampling_rate)
1093
+ print("text:", text)
1094
+ print("audio saved to output.wav")
1095
+ else:
1096
+ for r in res:
1097
+ text += r['text']
1098
+ print("text:", text)
1099
+
1100
+ ```
1101
+
1102
+ ### Audio-Only mode
1103
+ #### Mimick
1104
+ ```python
1105
+ mimick_prompt = "Please repeat each user's speech, including voice style and speech content."
1106
+ audio_input, _ = librosa.load('xxx.wav', sr=16000, mono=True)
1107
+ msgs = [{'role': 'user', 'content': [mimick_prompt,audio_input]}]
1108
+
1109
+ res = model.chat(
1110
+ msgs=msgs,
1111
+ tokenizer=tokenizer,
1112
+ sampling=True,
1113
+ max_new_tokens=128,
1114
+ use_tts_template=True,
1115
+ temperature=0.3,
1116
+ generate_audio=True,
1117
+ output_audio_path='output.wav', # save the tts result to output_audio_path
1118
+ )
1119
+ ```
1120
+
1121
+ #### General Speech Conversation with Configurable Voices
1122
+ <details> <summary>Click to view the Python code for enabling MiniCPM-o 2.6 to interact with you in a specified voice.</summary>
1123
+
1124
+ ```python
1125
+ ref_audio, _ = librosa.load('./assert/voice_01.wav', sr=16000, mono=True) # load the reference audio
1126
+
1127
+ # Audio RolePlay: # With this mode, model will role-play the character based on the audio prompt.
1128
+ sys_prompt = model.get_sys_prompt(ref_audio=ref_audio, mode='audio_roleplay', language='en')
1129
+ user_question = {'role': 'user', 'content': [librosa.load('xxx.wav', sr=16000, mono=True)[0]]}
1130
+
1131
+ # Audio Assistant: # With this mode, model will speak with the voice in ref_audio as a AI assistant.
1132
+ # sys_prompt = model.get_sys_prompt(ref_audio=ref_audio, mode='audio_assistant', language='en')
1133
+ # user_question = {'role': 'user', 'content': [librosa.load('xxx.wav', sr=16000, mono=True)[0]]} # Try to ask something!
1134
+ ```
1135
+ ```python
1136
+ msgs = [sys_prompt, user_question]
1137
+ res = model.chat(
1138
+ image=None,
1139
+ msgs=msgs,
1140
+ context=None,
1141
+ tokenizer=tokenizer,
1142
+ sampling=True,
1143
+ max_new_tokens=128,
1144
+ stream=False,
1145
+ stream_input=True,
1146
+ use_tts_template=True,
1147
+ generate_audio=True,
1148
+ temperature=0.3,
1149
+ output_audio_path='result.wav',
1150
+ )
1151
+
1152
+ # round two
1153
+ history = msgs.append({'role': 'assistant', 'content': res})
1154
+ user_question = {'role': 'user', 'content': [librosa.load('xxx.wav', sr=16000, mono=True)[0]]}
1155
+ msgs = history.append(user_question)
1156
+ res = model.chat(
1157
+ image=None,
1158
+ msgs=msgs,
1159
+ context=None,
1160
+ tokenizer=tokenizer,
1161
+ sampling=True,
1162
+ max_new_tokens=128,
1163
+ stream=False,
1164
+ stream_input=True,
1165
+ use_tts_template=True,
1166
+ generate_audio=True,
1167
+ temperature=0.3,
1168
+ output_audio_path='result_round_2.wav',
1169
+ )
1170
+ print(res)
1171
+ ```
1172
+
1173
+ </details>
1174
+
1175
+ #### Addressing various audio tasks
1176
+ <details>
1177
+ <summary> Click to show Python code running MiniCPM-o 2.6 with specific audioQA task. </summary>
1178
+
1179
+ ```python
1180
+ '''
1181
+ Audio Understanding Task Prompt:
1182
+ Speech:
1183
+ ASR with ZH(same as AST en2zh): 请仔细听这段音频片段,并将其内容逐字记录。
1184
+ ASR with EN(same as AST zh2en): Please listen to the audio snippet carefully and transcribe the content.
1185
+ Speaker Analysis: Based on the speaker's content, speculate on their gender, condition, age range, and health status.
1186
+ General Audio:
1187
+ Audio Caption: Summarize the main content of the audio.
1188
+ Sound Scene Tagging: Utilize one keyword to convey the audio's content or the associated scene.
1189
+ '''
1190
+ task_prompt = "\n"
1191
+ audio_input, _ = librosa.load('xxx.wav', sr=16000, mono=True)
1192
+
1193
+ msgs = [{'role': 'user', 'content': [task_prompt,audio_input]}]
1194
+
1195
+ res = model.chat(
1196
+ image=None,
1197
+ msgs=msgs,
1198
+ context=None,
1199
+ tokenizer=tokenizer,
1200
+ sampling=True,
1201
+ max_new_tokens=128,
1202
+ stream=False,
1203
+ stream_input=True,
1204
+ use_tts_template=True,
1205
+ generate_audio=True,
1206
+ temperature=0.3,
1207
+ output_audio_path='result.wav',
1208
+ )
1209
+ print(res)
1210
+ ```
1211
+ ```python
1212
+ '''
1213
+ Speech Generation Task Prompt:
1214
+ Human Instruction-to-Speech: see https://voxinstruct.github.io/VoxInstruct/
1215
+ Example:
1216
+ # 在新闻中,一个年轻男性兴致勃勃地说:“祝福亲爱的祖国母亲美丽富强!”他用低音调和低音量,慢慢地说出了这句话。
1217
+ # Delighting in a surprised tone, an adult male with low pitch and low volume comments:"One even gave my little dog a biscuit" This dialogue takes place at a leisurely pace, delivering a sense of excitement and surprise in the context.
1218
+
1219
+ Voice Cloning or Voice Creation: With this mode, model will act like a TTS model.
1220
+ '''
1221
+ # Human Instruction-to-Speech:
1222
+ task_prompt = '' #Try to make some Human Instruction-to-Speech prompt
1223
+ msgs = [{'role': 'user', 'content': [task_prompt]}] # you can try to use the same audio question
1224
+
1225
+ # Voice Cloning mode: With this mode, model will act like a TTS model.
1226
+ # sys_prompt = model.get_sys_prompt(ref_audio=ref_audio, mode='voice_cloning', language='en')
1227
+ # text_prompt = f"Please read the text below."
1228
+ # user_question = {'role': 'user', 'content': [text_prompt, "content that you want to read"]} # using same voice in sys_prompt to read the text. (Voice Cloning)
1229
+ # user_question = {'role': 'user', 'content': [text_prompt, librosa.load('xxx.wav', sr=16000, mono=True)[0]]} # using same voice in sys_prompt to read 'xxx.wav'. (Voice Creation)
1230
+
1231
+ msgs = [sys_prompt, user_question]
1232
+ res = model.chat(
1233
+ image=None,
1234
+ msgs=msgs,
1235
+ context=None,
1236
+ tokenizer=tokenizer,
1237
+ sampling=True,
1238
+ max_new_tokens=128,
1239
+ stream=False,
1240
+ stream_input=True,
1241
+ use_tts_template=True,
1242
+ generate_audio=True,
1243
+ temperature=0.3,
1244
+ output_audio_path='result.wav',
1245
+ )
1246
+
1247
+
1248
+ ```
1249
+
1250
+ </details>
1251
+
1252
+ ### Vision-Only mode
1253
+
1254
+ `MiniCPM-o-2_6` has the same inference methods as `MiniCPM-V-2_6`
1255
+
1256
+ #### chat with single image
1257
+ ```python
1258
+ # test.py
1259
+ image = Image.open('xx.jpg').convert('RGB')
1260
+ question = 'What is in the image?'
1261
+ msgs = [{'role': 'user', 'content': [image, question]}]
1262
+ res = model.chat(
1263
+ image=None,
1264
+ msgs=msgs,
1265
+ tokenizer=tokenizer
1266
+ )
1267
+ print(res)
1268
+
1269
+ ## if you want to use streaming, please make sure sampling=True and stream=True
1270
+ ## the model.chat will return a generator
1271
+ res = model.chat(
1272
+ msgs=msgs,
1273
+ tokenizer=tokenizer,
1274
+ sampling=True,
1275
+ stream=True
1276
+ )
1277
+ generated_text = ""
1278
+ for new_text in res:
1279
+ generated_text += new_text
1280
+ print(new_text, flush=True, end='')
1281
+ ```
1282
+
1283
+ #### Chat with multiple images
1284
+ <details>
1285
+ <summary> Click to show Python code running MiniCPM-o 2.6 with multiple images input. </summary>
1286
+
1287
+ ```python
1288
+ image1 = Image.open('image1.jpg').convert('RGB')
1289
+ image2 = Image.open('image2.jpg').convert('RGB')
1290
+ question = 'Compare image 1 and image 2, tell me about the differences between image 1 and image 2.'
1291
+ msgs = [{'role': 'user', 'content': [image1, image2, question]}]
1292
+ answer = model.chat(
1293
+ msgs=msgs,
1294
+ tokenizer=tokenizer
1295
+ )
1296
+ print(answer)
1297
+ ```
1298
+ </details>
1299
+
1300
+ #### In-context few-shot learning
1301
+ <details>
1302
+ <summary> Click to view Python code running MiniCPM-o 2.6 with few-shot input. </summary>
1303
+
1304
+ ```python
1305
+ question = "production date"
1306
+ image1 = Image.open('example1.jpg').convert('RGB')
1307
+ answer1 = "2023.08.04"
1308
+ image2 = Image.open('example2.jpg').convert('RGB')
1309
+ answer2 = "2007.04.24"
1310
+ image_test = Image.open('test.jpg').convert('RGB')
1311
+ msgs = [
1312
+ {'role': 'user', 'content': [image1, question]}, {'role': 'assistant', 'content': [answer1]},
1313
+ {'role': 'user', 'content': [image2, question]}, {'role': 'assistant', 'content': [answer2]},
1314
+ {'role': 'user', 'content': [image_test, question]}
1315
+ ]
1316
+ answer = model.chat(
1317
+ msgs=msgs,
1318
+ tokenizer=tokenizer
1319
+ )
1320
+ print(answer)
1321
+ ```
1322
+ </details>
1323
+
1324
+ #### Chat with video
1325
+ <details>
1326
+ <summary> Click to view Python code running MiniCPM-o 2.6 with video input. </summary>
1327
+
1328
+ ```python
1329
+ MAX_NUM_FRAMES=64 # if cuda OOM set a smaller number
1330
+ def encode_video(video_path):
1331
+ def uniform_sample(l, n):
1332
+ gap = len(l) / n
1333
+ idxs = [int(i * gap + gap / 2) for i in range(n)]
1334
+ return [l[i] for i in idxs]
1335
+ vr = VideoReader(video_path, ctx=cpu(0))
1336
+ sample_fps = round(vr.get_avg_fps() / 1) # FPS
1337
+ frame_idx = [i for i in range(0, len(vr), sample_fps)]
1338
+ if len(frame_idx) > MAX_NUM_FRAMES:
1339
+ frame_idx = uniform_sample(frame_idx, MAX_NUM_FRAMES)
1340
+ frames = vr.get_batch(frame_idx).asnumpy()
1341
+ frames = [Image.fromarray(v.astype('uint8')) for v in frames]
1342
+ print('num frames:', len(frames))
1343
+ return frames
1344
+ video_path ="video_test.mp4"
1345
+ frames = encode_video(video_path)
1346
+ question = "Describe the video"
1347
+ msgs = [
1348
+ {'role': 'user', 'content': frames + [question]},
1349
+ ]
1350
+ # Set decode params for video
1351
+ params={}
1352
+ params["use_image_id"] = False
1353
+ params["max_slice_nums"] = 2 # use 1 if cuda OOM and video resolution > 448*448
1354
+ answer = model.chat(
1355
+ msgs=msgs,
1356
+ tokenizer=tokenizer,
1357
+ **params
1358
+ )
1359
+ print(answer)
1360
+ ```
1361
+ </details>
1362
+
1363
+ Please look at [GitHub](https://github.com/OpenBMB/MiniCPM-V) for more detail about usage.
1364
+
1365
+
1366
+ ## Inference with llama.cpp<a id="llamacpp"></a>
1367
+ MiniCPM-o 2.6 can run with llama.cpp. See our fork of [llama.cpp](https://github.com/OpenBMB/llama.cpp/tree/minicpm-v2.5/examples/minicpmv) for more detail.
1368
+
1369
+
1370
+ ## Int4 quantized version
1371
+ Download the int4 quantized version for lower GPU memory (7GB) usage: [MiniCPM-o-2_6-int4](https://huggingface.co/openbmb/MiniCPM-o-2_6-int4).
1372
+
1373
+
1374
+ ## License
1375
+ #### Model License
1376
+ * The code in this repo is released under the [Apache-2.0](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE) License.
1377
+ * The usage of MiniCPM-o and MiniCPM-V series model weights must strictly follow [MiniCPM Model License.md](https://github.com/OpenBMB/MiniCPM/blob/main/MiniCPM%20Model%20License.md).
1378
+ * The models and weights of MiniCPM are completely free for academic research. After filling out a ["questionnaire"](https://modelbest.feishu.cn/share/base/form/shrcnpV5ZT9EJ6xYjh3Kx0J6v8g) for registration, MiniCPM-o 2.6 weights are also available for free commercial use.
1379
+
1380
+
1381
+ #### Statement
1382
+ * As an LMM, MiniCPM-o 2.6 generates contents by learning a large mount of multimodal corpora, but it cannot comprehend, express personal opinions or make value judgement. Anything generated by MiniCPM-o 2.6 does not represent the views and positions of the model developers
1383
+ * We will not be liable for any problems arising from the use of the MinCPM-V models, including but not limited to data security issues, risk of public opinion, or any risks and problems arising from the misdirection, misuse, dissemination or misuse of the model.
1384
+
1385
+ ## Key Techniques and Other Multimodal Projects
1386
+
1387
+ 👏 Welcome to explore key techniques of MiniCPM-o 2.6 and other multimodal projects of our team:
1388
+
1389
+ [VisCPM](https://github.com/OpenBMB/VisCPM/tree/main) | [RLHF-V](https://github.com/RLHF-V/RLHF-V) | [LLaVA-UHD](https://github.com/thunlp/LLaVA-UHD) | [RLAIF-V](https://github.com/RLHF-V/RLAIF-V)
1390
+
1391
+ ## Citation
1392
+
1393
+ If you find our work helpful, please consider citing our papers 📝 and liking this project ❤️!
1394
+
1395
+ ```bib
1396
+ @article{yao2024minicpm,
1397
+ title={MiniCPM-V: A GPT-4V Level MLLM on Your Phone},
1398
+ author={Yao, Yuan and Yu, Tianyu and Zhang, Ao and Wang, Chongyi and Cui, Junbo and Zhu, Hongji and Cai, Tianchi and Li, Haoyu and Zhao, Weilin and He, Zhihui and others},
1399
+ journal={arXiv preprint arXiv:2408.01800},
1400
+ year={2024}
1401
+ }
1402
+ ```
configuration_minicpm.py CHANGED
@@ -190,6 +190,7 @@ class MiniCPMOConfig(Qwen2Config):
190
  elif isinstance(vision_config, SiglipVisionConfig):
191
  self.vision_config = vision_config
192
 
 
193
  if audio_config is None:
194
  self.audio_config = WhisperConfig()
195
  elif isinstance(audio_config, dict):
 
190
  elif isinstance(vision_config, SiglipVisionConfig):
191
  self.vision_config = vision_config
192
 
193
+ # same as openai/whisper-medium add use_cache
194
  if audio_config is None:
195
  self.audio_config = WhisperConfig()
196
  elif isinstance(audio_config, dict):
modeling_minicpmo.py CHANGED
@@ -121,19 +121,21 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
121
 
122
  self.processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True)
123
 
124
- self.terminators = ['<|im_end|>', '<|endoftext|>']
125
 
126
  self.default_tts_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<|spk_bos|><|spk|><|spk_eos|><|tts_bos|>' }}{% endif %}"
127
  self.force_no_stop = False
128
 
129
  # for stream api
 
 
 
130
  self.session_id = None
131
  self.new_user_msg = True
132
  self.llm_generated = False
133
  self.llm_generate_completed = False
134
  self.llm_past_key_values = None
135
  self.audio_past_key_values = None # apm kv cache
136
- self.speak_score = [0.0]
137
 
138
  def init_tts(
139
  self,
@@ -401,6 +403,21 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
401
  return vllm_embedding, vision_hidden_states
402
 
403
  def get_audio_embedding_streaming(self, data):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  wavforms = data.get("audio_features", []) # (bs, 80, frames) or [], multi audios need filled in advance
405
  audio_feature_lens_raw = data.get("audio_feature_lens", []) # list, [[x1, x2], [y1], [z1]]
406
 
@@ -447,15 +464,24 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
447
  return []
448
 
449
  def get_audio_embedding(self, data, chunk_length=-1):
450
- """
451
- Compute all audio embeddings
 
 
 
 
 
452
  Args:
453
- data:
454
- chunk_length: if chunk_length == -1 means whisper use full attention
455
- if chunk_length > 0 means whisper use chunk attention
 
 
 
456
  Returns:
457
- audio embeddings
458
  """
 
459
  wavforms = data.get("audio_features", []) # (bs, 80, frames) or [], multi audios need filled in advance
460
  audio_feature_lens_raw = data.get("audio_feature_lens", []) # list, [[x1, x2], [y1], [z1]]
461
 
@@ -520,7 +546,6 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
520
 
521
  def get_omni_embedding(self, data, input_embeddings, chunk_length=-1, stream_input=False):
522
  """
523
-
524
  Args:
525
  data:
526
  input_embeddings:
@@ -576,14 +601,21 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
576
 
577
  def forward(self, data, **kwargs):
578
  vllm_embedding, vision_hidden_states = self.get_vllm_embedding(data)
579
- vllm_embedding = self.get_omni_embedding(
580
- data, input_embeddings=vllm_embedding, chunk_length=self.config.audio_chunk_length
581
- )
 
 
582
 
583
  position_ids = data["position_ids"]
584
  if position_ids.dtype != torch.int64:
585
  position_ids = position_ids.long()
586
 
 
 
 
 
 
587
  return self.llm(input_ids=None, position_ids=position_ids, inputs_embeds=vllm_embedding, **kwargs)
588
 
589
  def _decode(self, inputs_embeds, tokenizer, attention_mask, **kwargs):
@@ -627,6 +659,93 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
627
  result_text.append(tokenizer.decode(result))
628
  return result_text
629
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
630
  def generate(
631
  self,
632
  input_ids=None,
@@ -697,7 +816,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
697
  omni_input=False,
698
  max_slice_nums=None,
699
  use_image_id=None,
700
- use_tts=False,
701
  generate_audio=False,
702
  return_spk_embed=False,
703
  return_dict=False,
@@ -721,7 +840,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
721
  omni_input: determine whether it is omni mode
722
  max_slice_nums: control the maximum number of image slices
723
  use_image_id: for video understanding or omni understanding, use_image_id should be False
724
- use_tts: if the msgs contain audio, use_tts should be True
725
  generate_audio: whether to generate audio output, only used when return_dict=True
726
  return_spk_embed: whether to return spk embedding, only used when return_dict=True
727
  return_dict: whether to return dict
@@ -798,12 +917,12 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
798
  for c in content:
799
  if isinstance(c, Image.Image):
800
  images.append(c)
801
- cur_msgs.append("<image>./</image>")
802
  elif isinstance(c, np.ndarray): # audio
803
  audios.append(c)
804
  audio_parts.append(i)
805
- cur_msgs.append("<audio>./</audio>")
806
- use_tts = True
807
  elif isinstance(c, str):
808
  cur_msgs.append(c)
809
  if omni_input:
@@ -816,7 +935,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
816
  copy_msgs,
817
  tokenize=False,
818
  add_generation_prompt=True,
819
- chat_template=self.default_tts_chat_template if use_tts else None,
820
  )
821
  )
822
  input_images_list.append(images)
@@ -886,13 +1005,18 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
886
  else:
887
  answer = res[0]
888
 
889
- if use_tts and generate_audio:
890
  mel_spec = self._generate_mel_spec(inputs, outputs, answer)
891
  wav_numpy, sr = self.decode_mel_to_audio(mel_spec, output_audio_path)
892
 
893
  if return_spk_embed:
894
  spk_embeds = self._get_last_spk_embeds(inputs, outputs)
895
 
 
 
 
 
 
896
  if return_dict:
897
  return OmniOutput(text=answer, spk_embeds=spk_embeds, audio_wav=wav_numpy, sampling_rate=sr)
898
  else:
@@ -904,6 +1028,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
904
  session_id,
905
  msgs,
906
  tokenizer,
 
907
  max_slice_nums=None,
908
  ls_temperature=1.0,
909
  **kwargs,
@@ -933,26 +1058,27 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
933
  for j, c in enumerate(content):
934
  if isinstance(c, Image.Image):
935
  images.append(c)
936
- cur_msgs.append("<image>./</image>")
937
  elif isinstance(c, np.ndarray): # audio
938
  audios.append(c)
939
- cur_msgs.append("<audio>./</audio>")
940
  elif isinstance(c, str):
941
  cur_msgs.append(c)
942
  else:
943
  logger.error("Invalid content type:", c)
944
 
 
945
  if not self.is_first and self.new_user_msg and msg["role"] == "user": # new user add im_start
946
  if self.llm_generated:
947
  if self.llm_generate_completed:
948
- msg["content"] = "<|im_end|>\n<|im_start|>user\n" + "".join(cur_msgs)
949
  else: # break llm gen, add tts_eos
950
- msg["content"] = "<|tts_eos|><|im_end|>\n<|im_start|>user\n" + "".join(cur_msgs)
951
  else:
952
- msg["content"] = "<|im_start|>user\n" + "".join(cur_msgs)
953
  self.new_user_msg = False
954
  else:
955
- msg["content"] = "".join(cur_msgs)
956
 
957
  if msg["role"] in ["system", "assistant"]:
958
  self.new_user_msg = True
@@ -960,11 +1086,9 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
960
 
961
  if self.is_first:
962
  # init pask_key_values
963
- logger.debug(f"new session_id: {session_id}, reset kv cache")
 
964
  self.session_id = session_id
965
- self.llm_past_key_values = None # llm kv cache
966
- self.new_user_msg = True
967
- self.audio_past_key_values = None # apm kv cache
968
 
969
  prompt = tokenizer.apply_chat_template(
970
  copy_msgs, tokenize=False, add_generation_prompt=False, chat_template=self.default_tts_chat_template
@@ -1015,14 +1139,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1015
  return_dict=True,
1016
  )
1017
  self.llm_past_key_values = outputs["past_key_values"]
1018
-
1019
- listen_id = tokenizer.convert_tokens_to_ids("<|listen|>")
1020
- speak_id = tokenizer.convert_tokens_to_ids("<|speak|>")
1021
- listen_speak_score = torch.Tensor([outputs["logits"][0, -1, listen_id], outputs["logits"][0, -1, speak_id]])
1022
- listen_speak_score = F.softmax(listen_speak_score / ls_temperature, dim=0).numpy()
1023
- self.speak_score = [float(listen_speak_score[1])]
1024
-
1025
- return self.speak_score
1026
 
1027
  @torch.inference_mode()
1028
  def streaming_generate(
@@ -1032,7 +1149,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1032
  max_new_tokens=512,
1033
  min_new_tokens=0,
1034
  sampling=True,
1035
- use_tts=True,
1036
  enable_regenerate=False,
1037
  **kwargs,
1038
  ):
@@ -1079,7 +1196,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1079
  generation_config["max_new_tokens"] = max_new_tokens
1080
  streamer = self.llm_generate_chunk(input_ids, attention_mask, tokenizer, terminators, generation_config)
1081
 
1082
- if use_tts:
1083
  result = self._generate_mel_spec_audio_streaming(
1084
  spk_bounds, streamer, output_chunk_size=25, enable_regenerate=enable_regenerate
1085
  )
@@ -1323,6 +1440,10 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1323
  return mel_spec
1324
 
1325
  def _linear_overlap_add2_wav(self, frames: List[torch.Tensor], overlap: int):
 
 
 
 
1326
  assert len(frames) == 2
1327
  device = frames[0].device
1328
  dtype = frames[0].dtype
@@ -1569,7 +1690,8 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1569
  prev_wav = wav_np[len(prev_wav) :]
1570
  cur_text = gen_text_raw[prev_text_len:]
1571
  prev_text_len = len(gen_text_raw)
1572
- yield wav_y, sr, cur_text
 
1573
  else:
1574
  prev_wav = wav_np
1575
  else:
@@ -1580,7 +1702,8 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1580
  ) # tts_hop256*2
1581
  cur_text = gen_text_raw[prev_text_len:]
1582
  prev_text_len = len(gen_text_raw)
1583
- yield wav_np, sr, cur_text
 
1584
  else:
1585
  prev_wav = wav_np
1586
 
@@ -1678,7 +1801,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1678
  prev_wav = wav_np[len(prev_wav) :]
1679
  cur_text = gen_text_raw[prev_text_len:]
1680
  prev_text_len = len(gen_text_raw)
1681
- yield wav_y, sr, cur_text
1682
  else:
1683
  prev_wav = wav_np
1684
  else:
@@ -1689,7 +1812,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1689
  ) # tts_hop256*2
1690
  cur_text = gen_text_raw[prev_text_len:]
1691
  prev_text_len = len(gen_text_raw)
1692
- yield wav_np, sr, cur_text
1693
  else:
1694
  prev_wav = wav_np
1695
 
@@ -1703,7 +1826,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1703
 
1704
  if prev_wav is not None:
1705
  cur_text = gen_text_raw[prev_text_len:]
1706
- yield prev_wav, sr, cur_text # yield last chunk wav without smooth
1707
 
1708
  if new_segment_gen and not stop:
1709
  logger.debug(
@@ -1737,6 +1860,7 @@ class MiniCPMO(MiniCPMOPreTrainedModel):
1737
  return wav_numpy, sr
1738
 
1739
 
 
1740
  class MiniCPMWhisperEncoderLayer(nn.Module):
1741
  def __init__(self, config: WhisperConfig, layer_idx: int = None):
1742
  super().__init__()
@@ -1765,6 +1889,24 @@ class MiniCPMWhisperEncoderLayer(nn.Module):
1765
  past_key_values: Optional[EncoderDecoderCache] = None,
1766
  use_cache: Optional[bool] = False,
1767
  ) -> torch.Tensor:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1768
  residual = hidden_states
1769
  hidden_states = self.self_attn_layer_norm(hidden_states)
1770
  hidden_states, attn_weights, past_key_values = self.self_attn(
@@ -1802,6 +1944,7 @@ class MiniCPMWhisperEncoderLayer(nn.Module):
1802
  return outputs
1803
 
1804
 
 
1805
  class MiniCPMWhisperEncoder(WhisperEncoder):
1806
 
1807
  def __init__(self, config: WhisperConfig):
@@ -1821,6 +1964,107 @@ class MiniCPMWhisperEncoder(WhisperEncoder):
1821
  past_key_values: Optional[EncoderDecoderCache] = None,
1822
  use_cache: Optional[bool] = None,
1823
  ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1824
  output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1825
  output_hidden_states = (
1826
  output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
@@ -1935,7 +2179,7 @@ class MiniCPMWhisperEncoder(WhisperEncoder):
1935
  )
1936
 
1937
 
1938
- # dvae module
1939
  class ConvNeXtBlock(nn.Module):
1940
  def __init__(
1941
  self,
@@ -1989,6 +2233,7 @@ class ConvNeXtBlock(nn.Module):
1989
  return x
1990
 
1991
 
 
1992
  class GFSQ(nn.Module):
1993
  def __init__(
1994
  self,
@@ -2031,6 +2276,7 @@ class GFSQ(nn.Module):
2031
  return ind.transpose_(1, 2) if self.transpose else ind
2032
 
2033
 
 
2034
  class DVAEDecoder(nn.Module):
2035
  def __init__(
2036
  self,
@@ -2075,6 +2321,7 @@ class DVAEDecoder(nn.Module):
2075
  return x
2076
 
2077
 
 
2078
  class DVAE(nn.Module):
2079
  def __init__(
2080
  self,
@@ -2153,7 +2400,6 @@ class DVAE(nn.Module):
2153
  return torch.mul(dec_out, self.coef, out=dec_out)
2154
 
2155
 
2156
- # tts module
2157
  def apply_spk_emb(
2158
  input_ids: torch.Tensor = None,
2159
  spk_emb: torch.Tensor = None,
@@ -2162,7 +2408,7 @@ def apply_spk_emb(
2162
  num_spk_embs: int = 1,
2163
  ):
2164
  """
2165
- Replace consecutive speaker embedding placeholders in input_embeds with pre-prepared speaker embeddings. This is an in-place replacement, no new tensor is created, so no value is returned.
2166
 
2167
  Args:
2168
  input_ids (torch.Tensor): Input ID tensor, shape [batch_size, seq_len_max]
@@ -2201,7 +2447,7 @@ def make_streaming_chunk_mask_generation(
2201
  use_spk_emb: bool = True,
2202
  ) -> torch.Tensor:
2203
  """
2204
- Determine which `text` tokens the model can attend to when generating each chunk of `audio` tokens.
2205
 
2206
  This function creates a mask that allows the model to attend to a specific chunk of text
2207
  tokens when generating each chunk of audio tokens, enabling streaming TTS generation.
@@ -2258,6 +2504,7 @@ def make_streaming_chunk_mask_generation(
2258
  return causal_mask
2259
 
2260
 
 
2261
  class CustomRepetitionPenaltyLogitsProcessorRepeat:
2262
  def __init__(self, penalty: float, max_input_ids: int, past_window: int):
2263
  if not isinstance(penalty, float) or not (penalty > 0):
@@ -2316,6 +2563,97 @@ class MultiModalProjector(nn.Module):
2316
 
2317
 
2318
  class ConditionalChatTTS(PreTrainedModel):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2319
  config_class = ConditionalChatTTSConfig
2320
 
2321
  def __init__(self, config: ConditionalChatTTSConfig):
@@ -2373,19 +2711,16 @@ class ConditionalChatTTS(PreTrainedModel):
2373
  self.model = model
2374
 
2375
  @torch.inference_mode()
2376
- def prepare_inputs_embeds(
2377
  self,
2378
  input_ids: torch.Tensor,
2379
  lm_spk_emb_last_hidden_states: Optional[torch.Tensor] = None,
2380
- lm_last_hidden_states: Optional[torch.Tensor] = None,
2381
  ):
2382
- """Prepare inputs_embeds for the model in inference mode,
2383
- encode input_ids to embeddings, then merge lm_spk_emb_last_hidden_states, and lm_last_hidden_states.
2384
 
2385
  Args:
2386
  input_ids (torch.Tensor): Input token IDs.
2387
  lm_spk_emb_last_hidden_states (Optional[torch.Tensor], optional): Last hidden states of speaker embeddings from the language model. Defaults to None.
2388
- lm_last_hidden_states (Optional[torch.Tensor], optional): Last hidden states from the language model. Defaults to None.
2389
 
2390
  Raises:
2391
  NotImplementedError: If speaker embedding is not used and language model hidden states are not implemented.
@@ -2415,8 +2750,6 @@ class ConditionalChatTTS(PreTrainedModel):
2415
  num_spk_embs=self.num_spk_embs,
2416
  )
2417
  else:
2418
- assert lm_last_hidden_states is not None
2419
- # TODO: Add projected language model hidden states to tts embedding space
2420
  raise NotImplementedError
2421
 
2422
  return inputs_embeds
@@ -2428,10 +2761,9 @@ class ConditionalChatTTS(PreTrainedModel):
2428
  position_ids: torch.LongTensor,
2429
  past_key_values: List[Tuple[torch.Tensor, torch.Tensor]],
2430
  lm_spk_emb_last_hidden_states: Optional[torch.Tensor] = None,
2431
- lm_last_hidden_states: Optional[torch.Tensor] = None,
2432
  ):
2433
  """Prefill a chunk of new text tokens in streaming setting.
2434
- Specifically speaking, update `past_key_values` using new text tokens.
2435
 
2436
  Args:
2437
  input_ids (Tensor): Tensor of shape [batch_size, seq_len]
@@ -2445,11 +2777,10 @@ class ConditionalChatTTS(PreTrainedModel):
2445
  assert input_ids.shape[0] == 1
2446
  assert past_key_values is not None
2447
 
2448
- # Merge text and embeddings from language model
2449
- inputs_embeds = self.prepare_inputs_embeds(
2450
  input_ids=input_ids,
2451
  lm_spk_emb_last_hidden_states=lm_spk_emb_last_hidden_states,
2452
- lm_last_hidden_states=lm_last_hidden_states,
2453
  )
2454
 
2455
  # Clone KV Cache
@@ -2476,7 +2807,7 @@ class ConditionalChatTTS(PreTrainedModel):
2476
  # Get model updated KV Cache
2477
  past_key_values_for_prefill_updated = outputs_prefill.past_key_values
2478
 
2479
- # Update generated KV Cache to input past_key_values
2480
  for layer_idx in range(len(past_key_values)):
2481
  # Update keys
2482
  past_key_values[layer_idx][0][:, :, position_ids[:, 0] : position_ids[:, -1] + 1, :] = (
@@ -2504,7 +2835,9 @@ class ConditionalChatTTS(PreTrainedModel):
2504
  streaming_tts_text_mask=None,
2505
  add_audio_bos: bool = True,
2506
  ):
2507
- """
 
 
2508
  Args:
2509
  input_ids (torch.Tensor): (1, seq_len, num_vq) Audio input token ids.
2510
  past_key_values (List[Tuple[torch.Tensor, torch.Tensor]]): Past key values for attention mechanism.
@@ -2534,7 +2867,7 @@ class ConditionalChatTTS(PreTrainedModel):
2534
  streaming_tts_text_mask=streaming_tts_text_mask,
2535
  streaming_reserved_length=self.streaming_text_reserved_len,
2536
  streaming_text_chunk_size=self.streaming_text_chunk_size,
2537
- ) # [1, 1, 1, past_key_values_length + input_le]
2538
 
2539
  # Model forward
2540
  outputs: BaseModelOutputWithPast = self.model(
@@ -2564,57 +2897,12 @@ class ConditionalChatTTS(PreTrainedModel):
2564
  logits_processors: List[CustomRepetitionPenaltyLogitsProcessorRepeat] = [],
2565
  show_tqdm=False,
2566
  ):
2567
- """Generate audio codes in streaming setting.
2568
  Specifically speaking, generate audio codes when not all text tokens are prefilled.
2569
 
2570
- Usage:
2571
- Always pass an non-empty `past_key_values` to the function. The function does not do `prefill` by itself. It relies on `prefill_text` method to provide a valid `past_key_values`.
2572
 
2573
- 1. Create an empty `past_key_values` with
2574
- ```python
2575
- initial_kv_cache_length = 1 + self.num_spk_embs + self.streaming_text_reserved_len
2576
- dtype = model.emb_text.weight.dtype
2577
- device = model.emb_text.weight.device
2578
- past_key_values = [
2579
- (
2580
- torch.zeros(1, model.config.num_attention_heads, initial_kv_cache_length, model.config.hidden_size // model.config.num_attention_heads, dtype=dtype, device=device),
2581
- torch.zeros(1, model.config.num_attention_heads, initial_kv_cache_length, model.config.hidden_size // model.config.num_attention_heads, dtype=dtype, device=device)
2582
- )
2583
- for _ in range(model.config.num_hidden_layers)
2584
- ]
2585
-
2586
- 2. Prefill some text tokens using `prefill_text` method.
2587
- ```python
2588
- outputs = llm.generate(**kwargs)
2589
- lm_spk_emb_last_hidden_states or lm_last_hidden_states = extract(outputs.last_hidden_states)
2590
- input_ids = tts_tokenizer.encode(llm_tokenizer.decode(llm_tokens))
2591
- position_ids = torch.arange(begin, end, dtype=torch.long, device=device)
2592
- past_key_values = self.prefill_text(
2593
- input_ids=input_ids,
2594
- position_ids=position_ids,
2595
- past_key_values=past_key_values,
2596
- lm_spk_emb_last_hidden_states=lm_spk_emb_last_hidden_states,
2597
- lm_last_hidden_states=lm_last_hidden_states,
2598
- )
2599
- ```
2600
-
2601
- 3. Generate audio codes using `generate` method.
2602
- ```python
2603
- # initialize input_ids, this should be only done `once`
2604
- condition_length = 1 + model.num_spk_embs * model.use_speaker_embedding + model.streaming_text_reserved_len + 1
2605
- input_ids = torch.zeros(batch_size=1, condition_length, self.num_vq)
2606
-
2607
- outputs = self.generate(
2608
- input_ids=input_ids,
2609
- past_key_values=past_key_values,
2610
- )
2611
-
2612
- # update past_key_values and input_ids
2613
- past_key_values = outputs.past_key_values
2614
- input_ids = outputs.input_ids
2615
- ```
2616
-
2617
- 4. Repeat step 2 and 3.
2618
 
2619
  Args:
2620
  input_ids (torch.Tensor): Input token ids.
@@ -2626,8 +2914,7 @@ class ConditionalChatTTS(PreTrainedModel):
2626
  logits_warpers (List[LogitsWarper], optional): List of logits warpers. Defaults to [].
2627
  logits_processors (List[CustomRepetitionPenaltyLogitsProcessorRepeat], optional): List of logits processors. Defaults to [].
2628
  show_tqdm (bool, optional): Whether to show progress bar. Defaults to True.
2629
- Raises:
2630
- NotImplementedError: _description_
2631
  Returns:
2632
  GenerationOutputs: Generation outputs.
2633
  """
@@ -2655,7 +2942,7 @@ class ConditionalChatTTS(PreTrainedModel):
2655
  device=input_ids.device,
2656
  )
2657
 
2658
- # Copy existing input_ids to input_ids_buf
2659
  input_ids_buf.narrow(1, 0, progress).copy_(input_ids)
2660
 
2661
  del input_ids
@@ -2674,19 +2961,22 @@ class ConditionalChatTTS(PreTrainedModel):
2674
  for i in range(max_new_token):
2675
  # Prepare generation inputs
2676
  audio_bos = False
2677
- # If this is the first audio token, the case is special
 
2678
  if progress == condition_length:
2679
  audio_bos = True
2680
 
 
 
 
 
2681
  if audio_bos:
2682
- # Generate the first token, activate the model with `self.audio_bos_token_id`, the model will predict a new audio token.
2683
- assert progress == (past_key_values[0][0].shape[2] + 1)
2684
  narrowed_input_ids = torch.tensor([[self.audio_bos_token_id]], dtype=torch.long, device=self.device)
2685
  inputs_embeds = self.emb_text(narrowed_input_ids)
2686
  del narrowed_input_ids
2687
  else:
2688
- # Generate the following audio tokens, it is applicable to all other cases, including second and the following calling of `generate`
2689
- assert progress == (past_key_values[0][0].shape[2] + 1)
2690
  narrowed_input_ids = input_ids.narrow(dim=1, start=input_ids.shape[1] - 1, length=1)
2691
  code_emb = [self.emb_code[i](narrowed_input_ids[:, :, i]) for i in range(self.num_vq)]
2692
  inputs_embeds = torch.stack(code_emb, 3).sum(3)
@@ -2696,6 +2986,8 @@ class ConditionalChatTTS(PreTrainedModel):
2696
  ).unsqueeze(0)
2697
 
2698
  cache_position = position_ids.clone()
 
 
2699
  causal_mask = make_streaming_chunk_mask_generation(
2700
  inputs_embeds=inputs_embeds,
2701
  past_seen_tokens=past_key_values[0][0].shape[2],
@@ -2787,7 +3079,7 @@ class ConditionalChatTTS(PreTrainedModel):
2787
  finish.logical_or_(finish_or)
2788
 
2789
  del finish_or
2790
- # 新的 `token` 存入 `input_ids_buf`
2791
  input_ids_buf.narrow(1, progress, 1).copy_(idx_next.unsqueeze_(1))
2792
 
2793
  if i == 0 and finish.any():
@@ -2831,8 +3123,18 @@ class ConditionalChatTTS(PreTrainedModel):
2831
  def decode_to_mel_specs(
2832
  self,
2833
  result_list: List[torch.Tensor],
2834
- use_decoder: bool = False,
2835
  ):
 
 
 
 
 
 
 
 
 
 
 
2836
  decoder = self.dvae
2837
  max_x_len = -1
2838
  if len(result_list) == 0:
@@ -2855,6 +3157,7 @@ class ConditionalChatTTS(PreTrainedModel):
2855
  return mel_specs
2856
 
2857
 
 
2858
  def gen_logits(
2859
  num_code: int,
2860
  top_P=0.7,
 
121
 
122
  self.processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True)
123
 
124
+ self.terminators = ["<|im_end|>", "<|endoftext|>"]
125
 
126
  self.default_tts_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<|spk_bos|><|spk|><|spk_eos|><|tts_bos|>' }}{% endif %}"
127
  self.force_no_stop = False
128
 
129
  # for stream api
130
+ self.reset_session()
131
+
132
+ def reset_session(self):
133
  self.session_id = None
134
  self.new_user_msg = True
135
  self.llm_generated = False
136
  self.llm_generate_completed = False
137
  self.llm_past_key_values = None
138
  self.audio_past_key_values = None # apm kv cache
 
139
 
140
  def init_tts(
141
  self,
 
403
  return vllm_embedding, vision_hidden_states
404
 
405
  def get_audio_embedding_streaming(self, data):
406
+ r"""
407
+ Extract audio embeddings in a streaming manner using cached key-value pairs.
408
+
409
+ This method processes incoming audio features incrementally and stores/updates `past_key_values`
410
+ for faster inference on subsequent audio frames. It only supports batch_size=1 and is intended
411
+ for streaming scenarios.
412
+
413
+ Args:
414
+ data (dict):
415
+ - **"audio_features"** (`torch.FloatTensor`): Input mel-spectrograms of shape `(batch_size, 80, frames)`.
416
+ - **"audio_feature_lens"** (List[List[int]]): Lengths of each audio segment for each item in the batch.
417
+
418
+ Returns:
419
+ List[List[torch.Tensor]]: audio embeddings
420
+ """
421
  wavforms = data.get("audio_features", []) # (bs, 80, frames) or [], multi audios need filled in advance
422
  audio_feature_lens_raw = data.get("audio_feature_lens", []) # list, [[x1, x2], [y1], [z1]]
423
 
 
464
  return []
465
 
466
  def get_audio_embedding(self, data, chunk_length=-1):
467
+ r"""
468
+ Extract full audio embeddings with optional chunk-based attention.
469
+
470
+ This method computes embeddings for all audio frames at once, either using full attention (when
471
+ `chunk_length` is -1) or chunk-based attention (when `chunk_length` is a positive number). It does
472
+ not use key-value caching and is suitable for non-streaming inference.
473
+
474
  Args:
475
+ data (dict):
476
+ - **"audio_features"** (`torch.FloatTensor`): Input mel-spectrograms of shape `(batch_size, 80, frames)`.
477
+ - **"audio_feature_lens"** (List[List[int]]): Lengths of each audio segment for each item in the batch.
478
+ chunk_length (int, optional): Determines whether to use full attention (-1) or chunk-based
479
+ attention (>0) during embedding computation.
480
+
481
  Returns:
482
+ List[List[torch.Tensor]]: audio embeddings
483
  """
484
+
485
  wavforms = data.get("audio_features", []) # (bs, 80, frames) or [], multi audios need filled in advance
486
  audio_feature_lens_raw = data.get("audio_feature_lens", []) # list, [[x1, x2], [y1], [z1]]
487
 
 
546
 
547
  def get_omni_embedding(self, data, input_embeddings, chunk_length=-1, stream_input=False):
548
  """
 
549
  Args:
550
  data:
551
  input_embeddings:
 
601
 
602
  def forward(self, data, **kwargs):
603
  vllm_embedding, vision_hidden_states = self.get_vllm_embedding(data)
604
+
605
+ if self.config.init_audio:
606
+ vllm_embedding = self.get_omni_embedding(
607
+ data, input_embeddings=vllm_embedding, chunk_length=self.config.audio_chunk_length
608
+ )
609
 
610
  position_ids = data["position_ids"]
611
  if position_ids.dtype != torch.int64:
612
  position_ids = position_ids.long()
613
 
614
+ # compatible with llama factory
615
+ for key in ["input_ids", "inputs_embeds", "position_ids"]:
616
+ if key in kwargs:
617
+ del kwargs[key]
618
+
619
  return self.llm(input_ids=None, position_ids=position_ids, inputs_embeds=vllm_embedding, **kwargs)
620
 
621
  def _decode(self, inputs_embeds, tokenizer, attention_mask, **kwargs):
 
659
  result_text.append(tokenizer.decode(result))
660
  return result_text
661
 
662
+ def get_sys_prompt(self, ref_audio=None, mode="default", language="zh"):
663
+ """
664
+ Choose different system prompts according to different tasks
665
+ Args:
666
+ ref_audio: if ref_audio is not None, will use the voice cloning prompts, and the voice
667
+ generated by the model will refer to the timbre of ref audio
668
+ mode:
669
+ "default": default system prompt and not refer to any task
670
+ "omni": input video and audio simultaneously
671
+ "audio_assistant": Default voice-only mode, the model will use the ref_audio's voice to reply user as a helpful assistant.
672
+ "audio_roleplay": Roleplay voice-only model, the model will use the ref_audio's voice to reply, and also role-play the character based on the audio prompt.
673
+ "voice_cloning": TTS mode, the model will clone the voice of ref_audio
674
+ language: prompts language, the model has the ability to automatically select the response language
675
+ based on the question language
676
+ Returns:
677
+
678
+ """
679
+ if ref_audio is not None:
680
+ assert isinstance(ref_audio, np.ndarray), "ref_audio error"
681
+ if mode == "omni":
682
+ if language == "zh":
683
+ sys_prompt = "你是一个AI助手。你能接受视频,音频和文本输入并输出语音和文本。"
684
+ vc_prompt_prefix = sys_prompt + "模仿输入音频中的声音特征。"
685
+ vc_prompt_suffix = "作为助手,你将使用这种声音风格说话。"
686
+ else:
687
+ sys_prompt = "You are a helpful assistant. You can accept video, audio and text input and output voice and text. "
688
+ vc_prompt_prefix = sys_prompt + "Clone the voice in the provided audio prompt."
689
+ vc_prompt_suffix = "As an assistant, you will speak using this voice style."
690
+
691
+ if ref_audio is not None:
692
+ sys_msgs = {"role": "user", "content": [vc_prompt_prefix, ref_audio, vc_prompt_suffix]}
693
+
694
+ else:
695
+ sys_msgs = {"role": "user", "content": [sys_prompt]}
696
+
697
+ return sys_msgs
698
+ elif mode == "audio_assistant":
699
+ if language == "zh":
700
+ vc_prompt_prefix = "模仿输入音频中的声音特征。"
701
+ vc_prompt_suffix = "作为助手,你将使用这种声音风格说话。"
702
+ else:
703
+ vc_prompt_prefix = "Clone the voice in the provided audio prompt."
704
+ vc_prompt_suffix = "As an assistant, you will speak using this voice style."
705
+
706
+ if ref_audio is not None:
707
+ sys_msgs = {"role": "user", "content": [vc_prompt_prefix, ref_audio, vc_prompt_suffix]}
708
+
709
+ else:
710
+ logger.warning(
711
+ "Warning: ref_audio is None, speech generation will be performed based on the default voice."
712
+ )
713
+ sys_msgs = {"role": "user", "content": ["Use the <reserved_53> voice.", vc_prompt_suffix]}
714
+
715
+ return sys_msgs
716
+ elif mode == "audio_roleplay":
717
+ if language == "zh":
718
+ vc_prompt_prefix = "模仿输入音频中的声音特征。"
719
+ vc_prompt_suffix = "假装你是上述音频中的人物,与我进行对话。"
720
+ else:
721
+ vc_prompt_prefix = "Clone the voice in the provided audio prompt."
722
+ vc_prompt_suffix = "Try to role-play the character based on the audio prompt above."
723
+
724
+ if ref_audio is not None:
725
+ sys_msgs = {"role": "user", "content": [vc_prompt_prefix, ref_audio, vc_prompt_suffix]}
726
+ else:
727
+ print("Warning: ref_audio is None, speech generation will be performed based on the default voice.")
728
+ sys_msgs = {"role": "user", "content": ["Use the <reserved_53> voice.", vc_prompt_suffix]}
729
+
730
+ return sys_msgs
731
+ elif mode == "voice_cloning":
732
+ if language == "zh":
733
+ vc_prompt_prefix = "模仿输入音频中的声音特征。"
734
+ else:
735
+ vc_prompt_prefix = "Clone the voice in the provided audio prompt."
736
+
737
+ if ref_audio is not None:
738
+ sys_msgs = {"role": "user", "content": [vc_prompt_prefix, ref_audio]}
739
+ else:
740
+ raise ValueError("ref_audio con't be None in voice_cloning mode.")
741
+
742
+ return sys_msgs
743
+ else:
744
+ sys_prompt = "You are a helpful assistant. You can accept audio and text input and output voice and text."
745
+ sys_msgs = {"role": "user", "content": [sys_prompt]}
746
+
747
+ return sys_msgs
748
+
749
  def generate(
750
  self,
751
  input_ids=None,
 
816
  omni_input=False,
817
  max_slice_nums=None,
818
  use_image_id=None,
819
+ use_tts_template=False,
820
  generate_audio=False,
821
  return_spk_embed=False,
822
  return_dict=False,
 
840
  omni_input: determine whether it is omni mode
841
  max_slice_nums: control the maximum number of image slices
842
  use_image_id: for video understanding or omni understanding, use_image_id should be False
843
+ use_tts_template: if the msgs contain audio, use_tts_template should be True
844
  generate_audio: whether to generate audio output, only used when return_dict=True
845
  return_spk_embed: whether to return spk embedding, only used when return_dict=True
846
  return_dict: whether to return dict
 
917
  for c in content:
918
  if isinstance(c, Image.Image):
919
  images.append(c)
920
+ cur_msgs.append("(<image>./</image>)")
921
  elif isinstance(c, np.ndarray): # audio
922
  audios.append(c)
923
  audio_parts.append(i)
924
+ cur_msgs.append("(<audio>./</audio>)")
925
+ use_tts_template = True
926
  elif isinstance(c, str):
927
  cur_msgs.append(c)
928
  if omni_input:
 
935
  copy_msgs,
936
  tokenize=False,
937
  add_generation_prompt=True,
938
+ chat_template=self.default_tts_chat_template if use_tts_template else None,
939
  )
940
  )
941
  input_images_list.append(images)
 
1005
  else:
1006
  answer = res[0]
1007
 
1008
+ if use_tts_template and generate_audio:
1009
  mel_spec = self._generate_mel_spec(inputs, outputs, answer)
1010
  wav_numpy, sr = self.decode_mel_to_audio(mel_spec, output_audio_path)
1011
 
1012
  if return_spk_embed:
1013
  spk_embeds = self._get_last_spk_embeds(inputs, outputs)
1014
 
1015
+ if isinstance(answer, list):
1016
+ answer = [i.replace(tokenizer.tts_end, "") for i in answer]
1017
+ else:
1018
+ answer = answer.replace(tokenizer.tts_end, "")
1019
+
1020
  if return_dict:
1021
  return OmniOutput(text=answer, spk_embeds=spk_embeds, audio_wav=wav_numpy, sampling_rate=sr)
1022
  else:
 
1028
  session_id,
1029
  msgs,
1030
  tokenizer,
1031
+ omni_input=True,
1032
  max_slice_nums=None,
1033
  ls_temperature=1.0,
1034
  **kwargs,
 
1058
  for j, c in enumerate(content):
1059
  if isinstance(c, Image.Image):
1060
  images.append(c)
1061
+ cur_msgs.append("(<image>./</image>)")
1062
  elif isinstance(c, np.ndarray): # audio
1063
  audios.append(c)
1064
+ cur_msgs.append("(<audio>./</audio>)")
1065
  elif isinstance(c, str):
1066
  cur_msgs.append(c)
1067
  else:
1068
  logger.error("Invalid content type:", c)
1069
 
1070
+ cur_contents = "".join(cur_msgs) if omni_input else "\n".join(omni_input)
1071
  if not self.is_first and self.new_user_msg and msg["role"] == "user": # new user add im_start
1072
  if self.llm_generated:
1073
  if self.llm_generate_completed:
1074
+ msg["content"] = "<|im_end|>\n<|im_start|>user\n" + cur_contents
1075
  else: # break llm gen, add tts_eos
1076
+ msg["content"] = "<|tts_eos|><|im_end|>\n<|im_start|>user\n" + cur_contents
1077
  else:
1078
+ msg["content"] = "<|im_start|>user\n" + cur_contents
1079
  self.new_user_msg = False
1080
  else:
1081
+ msg["content"] = cur_contents
1082
 
1083
  if msg["role"] in ["system", "assistant"]:
1084
  self.new_user_msg = True
 
1086
 
1087
  if self.is_first:
1088
  # init pask_key_values
1089
+ logger.info(f"new session_id: {session_id}, reset kv cache")
1090
+ self.reset_session()
1091
  self.session_id = session_id
 
 
 
1092
 
1093
  prompt = tokenizer.apply_chat_template(
1094
  copy_msgs, tokenize=False, add_generation_prompt=False, chat_template=self.default_tts_chat_template
 
1139
  return_dict=True,
1140
  )
1141
  self.llm_past_key_values = outputs["past_key_values"]
1142
+ return
 
 
 
 
 
 
 
1143
 
1144
  @torch.inference_mode()
1145
  def streaming_generate(
 
1149
  max_new_tokens=512,
1150
  min_new_tokens=0,
1151
  sampling=True,
1152
+ generate_audio=True,
1153
  enable_regenerate=False,
1154
  **kwargs,
1155
  ):
 
1196
  generation_config["max_new_tokens"] = max_new_tokens
1197
  streamer = self.llm_generate_chunk(input_ids, attention_mask, tokenizer, terminators, generation_config)
1198
 
1199
+ if generate_audio:
1200
  result = self._generate_mel_spec_audio_streaming(
1201
  spk_bounds, streamer, output_chunk_size=25, enable_regenerate=enable_regenerate
1202
  )
 
1440
  return mel_spec
1441
 
1442
  def _linear_overlap_add2_wav(self, frames: List[torch.Tensor], overlap: int):
1443
+ """
1444
+ Merge two audio waveforms with smooth in streaming audio generation.
1445
+ Borrowed some codes from `https://github.com/huggingface/transformers/blob/main/src/transformers/models/encodec/modeling_encodec.py`
1446
+ """
1447
  assert len(frames) == 2
1448
  device = frames[0].device
1449
  dtype = frames[0].dtype
 
1690
  prev_wav = wav_np[len(prev_wav) :]
1691
  cur_text = gen_text_raw[prev_text_len:]
1692
  prev_text_len = len(gen_text_raw)
1693
+ yield OmniOutput(text=cur_text, audio_wav=wav_y, sampling_rate=sr)
1694
+
1695
  else:
1696
  prev_wav = wav_np
1697
  else:
 
1702
  ) # tts_hop256*2
1703
  cur_text = gen_text_raw[prev_text_len:]
1704
  prev_text_len = len(gen_text_raw)
1705
+ yield OmniOutput(text=cur_text, audio_wav=wav_np, sampling_rate=sr)
1706
+
1707
  else:
1708
  prev_wav = wav_np
1709
 
 
1801
  prev_wav = wav_np[len(prev_wav) :]
1802
  cur_text = gen_text_raw[prev_text_len:]
1803
  prev_text_len = len(gen_text_raw)
1804
+ yield OmniOutput(text=cur_text, audio_wav=wav_y, sampling_rate=sr)
1805
  else:
1806
  prev_wav = wav_np
1807
  else:
 
1812
  ) # tts_hop256*2
1813
  cur_text = gen_text_raw[prev_text_len:]
1814
  prev_text_len = len(gen_text_raw)
1815
+ yield OmniOutput(text=cur_text, audio_wav=wav_np, sampling_rate=sr)
1816
  else:
1817
  prev_wav = wav_np
1818
 
 
1826
 
1827
  if prev_wav is not None:
1828
  cur_text = gen_text_raw[prev_text_len:]
1829
+ yield OmniOutput(text=cur_text, audio_wav=prev_wav, sampling_rate=sr) # yield last chunk wav without smooth
1830
 
1831
  if new_segment_gen and not stop:
1832
  logger.debug(
 
1860
  return wav_numpy, sr
1861
 
1862
 
1863
+ # Copied from transformers.models.whisper.modeling_whisper.WhisperEncoderLayer and add use_cache for streaming inference
1864
  class MiniCPMWhisperEncoderLayer(nn.Module):
1865
  def __init__(self, config: WhisperConfig, layer_idx: int = None):
1866
  super().__init__()
 
1889
  past_key_values: Optional[EncoderDecoderCache] = None,
1890
  use_cache: Optional[bool] = False,
1891
  ) -> torch.Tensor:
1892
+ r"""
1893
+ Args:
1894
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, embed_dim)`):
1895
+ Hidden states to be fed into the encoder layer.
1896
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, 1, tgt_len, src_len)`):
1897
+ Attention mask where padding elements are indicated by large negative values.
1898
+ layer_head_mask (`torch.FloatTensor` of shape `(encoder_attention_heads,)`):
1899
+ Mask to nullify selected heads of the attention modules.
1900
+ output_attentions (`bool`, *optional*):
1901
+ Whether or not to return the attention weights.
1902
+ past_key_values (`EncoderDecoderCache`, *optional*):
1903
+ Past key-value pairs used for incremental decoding.
1904
+ use_cache (`bool`, *optional*):
1905
+ Whether or not to return updated `past_key_values` for caching.
1906
+
1907
+ Returns:
1908
+ A tuple of shape `(hidden_states, optional(attn_weights), optional(past_key_values))`.
1909
+ """
1910
  residual = hidden_states
1911
  hidden_states = self.self_attn_layer_norm(hidden_states)
1912
  hidden_states, attn_weights, past_key_values = self.self_attn(
 
1944
  return outputs
1945
 
1946
 
1947
+ # Copied from from transformers.models.whisper.modeling_whisper.WhisperEncoder and add use_cache for streaming inference
1948
  class MiniCPMWhisperEncoder(WhisperEncoder):
1949
 
1950
  def __init__(self, config: WhisperConfig):
 
1964
  past_key_values: Optional[EncoderDecoderCache] = None,
1965
  use_cache: Optional[bool] = None,
1966
  ):
1967
+ r"""
1968
+ Forward pass of the Whisper encoder.
1969
+
1970
+ Args:
1971
+ input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, sequence_length)`):
1972
+ Float values of log-mel features extracted from the raw audio waveform. Typically generated
1973
+ by a feature extractor (e.g., `WhisperFeatureExtractor`) that processes `.flac` or `.wav`
1974
+ files into padded 2D mel spectrogram frames. These features are projected via convolution layers
1975
+ (`conv1` and `conv2`) and then transformed into embeddings for the encoder.
1976
+
1977
+ attention_mask (`torch.Tensor`, *optional*):
1978
+ Not used by Whisper for masking `input_features`, but included for API compatibility with
1979
+ other models. If provided, it is simply ignored within the model. By default, Whisper
1980
+ effectively ignores silence in the input log-mel spectrogram.
1981
+
1982
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
1983
+ Mask to nullify selected attention heads. The elements should be either 1 or 0, where:
1984
+ - 1 indicates the head is **not masked**,
1985
+ - 0 indicates the head is **masked** (i.e., the attention head is dropped).
1986
+
1987
+ output_attentions (`bool`, *optional*):
1988
+ Whether or not to return the attention tensors of all encoder layers. If set to `True`, the
1989
+ returned tuple (or `BaseModelOutputWithPast`) will contain an additional element with
1990
+ attention weights for each encoder layer.
1991
+
1992
+ output_hidden_states (`bool`, *optional*):
1993
+ Whether or not to return the hidden states of all layers. If set to `True`, the returned
1994
+ tuple (or `BaseModelOutputWithPast`) will contain a tuple of hidden states, including the
1995
+ initial embedding output as well as the outputs of each layer.
1996
+
1997
+ return_dict (`bool`, *optional*):
1998
+ Whether or not to return a `BaseModelOutputWithPast` (a subclass of `ModelOutput`) instead
1999
+ of a plain tuple. If set to `True`, the output will be a `BaseModelOutputWithPast` object,
2000
+ otherwise it will be a tuple.
2001
+
2002
+ past_key_values (`EncoderDecoderCache`, *optional*):
2003
+ When using caching for faster inference, this is an object that stores the key-value pairs
2004
+ for attention states. If provided, the model will append new states to the existing cache
2005
+ and return the updated cache. This speeds up sequential decoding or chunked inference.
2006
+
2007
+ - If `past_key_values` is `None`, no past states are used or returned.
2008
+ - If `past_key_values` is not `None` and `use_cache=True`, the model will use the provided
2009
+ cache and return the updated cache (as `next_encoder_cache`).
2010
+
2011
+ use_cache (`bool`, *optional*):
2012
+ Whether or not the model should use caching (`past_key_values`) to speed up processing
2013
+ during inference. When set to `True`, the model will:
2014
+ - Inspect and use `past_key_values` if provided.
2015
+ - Return updated `past_key_values` (under the name `next_encoder_cache` in
2016
+ `BaseModelOutputWithPast`).
2017
+
2018
+ Returns:
2019
+ `BaseModelOutputWithPast` or `tuple` (depending on `return_dict`):
2020
+ If `return_dict=True`, a `BaseModelOutputWithPast` is returned, which contains:
2021
+ - **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
2022
+ The output of the final encoder layer.
2023
+ - **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned if `output_hidden_states=True`):
2024
+ Hidden states of the model at each layer (including the initial projection).
2025
+ - **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned if `output_attentions=True`):
2026
+ Attention weights from each encoder layer.
2027
+ - **past_key_values** (an object of type `EncoderDecoderCache` or `None`, *optional*):
2028
+ Updated cache of key-value pairs if `use_cache=True`.
2029
+
2030
+ If `return_dict=False`, a tuple is returned, where the format is:
2031
+ `(last_hidden_state, hidden_states, attentions)`, with `hidden_states` and `attentions`
2032
+ only present if their respective `output_*` arguments are set to `True`.
2033
+
2034
+ Example:
2035
+ >>> from transformers import AutoFeatureExtractor, WhisperConfig, WhisperForConditionalGeneration
2036
+ >>> import torch
2037
+
2038
+ >>> # Load a feature extractor and a Whisper model
2039
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-tiny.en")
2040
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
2041
+
2042
+ >>> # Assume you have audio (list of floats or numpy array) loaded from a file
2043
+ >>> # Then extract the mel features:
2044
+ >>> input_features = feature_extractor(audio, sampling_rate=16000, return_tensors="pt").input_features
2045
+
2046
+ >>> # Forward pass
2047
+ >>> outputs = model.encoder(
2048
+ ... input_features=input_features,
2049
+ ... output_hidden_states=True,
2050
+ ... output_attentions=True,
2051
+ ... use_cache=True
2052
+ ... )
2053
+
2054
+ >>> # Retrieve the last hidden state
2055
+ >>> last_hidden_state = outputs.last_hidden_state
2056
+ >>> print(last_hidden_state.shape)
2057
+ torch.Size([batch_size, seq_length, hidden_size])
2058
+
2059
+ >>> # Retrieve the intermediate hidden states if output_hidden_states=True
2060
+ >>> all_encoder_hidden_states = outputs.hidden_states
2061
+
2062
+ >>> # Retrieve attention weights if output_attentions=True
2063
+ >>> all_encoder_attentions = outputs.attentions
2064
+
2065
+ >>> # Retrieve updated past key values if use_cache=True
2066
+ >>> encoder_cache = outputs.past_key_values
2067
+ """
2068
  output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
2069
  output_hidden_states = (
2070
  output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
 
2179
  )
2180
 
2181
 
2182
+ # Borrowed from `https://github.com/2noise/ChatTTS/blob/main/ChatTTS/model/dvae.py`
2183
  class ConvNeXtBlock(nn.Module):
2184
  def __init__(
2185
  self,
 
2233
  return x
2234
 
2235
 
2236
+ # Borrowed from `https://github.com/2noise/ChatTTS/blob/main/ChatTTS/model/dvae.py`
2237
  class GFSQ(nn.Module):
2238
  def __init__(
2239
  self,
 
2276
  return ind.transpose_(1, 2) if self.transpose else ind
2277
 
2278
 
2279
+ # Borrowed from `https://github.com/2noise/ChatTTS/blob/main/ChatTTS/model/dvae.py`
2280
  class DVAEDecoder(nn.Module):
2281
  def __init__(
2282
  self,
 
2321
  return x
2322
 
2323
 
2324
+ # Borrowed from `https://github.com/2noise/ChatTTS/blob/main/ChatTTS/model/dvae.py`
2325
  class DVAE(nn.Module):
2326
  def __init__(
2327
  self,
 
2400
  return torch.mul(dec_out, self.coef, out=dec_out)
2401
 
2402
 
 
2403
  def apply_spk_emb(
2404
  input_ids: torch.Tensor = None,
2405
  spk_emb: torch.Tensor = None,
 
2408
  num_spk_embs: int = 1,
2409
  ):
2410
  """
2411
+ Replace consecutive `num_spk_embs` speaker embedding placeholders in input_embeds with pre-prepared speaker embeddings. This is an in-place replacement, no new tensor is created, so no value is returned.
2412
 
2413
  Args:
2414
  input_ids (torch.Tensor): Input ID tensor, shape [batch_size, seq_len_max]
 
2447
  use_spk_emb: bool = True,
2448
  ) -> torch.Tensor:
2449
  """
2450
+ In streaming audio generation, determine which `text` positions the TTS model can attend to when generating each chunk of `audio` tokens.
2451
 
2452
  This function creates a mask that allows the model to attend to a specific chunk of text
2453
  tokens when generating each chunk of audio tokens, enabling streaming TTS generation.
 
2504
  return causal_mask
2505
 
2506
 
2507
+ # Borrowed from `https://github.com/2noise/ChatTTS/blob/main/ChatTTS/model/processors.py`
2508
  class CustomRepetitionPenaltyLogitsProcessorRepeat:
2509
  def __init__(self, penalty: float, max_input_ids: int, past_window: int):
2510
  if not isinstance(penalty, float) or not (penalty > 0):
 
2563
 
2564
 
2565
  class ConditionalChatTTS(PreTrainedModel):
2566
+ """A conditional text-to-speech model that can generate speech from text with speaker conditioning.
2567
+
2568
+ This model extends PreTrainedModel to provide text-to-speech capabilities with:
2569
+ - LLM hidden state conditioning
2570
+ - Streaming generation
2571
+
2572
+ The model uses a transformer architecture with LLM hidden states and can operate in both
2573
+ streaming and non-streaming modes for flexible deployment.
2574
+
2575
+ The model process sequence in the following format:
2576
+ | text bos token | LLM embedding projected to tts embedding space | text tokens (fixed length, reserved for future tokens) | audio bos token | audio tokens (audio token length is not fixed)| audio eos token |
2577
+
2578
+ The format is designed to support LLM-conditioned streaming audio generation.
2579
+
2580
+ Usage:
2581
+ To support streaming generation, two global variables should be maintained outside of the model.
2582
+ 1. `audio_input_ids`: stores *discrete* audio codes. It is a tensor with shape [1, sequence length+1, num_vq].
2583
+ 2. `past_key_values`: stores the KV cache for both text tokens and audio codes. It is a list of tuples, each tuple contains two tensors with shape [1, num_attention_heads, sequence length, hidden_size // num_attention_heads]
2584
+
2585
+ where `num_vq` is the number of audio codebooks, in default setting, it is `4`.
2586
+
2587
+ 1. Create an empty `past_key_values` with
2588
+ ```python
2589
+ initial_kv_cache_length = 1 + model.num_spk_embs + model.streaming_text_reserved_len # where `1` denotes the `bos` token
2590
+ dtype = model.emb_text.weight.dtype
2591
+ device = model.emb_text.weight.device
2592
+ past_key_values = [
2593
+ (
2594
+ torch.zeros(1, model.config.num_attention_heads, initial_kv_cache_length, model.config.hidden_size // model.config.num_attention_heads, dtype=dtype, device=device),
2595
+ torch.zeros(1, model.config.num_attention_heads, initial_kv_cache_length, model.config.hidden_size // model.config.num_attention_heads, dtype=dtype, device=device)
2596
+ )
2597
+ for _ in range(model.config.num_hidden_layers)
2598
+ ]
2599
+
2600
+ 2. At the same time, create an empty `audio_input_ids` with shape [1, sequence length, num_vq], `num_vq` denotes multiple layer audio codebooks. But here we also include text tokens in the sequence, but they will be zeros, and will not be used, just a placeholder.
2601
+
2602
+ ```python
2603
+ initial_audio_input_ids_length = 1 + model.num_spk_embs + model.streaming_text_reserved_len + 1
2604
+ # [bos token, speaker embeddings, text tokens, audio bos token]
2605
+ audio_input_ids = torch.zeros(batch_size=1, initial_audio_input_ids_length, model.num_vq)
2606
+ ```
2607
+
2608
+ 2. Prefill some text tokens to TTS model (for example, 10 tokens) using `prefill_text` method.
2609
+
2610
+ ```python
2611
+ outputs = llm.generate(**kwargs)
2612
+ llm_tokens = some_function_to_extract_llm_tokens(outputs)
2613
+ lm_spk_emb_last_hidden_states = some_function_to_extract_lm_spk_emb_last_hidden_states(outputs)
2614
+ tts_text_input_ids = tts_tokenizer.encode(llm_tokenizer.decode(llm_tokens))
2615
+ # here assume we are prefilling text token 0 to text token 9 (included), totally 10 tokens.
2616
+ begin = 0
2617
+ end = 9+1
2618
+ position_ids = torch.arange(begin, end, dtype=torch.long, device=device)
2619
+
2620
+ past_key_values = model.prefill_text(
2621
+ input_ids=tts_text_input_ids,
2622
+ position_ids=position_ids,
2623
+ past_key_values=past_key_values,
2624
+ lm_spk_emb_last_hidden_states=lm_spk_emb_last_hidden_states,
2625
+ )
2626
+ ```
2627
+
2628
+ 3. Make a `streaming_tts_text_mask` to denote which position contains valid text tokens, similar to `attention_mask` in standard causal attention.
2629
+
2630
+ ```python
2631
+ streaming_tts_text_mask = torch.zeros(model.streaming_reserved_length)
2632
+ streaming_tts_text_mask[0:end] = 1 # denotes these post
2633
+ ```
2634
+
2635
+ 3. Generate audio codes using `generate` method.
2636
+
2637
+ ```python
2638
+ outputs = model.generate(
2639
+ input_ids=audio_input_ids,
2640
+ past_key_values=past_key_values,
2641
+ streaming_tts_text_mask=streaming_tts_text_mask,
2642
+ max_new_token=50,
2643
+ )
2644
+
2645
+ # update past_key_values and input_ids
2646
+ past_key_values = outputs.past_key_values
2647
+ audio_input_ids = outputs.input_ids
2648
+ ```
2649
+
2650
+ The `past_key_values` is extended by `max_new_token=50`, and `audio_input_ids` is also extended by `max_new_token=50` after `generate` calling.
2651
+
2652
+ 4. Notice that after prefilling `10` text tokens, the model can generate up to `50` audio tokens, if you want to generate more audio tokens, you need to prefill next `10` text tokens. And it is okay to only generate `25` audio tokens for faster initial response.
2653
+
2654
+ 5. Repeat steps `2,3,4` as needed in your streaming audio generation cases, but ensure usage complies with the following guidelines discussed above.
2655
+ """
2656
+
2657
  config_class = ConditionalChatTTSConfig
2658
 
2659
  def __init__(self, config: ConditionalChatTTSConfig):
 
2711
  self.model = model
2712
 
2713
  @torch.inference_mode()
2714
+ def merge_inputs_embeds(
2715
  self,
2716
  input_ids: torch.Tensor,
2717
  lm_spk_emb_last_hidden_states: Optional[torch.Tensor] = None,
 
2718
  ):
2719
+ """Merge `input_ids` and `lm_spk_emb_last_hidden_states` to `inputs_embeds`.
 
2720
 
2721
  Args:
2722
  input_ids (torch.Tensor): Input token IDs.
2723
  lm_spk_emb_last_hidden_states (Optional[torch.Tensor], optional): Last hidden states of speaker embeddings from the language model. Defaults to None.
 
2724
 
2725
  Raises:
2726
  NotImplementedError: If speaker embedding is not used and language model hidden states are not implemented.
 
2750
  num_spk_embs=self.num_spk_embs,
2751
  )
2752
  else:
 
 
2753
  raise NotImplementedError
2754
 
2755
  return inputs_embeds
 
2761
  position_ids: torch.LongTensor,
2762
  past_key_values: List[Tuple[torch.Tensor, torch.Tensor]],
2763
  lm_spk_emb_last_hidden_states: Optional[torch.Tensor] = None,
 
2764
  ):
2765
  """Prefill a chunk of new text tokens in streaming setting.
2766
+ Specifically speaking, update `past_key_values` using new text tokens, then the model will read the new text tokens.
2767
 
2768
  Args:
2769
  input_ids (Tensor): Tensor of shape [batch_size, seq_len]
 
2777
  assert input_ids.shape[0] == 1
2778
  assert past_key_values is not None
2779
 
2780
+ # Merge text and LLM embeddings
2781
+ inputs_embeds = self.merge_inputs_embeds(
2782
  input_ids=input_ids,
2783
  lm_spk_emb_last_hidden_states=lm_spk_emb_last_hidden_states,
 
2784
  )
2785
 
2786
  # Clone KV Cache
 
2807
  # Get model updated KV Cache
2808
  past_key_values_for_prefill_updated = outputs_prefill.past_key_values
2809
 
2810
+ # Update generated KV Cache to input `past_key_values`
2811
  for layer_idx in range(len(past_key_values)):
2812
  # Update keys
2813
  past_key_values[layer_idx][0][:, :, position_ids[:, 0] : position_ids[:, -1] + 1, :] = (
 
2835
  streaming_tts_text_mask=None,
2836
  add_audio_bos: bool = True,
2837
  ):
2838
+ """Prefill a chunk of audio ids to the model. Used in sliding-window long audio generation.
2839
+ Specifically, prefill many audio ids (typically from last window) to the model in the new window.
2840
+
2841
  Args:
2842
  input_ids (torch.Tensor): (1, seq_len, num_vq) Audio input token ids.
2843
  past_key_values (List[Tuple[torch.Tensor, torch.Tensor]]): Past key values for attention mechanism.
 
2867
  streaming_tts_text_mask=streaming_tts_text_mask,
2868
  streaming_reserved_length=self.streaming_text_reserved_len,
2869
  streaming_text_chunk_size=self.streaming_text_chunk_size,
2870
+ ) # [1, 1, 1, past_key_values_length + input_len]
2871
 
2872
  # Model forward
2873
  outputs: BaseModelOutputWithPast = self.model(
 
2897
  logits_processors: List[CustomRepetitionPenaltyLogitsProcessorRepeat] = [],
2898
  show_tqdm=False,
2899
  ):
2900
+ """Generate audio codes in streaming setting or non-streaming setting.
2901
  Specifically speaking, generate audio codes when not all text tokens are prefilled.
2902
 
2903
+ Always pass a valid `past_key_values` to the method. The method does not do `prefill` by itself. It relies on `prefill_text` method to provide valid `past_key_values`. Please refer to docstring of this class for more details.
 
2904
 
2905
+ In this method, we borrowed a lot of codes from `https://github.com/2noise/ChatTTS/blob/main/ChatTTS/model/gpt.py`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2906
 
2907
  Args:
2908
  input_ids (torch.Tensor): Input token ids.
 
2914
  logits_warpers (List[LogitsWarper], optional): List of logits warpers. Defaults to [].
2915
  logits_processors (List[CustomRepetitionPenaltyLogitsProcessorRepeat], optional): List of logits processors. Defaults to [].
2916
  show_tqdm (bool, optional): Whether to show progress bar. Defaults to True.
2917
+
 
2918
  Returns:
2919
  GenerationOutputs: Generation outputs.
2920
  """
 
2942
  device=input_ids.device,
2943
  )
2944
 
2945
+ # Copy existing `input_ids` to `input_ids_buf`
2946
  input_ids_buf.narrow(1, 0, progress).copy_(input_ids)
2947
 
2948
  del input_ids
 
2961
  for i in range(max_new_token):
2962
  # Prepare generation inputs
2963
  audio_bos = False
2964
+
2965
+ # If this is the first audio token, the case is SPECIAL
2966
  if progress == condition_length:
2967
  audio_bos = True
2968
 
2969
+ assert progress == (
2970
+ past_key_values[0][0].shape[2] + 1
2971
+ ) # If you are using according to the guidelines, this should be passed.
2972
+
2973
  if audio_bos:
2974
+ # Generate the first token, activate the model with `self.audio_bos_token_id`, the model will predict a new audio token. This is a special case because without the `audio bos token`, it is impossible to generate the first audio token in our streaming setting.
 
2975
  narrowed_input_ids = torch.tensor([[self.audio_bos_token_id]], dtype=torch.long, device=self.device)
2976
  inputs_embeds = self.emb_text(narrowed_input_ids)
2977
  del narrowed_input_ids
2978
  else:
2979
+ # Generate the following audio tokens, it is applicable to all other cases, including second and the following calling of `generate`.
 
2980
  narrowed_input_ids = input_ids.narrow(dim=1, start=input_ids.shape[1] - 1, length=1)
2981
  code_emb = [self.emb_code[i](narrowed_input_ids[:, :, i]) for i in range(self.num_vq)]
2982
  inputs_embeds = torch.stack(code_emb, 3).sum(3)
 
2986
  ).unsqueeze(0)
2987
 
2988
  cache_position = position_ids.clone()
2989
+
2990
+ # Make causal mask
2991
  causal_mask = make_streaming_chunk_mask_generation(
2992
  inputs_embeds=inputs_embeds,
2993
  past_seen_tokens=past_key_values[0][0].shape[2],
 
3079
  finish.logical_or_(finish_or)
3080
 
3081
  del finish_or
3082
+ # Store new `token` into `input_ids_buf`
3083
  input_ids_buf.narrow(1, progress, 1).copy_(idx_next.unsqueeze_(1))
3084
 
3085
  if i == 0 and finish.any():
 
3123
  def decode_to_mel_specs(
3124
  self,
3125
  result_list: List[torch.Tensor],
 
3126
  ):
3127
+ """Decode discrete audio codes to mel spectrograms.
3128
+
3129
+ Borrowed from `https://github.com/2noise/ChatTTS/blob/main/ChatTTS/core.py`
3130
+
3131
+ Args:
3132
+ result_list (List[torch.Tensor]): Audio codes output from `generate`.
3133
+
3134
+ Returns:
3135
+ torch.Tensor: Mel spectrograms.
3136
+ """
3137
+
3138
  decoder = self.dvae
3139
  max_x_len = -1
3140
  if len(result_list) == 0:
 
3157
  return mel_specs
3158
 
3159
 
3160
+ # Borrowed from `https://github.com/2noise/ChatTTS/blob/main/ChatTTS/model/processors.py`
3161
  def gen_logits(
3162
  num_code: int,
3163
  top_P=0.7,
modeling_navit_siglip.py CHANGED
@@ -851,6 +851,7 @@ class SiglipVisionTransformer(SiglipPreTrainedModel):
851
  config_class = SiglipVisionConfig
852
  main_input_name = "pixel_values"
853
  _supports_flash_attn_2 = True
 
854
 
855
  def __init__(self, config: SiglipVisionConfig):
856
  super().__init__(config)
 
851
  config_class = SiglipVisionConfig
852
  main_input_name = "pixel_values"
853
  _supports_flash_attn_2 = True
854
+ _no_split_modules = []
855
 
856
  def __init__(self, config: SiglipVisionConfig):
857
  super().__init__(config)
processing_minicpmo.py CHANGED
@@ -309,8 +309,10 @@ class MiniCPMOProcessor(ProcessorMixin):
309
  )
310
  return MiniCPMOBatchFeature(data={**model_inputs})
311
 
312
- image_pattern = "<image>./</image>"
313
- audio_pattern = "<audio>./</audio>"
 
 
314
  split_pattern = f"({image_pattern}|{audio_pattern})"
315
 
316
  if isinstance(texts, str):
@@ -343,13 +345,13 @@ class MiniCPMOProcessor(ProcessorMixin):
343
  image_id = 0
344
  audio_id = 0
345
  for i, chunk in enumerate(text_chunks):
346
- if chunk == image_pattern:
347
  image_placeholder = self.image_processor.get_slice_image_placeholder(
348
  image_sizes[index][image_id], image_id, max_slice_nums, use_image_id
349
  )
350
  image_id += 1
351
  text_chunks[i] = image_placeholder
352
- elif chunk == audio_pattern:
353
  audio_placeholder = audio_phs[index][audio_id]
354
  audio_id += 1
355
  text_chunks[i] = audio_placeholder
@@ -494,9 +496,6 @@ class ChatTTSProcessor:
494
  try:
495
  mel = self.audio_processor(audio) # [100(num_mel_bins), seq_len_mel]
496
  except Exception as e:
497
- print(
498
- "fuck! there is an error with audio waveform. If you use a dataset __getitem__, will skip and use next data as compensate, will not halt training."
499
- )
500
  raise e
501
  audio_features_varlen.append(mel)
502
 
 
309
  )
310
  return MiniCPMOBatchFeature(data={**model_inputs})
311
 
312
+ image_tag = "(<image>./</image>)"
313
+ image_pattern = "\(<image>./</image>\)"
314
+ audio_tag = "(<audio>./</audio>)"
315
+ audio_pattern = "\(<audio>./</audio>\)"
316
  split_pattern = f"({image_pattern}|{audio_pattern})"
317
 
318
  if isinstance(texts, str):
 
345
  image_id = 0
346
  audio_id = 0
347
  for i, chunk in enumerate(text_chunks):
348
+ if chunk == image_tag:
349
  image_placeholder = self.image_processor.get_slice_image_placeholder(
350
  image_sizes[index][image_id], image_id, max_slice_nums, use_image_id
351
  )
352
  image_id += 1
353
  text_chunks[i] = image_placeholder
354
+ elif chunk == audio_tag:
355
  audio_placeholder = audio_phs[index][audio_id]
356
  audio_id += 1
357
  text_chunks[i] = audio_placeholder
 
496
  try:
497
  mel = self.audio_processor(audio) # [100(num_mel_bins), seq_len_mel]
498
  except Exception as e:
 
 
 
499
  raise e
500
  audio_features_varlen.append(mel)
501
 
utils.py CHANGED
@@ -13,8 +13,8 @@
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
 
16
- import re
17
  import logging
 
18
 
19
  import librosa
20
  import numpy as np
@@ -42,6 +42,28 @@ def sentence_end(txt):
42
 
43
 
44
  class NumberToTextConverter:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  def __init__(self):
46
  self.num_to_chinese = {
47
  "0": "零",
@@ -103,6 +125,31 @@ class NumberToTextConverter:
103
 
104
 
105
  class VoiceChecker:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  def __init__(self):
107
  self.previous_mel = None
108
  self.consecutive_zeros = 0
@@ -129,7 +176,9 @@ class VoiceChecker:
129
  mel_spec_chunk = mel_spec[:, i * mel_chunk_size : (i + 1) * mel_chunk_size]
130
 
131
  distance = self.compute_distance(audio_chunk, mel_spec_chunk)
132
- logger.warning(f"mel dist: {distance:.1f}, zero: {self.consecutive_zeros}, low: {self.consecutive_low_distance}")
 
 
133
  if distance == 0:
134
  self.consecutive_low_distance = 0 # reset
135
  self.consecutive_zeros += 1
 
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
 
 
16
  import logging
17
+ import re
18
 
19
  import librosa
20
  import numpy as np
 
42
 
43
 
44
  class NumberToTextConverter:
45
+ r"""
46
+ A helper class to ensure text-to-speech (TTS) systems read numeric digits
47
+ in the desired language (Chinese or English) digit-by-digit. It forcibly
48
+ replaces all numeric substrings in text with their language-specific
49
+ textual representations, thereby reducing the likelihood of TTS mistakes
50
+ on numbers.
51
+ Note: MiniCPM-o 2.6 only use this in streaming mode.
52
+
53
+ Attributes:
54
+ num_to_chinese (dict):
55
+ Mapping from digit (str) to its Chinese textual form (str).
56
+ num_to_english (dict):
57
+ Mapping from digit (str) to its English textual form (str).
58
+
59
+ Example:
60
+ >>> converter = NumberToTextConverter()
61
+ >>> converter.replace_numbers_with_text("我有2个苹果", language="chinese")
62
+ '我有两个苹果'
63
+ >>> converter.replace_numbers_with_text("I have 23 books", language="english")
64
+ 'I have two three books'
65
+ """
66
+
67
  def __init__(self):
68
  self.num_to_chinese = {
69
  "0": "零",
 
125
 
126
 
127
  class VoiceChecker:
128
+ r"""
129
+ A simple utility class to detect silence or low variation in consecutive audio chunks by comparing
130
+ the mel-spectrogram distances. It keeps track of consecutive zero-distance and low-distance chunks
131
+ to decide if the audio is considered "bad" (e.g., overly silent or not changing enough).
132
+
133
+ Attributes:
134
+ previous_mel (`np.ndarray` or `None`):
135
+ Holds the previously observed mel-spectrogram in decibel scale. Used to compute
136
+ the next distance; reset via :meth:`reset`.
137
+ consecutive_zeros (`int`):
138
+ The number of consecutive chunks that were detected as silent (distance = 0).
139
+ consecutive_low_distance (`int`):
140
+ The number of consecutive chunks whose distance was below the threshold.
141
+
142
+ Example:
143
+ >>> checker = VoiceChecker()
144
+ >>> # Suppose we have audio_wav (list or np.ndarray) and mel_spec (np.ndarray)
145
+ >>> # We split them into chunks and call checker.is_bad(...)
146
+ >>> is_audio_bad = checker.is_bad(audio_wav, mel_spec, chunk_size=2560, thresh=100.0)
147
+ >>> if is_audio_bad:
148
+ ... print("Audio deemed bad!")
149
+ >>> # Reset states if needed
150
+ >>> checker.reset()
151
+ """
152
+
153
  def __init__(self):
154
  self.previous_mel = None
155
  self.consecutive_zeros = 0
 
176
  mel_spec_chunk = mel_spec[:, i * mel_chunk_size : (i + 1) * mel_chunk_size]
177
 
178
  distance = self.compute_distance(audio_chunk, mel_spec_chunk)
179
+ logger.warning(
180
+ f"mel dist: {distance:.1f}, zero: {self.consecutive_zeros}, low: {self.consecutive_low_distance}"
181
+ )
182
  if distance == 0:
183
  self.consecutive_low_distance = 0 # reset
184
  self.consecutive_zeros += 1