starsfriday commited on
Commit
7c2caef
·
verified ·
1 Parent(s): f4862d3

Add JoyFox-OmniFlow-9B

Browse files

Initial complete model release.

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +25 -0
  2. Modelfile +16 -0
  3. README.md +264 -0
  4. added_tokens.json +107 -0
  5. assets/HT_ref_audio.wav +3 -0
  6. assets/Skiing.mp4 +3 -0
  7. assets/Trump_WEF_2018_10s.mp3 +3 -0
  8. assets/audio_cases/assistant_ref.mp4 +0 -0
  9. assets/audio_cases/assistant_response.mp4 +3 -0
  10. assets/audio_cases/elon_musk__000_assistant_audio.wav +3 -0
  11. assets/audio_cases/elon_musk__system_ref_audio.wav +3 -0
  12. assets/audio_cases/elon_musk_ref.mp4 +3 -0
  13. assets/audio_cases/elon_musk_response.mp4 +3 -0
  14. assets/audio_cases/hermione__000_assistant_audio.wav +3 -0
  15. assets/audio_cases/hermione__system_ref_audio.wav +3 -0
  16. assets/audio_cases/minicpm_assistant__000_assistant_audio.wav +3 -0
  17. assets/audio_cases/minicpm_assistant__system_ref_audio.wav +3 -0
  18. assets/audio_cases/paimon__000_assistant_audio.wav +3 -0
  19. assets/audio_cases/paimon__system_ref_audio.wav +3 -0
  20. assets/audio_cases/readme.txt +1 -0
  21. assets/bajie.wav +3 -0
  22. assets/fossil.png +3 -0
  23. assets/haimianbaobao.wav +3 -0
  24. assets/highway.png +3 -0
  25. assets/nezha.wav +3 -0
  26. assets/omni_duplex1.mp4 +3 -0
  27. assets/omni_duplex2.mp4 +3 -0
  28. assets/sunwukong.wav +3 -0
  29. assets/system_ref_audio.wav +3 -0
  30. assets/system_ref_audio_2.wav +3 -0
  31. assets/token2wav/campplus.onnx +3 -0
  32. assets/token2wav/flow.pt +3 -0
  33. assets/token2wav/flow.yaml +34 -0
  34. assets/token2wav/hift.pt +3 -0
  35. assets/token2wav/speech_tokenizer_v2_25hz.onnx +3 -0
  36. chat_template.jinja +88 -0
  37. config.json +324 -0
  38. configuration.json +1 -0
  39. configuration_minicpmo.py +260 -0
  40. generation_config.json +13 -0
  41. merges.txt +0 -0
  42. model-00001-of-00004.safetensors +3 -0
  43. model-00002-of-00004.safetensors +3 -0
  44. model-00003-of-00004.safetensors +3 -0
  45. model-00004-of-00004.safetensors +3 -0
  46. model-tts.safetensors +3 -0
  47. model.safetensors.index.json +0 -0
  48. modeling_minicpmo.py +0 -0
  49. modeling_navit_siglip.py +981 -0
  50. preprocessor_config.json +49 -0
.gitattributes CHANGED
@@ -33,3 +33,28 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/HT_ref_audio.wav filter=lfs diff=lfs merge=lfs -text
37
+ assets/Skiing.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ assets/Trump_WEF_2018_10s.mp3 filter=lfs diff=lfs merge=lfs -text
39
+ assets/audio_cases/assistant_response.mp4 filter=lfs diff=lfs merge=lfs -text
40
+ assets/audio_cases/elon_musk__000_assistant_audio.wav filter=lfs diff=lfs merge=lfs -text
41
+ assets/audio_cases/elon_musk__system_ref_audio.wav filter=lfs diff=lfs merge=lfs -text
42
+ assets/audio_cases/elon_musk_ref.mp4 filter=lfs diff=lfs merge=lfs -text
43
+ assets/audio_cases/elon_musk_response.mp4 filter=lfs diff=lfs merge=lfs -text
44
+ assets/audio_cases/hermione__000_assistant_audio.wav filter=lfs diff=lfs merge=lfs -text
45
+ assets/audio_cases/hermione__system_ref_audio.wav filter=lfs diff=lfs merge=lfs -text
46
+ assets/audio_cases/minicpm_assistant__000_assistant_audio.wav filter=lfs diff=lfs merge=lfs -text
47
+ assets/audio_cases/minicpm_assistant__system_ref_audio.wav filter=lfs diff=lfs merge=lfs -text
48
+ assets/audio_cases/paimon__000_assistant_audio.wav filter=lfs diff=lfs merge=lfs -text
49
+ assets/audio_cases/paimon__system_ref_audio.wav filter=lfs diff=lfs merge=lfs -text
50
+ assets/bajie.wav filter=lfs diff=lfs merge=lfs -text
51
+ assets/fossil.png filter=lfs diff=lfs merge=lfs -text
52
+ assets/haimianbaobao.wav filter=lfs diff=lfs merge=lfs -text
53
+ assets/highway.png filter=lfs diff=lfs merge=lfs -text
54
+ assets/nezha.wav filter=lfs diff=lfs merge=lfs -text
55
+ assets/omni_duplex1.mp4 filter=lfs diff=lfs merge=lfs -text
56
+ assets/omni_duplex2.mp4 filter=lfs diff=lfs merge=lfs -text
57
+ assets/sunwukong.wav filter=lfs diff=lfs merge=lfs -text
58
+ assets/system_ref_audio.wav filter=lfs diff=lfs merge=lfs -text
59
+ assets/system_ref_audio_2.wav filter=lfs diff=lfs merge=lfs -text
60
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
Modelfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ollama modelfile auto-generated by llamafactory
2
+
3
+ FROM .
4
+
5
+ TEMPLATE """{{ if .System }}<|im_start|>system
6
+ {{ .System }}<|im_end|>
7
+ {{ end }}{{ range .Messages }}{{ if eq .Role "user" }}<|im_start|>user
8
+ {{ .Content }}<|im_end|>
9
+ <|im_start|>assistant
10
+ {{ else if eq .Role "assistant" }}{{ .Content }}<|im_end|>
11
+ {{ end }}{{ end }}"""
12
+
13
+ SYSTEM """You are a helpful assistant. You can accept audio and text input and output voice and text."""
14
+
15
+ PARAMETER stop "<|im_end|>"
16
+ PARAMETER num_ctx 4096
README.md ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ - zh
6
+ base_model: openbmb/MiniCPM-o-4_5
7
+ library_name: transformers
8
+ pipeline_tag: any-to-any
9
+ tags:
10
+ - minicpm-o
11
+ - full-duplex
12
+ - omni-modal
13
+ - audio
14
+ - vision
15
+ - tts
16
+ - speech-generation
17
+ - tool-calling
18
+ - roleplay
19
+ - code
20
+ - math
21
+ ---
22
+
23
+ # JoyFox-OmniFlow-9B
24
+
25
+ JoyFox-OmniFlow-9B is a general-purpose, full-duplex multimodal model built on
26
+ [OpenBMB MiniCPM-o 4.5](https://huggingface.co/openbmb/MiniCPM-o-4_5).
27
+
28
+ The model is designed for:
29
+
30
+ - English, Chinese, and multilingual conversations;
31
+ - instruction following and complex question answering;
32
+ - mathematical reasoning and code generation;
33
+ - knowledge-intensive and long-form responses;
34
+ - role-play, character-driven dialogue, and natural conversation;
35
+ - agent workflows and tool-calling formats;
36
+ - real-time vision, audio, text, and speech interaction.
37
+
38
+ JoyFox-OmniFlow-9B is distributed as a complete BF16 Safetensors model that can
39
+ be loaded directly with Hugging Face Transformers. The release includes the
40
+ language model, vision encoder, audio encoder, multimodal projection layers,
41
+ TTS module, voice-cloning support, token-to-waveform resources, and full-duplex
42
+ streaming components.
43
+
44
+ ## Highlights
45
+
46
+ - **Complete full-duplex model**: supports concurrent visual/audio input and text/speech output.
47
+ - **Integrated TTS**: includes speech generation weights, token2wav resources, and reference audio assets.
48
+ - **Broad language capabilities**: covers general instruction following, math, code, multilingual dialogue, role-play, and tool use.
49
+ - **Omni-modal interaction**: combines language, vision, audio, multimodal projection, and streaming session modules.
50
+ - **Voice cloning and character voices**: supports reference-audio-driven speech generation.
51
+ - **Ready for GPU inference**: fully validated on an NVIDIA RTX PRO 6000 Blackwell GPU.
52
+ - **Standard Transformers package**: no additional model-weight package is required at load time.
53
+
54
+ ## Capability Overview
55
+
56
+ | Component | Capability |
57
+ |---|---|
58
+ | Language model | General dialogue, knowledge, instruction following, math, code, and role-play |
59
+ | Vision module | Image, video-frame, and continuous visual-stream understanding |
60
+ | Audio module | Speech, environmental audio, and continuous audio-stream understanding |
61
+ | Multimodal projection | Alignment of language, vision, and audio representations |
62
+ | TTS | Natural text-to-speech generation |
63
+ | token2wav | Decoding speech tokens into waveform audio |
64
+ | Full-duplex streaming | Simultaneous seeing, listening, reasoning, and speaking |
65
+ | Voice cloning | Reference-audio-based voice control |
66
+
67
+ ## Model Package
68
+
69
+ | Item | Value |
70
+ |---|---|
71
+ | Model class | `MiniCPMO` |
72
+ | Model family | MiniCPM-o 4.5 |
73
+ | Weight precision | BF16 |
74
+ | Total parameters | 9,371,787,666 |
75
+ | TTS parameters | 347,696,290 |
76
+ | Weight keys | 1,414 |
77
+ | TTS weight keys | 194 |
78
+ | Safetensors shards | 5 |
79
+ | Total weight size | 18,743,575,332 bytes |
80
+ | Complete directory size | Approximately 18.67 GiB |
81
+ | Audio module | Included |
82
+ | Vision module | Included |
83
+ | TTS module | Included |
84
+ | Full-duplex streaming configuration | Enabled |
85
+
86
+ ## Integrity Validation
87
+
88
+ The released model passed the following checks:
89
+
90
+ - all 1,414 model weight keys are readable;
91
+ - all 194 TTS weight tensors are readable;
92
+ - the token2wav runtime assets are present;
93
+ - `init_audio=true`;
94
+ - `init_vision=true`;
95
+ - `init_tts=true`;
96
+ - `stream_input=true`;
97
+ - zero missing keys during a complete Transformers load;
98
+ - zero unexpected keys during a complete Transformers load;
99
+ - zero mismatched keys during a complete Transformers load.
100
+
101
+ ### GPU Load Validation
102
+
103
+ The complete BF16 model was successfully loaded on an NVIDIA RTX PRO 6000
104
+ Blackwell Server Edition:
105
+
106
+ - `llm`: CUDA
107
+ - `vpm`: CUDA
108
+ - `apm`: CUDA
109
+ - `tts`: CUDA
110
+ - `audio_projection_layer`: CUDA
111
+ - `resampler`: CUDA
112
+ - model-weight VRAM usage: approximately 17.56 GiB
113
+
114
+ The VRAM figure above primarily reflects model weights and small framework
115
+ overhead. Full-duplex inference requires additional memory for the KV cache,
116
+ video frames, audio buffers, and token2wav.
117
+
118
+ ## Installation
119
+
120
+ For text, image, or audio-understanding inference:
121
+
122
+ ```bash
123
+ pip install "transformers==4.51.0" accelerate \
124
+ "torch>=2.3.0,<=2.8.0" "torchaudio<=2.8.0" \
125
+ "minicpmo-utils>=1.0.5"
126
+ ```
127
+
128
+ For TTS or full-duplex streaming inference:
129
+
130
+ ```bash
131
+ pip install "transformers==4.51.0" accelerate \
132
+ "torch>=2.3.0,<=2.8.0" "torchaudio<=2.8.0" \
133
+ "minicpmo-utils[all]>=1.0.5"
134
+ ```
135
+
136
+ FFmpeg is also required for full-duplex video processing:
137
+
138
+ ```bash
139
+ sudo apt update
140
+ sudo apt install -y ffmpeg
141
+ ```
142
+
143
+ The model structure was also validated locally with `transformers==4.57.0` and
144
+ `torch==2.11.0+cu130`. For production full-duplex use, the MiniCPM-o 4.5
145
+ officially recommended dependency versions are preferred.
146
+
147
+ ## GPU Quick Start
148
+
149
+ ```python
150
+ import torch
151
+ from transformers import AutoModel, AutoProcessor
152
+
153
+ model_id = "joyfox/JoyFox-OmniFlow-9B"
154
+
155
+ model = AutoModel.from_pretrained(
156
+ model_id,
157
+ trust_remote_code=True,
158
+ attn_implementation="sdpa",
159
+ torch_dtype=torch.bfloat16,
160
+ init_vision=True,
161
+ init_audio=True,
162
+ init_tts=True,
163
+ )
164
+ processor = AutoProcessor.from_pretrained(
165
+ model_id,
166
+ trust_remote_code=True,
167
+ )
168
+
169
+ model.eval().cuda()
170
+ ```
171
+
172
+ ## Enabling TTS and Full-Duplex Mode
173
+
174
+ After installing `minicpmo-utils[all]`:
175
+
176
+ ```python
177
+ # Initialize token2wav for speech-token-to-waveform decoding.
178
+ model.init_tts()
179
+
180
+ # Enter full-duplex mode.
181
+ duplex_model = model.as_duplex()
182
+
183
+ # Return to standard half-duplex mode when needed.
184
+ model = duplex_model.as_simplex(reset_session=True)
185
+ ```
186
+
187
+ Real-time video/audio chunking, `streaming_prefill`, `streaming_generate`, and
188
+ output-video generation follow the standard MiniCPM-o 4.5 full-duplex API.
189
+
190
+ ## Speech Output Example
191
+
192
+ ```python
193
+ import librosa
194
+ import torch
195
+ from huggingface_hub import hf_hub_download
196
+
197
+ ref_audio_path = hf_hub_download(
198
+ repo_id=model_id,
199
+ filename="assets/HT_ref_audio.wav",
200
+ )
201
+ ref_audio, _ = librosa.load(ref_audio_path, sr=16000, mono=True)
202
+
203
+ model.init_tts()
204
+ system_message = model.get_sys_prompt(
205
+ ref_audio=ref_audio,
206
+ mode="omni",
207
+ language="en",
208
+ )
209
+
210
+ messages = [
211
+ system_message,
212
+ {
213
+ "role": "user",
214
+ "content": ["Introduce yourself in a natural and concise way."],
215
+ },
216
+ ]
217
+
218
+ with torch.inference_mode():
219
+ answer = model.chat(
220
+ msgs=messages,
221
+ do_sample=True,
222
+ temperature=0.7,
223
+ max_new_tokens=1024,
224
+ use_tts_template=True,
225
+ enable_thinking=False,
226
+ omni_mode=True,
227
+ generate_audio=True,
228
+ output_audio_path="output.wav",
229
+ )
230
+
231
+ print(answer)
232
+ ```
233
+
234
+ ## Intended Use
235
+
236
+ JoyFox-OmniFlow-9B is suitable for:
237
+
238
+ - general English, Chinese, and multilingual assistants;
239
+ - mathematical, coding, knowledge, and complex instruction tasks;
240
+ - role-play and character-driven dialogue;
241
+ - agent and tool-calling applications;
242
+ - multimodal assistants with visual and audio input;
243
+ - half-duplex conversations with speech output;
244
+ - real-time full-duplex video and audio interaction;
245
+ - reference-audio-based voice cloning and character speech.
246
+
247
+ ## Limitations
248
+
249
+ - This release does not report independent external benchmark results.
250
+ - Response style depends on the system prompt, chat template, and decoding configuration.
251
+ - Production tool-calling systems should validate schemas, arguments, and execution permissions.
252
+ - The model may produce inaccurate, biased, or inappropriate content; high-risk use cases require human review.
253
+ - Full-duplex quality depends on audio sampling, video chunking, system prompts, reference voices, and runtime implementation.
254
+ - Full-duplex TTS requires the additional runtime dependencies included with `minicpmo-utils[all]`.
255
+
256
+ ## License and Acknowledgements
257
+
258
+ This model is built on MiniCPM-o 4.5 and is subject to the applicable upstream
259
+ license requirements. The model card declares Apache-2.0 metadata. Before
260
+ deployment, redistribution, or commercial use, review the original MiniCPM-o
261
+ 4.5 license and the terms applicable to your intended use.
262
+
263
+ We thank OpenBMB, LLaMA-Factory, and the open-source community for the model,
264
+ tooling, and supporting resources used in this project.
added_tokens.json ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</answer>": 151686,
3
+ "</box>": 151674,
4
+ "</focus>": 151688,
5
+ "</image>": 151670,
6
+ "</image_id>": 151682,
7
+ "</image_save_to>": 151696,
8
+ "</line>": 151690,
9
+ "</perception>": 151692,
10
+ "</point>": 151678,
11
+ "</quad>": 151676,
12
+ "</ref>": 151672,
13
+ "</slice>": 151680,
14
+ "</source_image>": 151694,
15
+ "</think>": 151668,
16
+ "</tool_call>": 151658,
17
+ "</tool_response>": 151666,
18
+ "</unit>": 151684,
19
+ "<answer>": 151685,
20
+ "<box>": 151673,
21
+ "<focus>": 151687,
22
+ "<image>": 151669,
23
+ "<image_id>": 151681,
24
+ "<image_save_to>": 151695,
25
+ "<line>": 151689,
26
+ "<perception>": 151691,
27
+ "<point>": 151677,
28
+ "<quad>": 151675,
29
+ "<ref>": 151671,
30
+ "<slice>": 151679,
31
+ "<source_image>": 151693,
32
+ "<think>": 151667,
33
+ "<tool_call>": 151657,
34
+ "<tool_response>": 151665,
35
+ "<unit>": 151683,
36
+ "<|audio_end|>": 151699,
37
+ "<|audio_start|>": 151697,
38
+ "<|audio|>": 151698,
39
+ "<|box_end|>": 151649,
40
+ "<|box_start|>": 151648,
41
+ "<|chunk_bos|>": 151719,
42
+ "<|chunk_eos|>": 151718,
43
+ "<|chunk_tts_bos|>": 151720,
44
+ "<|chunk_tts_eos|>": 151721,
45
+ "<|emotion_end|>": 151711,
46
+ "<|emotion_start|>": 151710,
47
+ "<|endoftext|>": 151643,
48
+ "<|file_sep|>": 151664,
49
+ "<|fim_middle|>": 151660,
50
+ "<|fim_pad|>": 151662,
51
+ "<|fim_prefix|>": 151659,
52
+ "<|fim_suffix|>": 151661,
53
+ "<|im_end|>": 151645,
54
+ "<|im_start|>": 151644,
55
+ "<|image_pad|>": 151655,
56
+ "<|interrupt|>": 151707,
57
+ "<|listen|>": 151705,
58
+ "<|object_ref_end|>": 151647,
59
+ "<|object_ref_start|>": 151646,
60
+ "<|pitch_end|>": 151715,
61
+ "<|pitch_start|>": 151714,
62
+ "<|quad_end|>": 151651,
63
+ "<|quad_start|>": 151650,
64
+ "<|repo_name|>": 151663,
65
+ "<|speak|>": 151706,
66
+ "<|speed_end|>": 151713,
67
+ "<|speed_start|>": 151712,
68
+ "<|spk_bos|>": 151700,
69
+ "<|spk_eos|>": 151702,
70
+ "<|spk|>": 151701,
71
+ "<|timbre_10|>": 151726,
72
+ "<|timbre_11|>": 151727,
73
+ "<|timbre_12|>": 151728,
74
+ "<|timbre_13|>": 151729,
75
+ "<|timbre_14|>": 151730,
76
+ "<|timbre_15|>": 151731,
77
+ "<|timbre_16|>": 151732,
78
+ "<|timbre_17|>": 151733,
79
+ "<|timbre_18|>": 151734,
80
+ "<|timbre_19|>": 151735,
81
+ "<|timbre_20|>": 151736,
82
+ "<|timbre_21|>": 151737,
83
+ "<|timbre_22|>": 151738,
84
+ "<|timbre_23|>": 151739,
85
+ "<|timbre_24|>": 151740,
86
+ "<|timbre_25|>": 151741,
87
+ "<|timbre_26|>": 151742,
88
+ "<|timbre_27|>": 151743,
89
+ "<|timbre_28|>": 151744,
90
+ "<|timbre_29|>": 151745,
91
+ "<|timbre_30|>": 151746,
92
+ "<|timbre_31|>": 151747,
93
+ "<|timbre_7|>": 151723,
94
+ "<|timbre_8|>": 151724,
95
+ "<|timbre_9|>": 151725,
96
+ "<|tts_bos|>": 151703,
97
+ "<|tts_eos|>": 151704,
98
+ "<|tts_pad|>": 151722,
99
+ "<|turn_bos|>": 151716,
100
+ "<|turn_eos|>": 151717,
101
+ "<|vad_end|>": 151709,
102
+ "<|vad_start|>": 151708,
103
+ "<|video_pad|>": 151656,
104
+ "<|vision_end|>": 151653,
105
+ "<|vision_pad|>": 151654,
106
+ "<|vision_start|>": 151652
107
+ }
assets/HT_ref_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb8f06ba5080cdf548969138881fb8ad8b04e2516108f4e08ba0363b68b613ea
3
+ size 192590
assets/Skiing.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:479ace116d6ac92487ad90f415b3ef817cd019bba4521043ef0d5faaa1a8415d
3
+ size 8534409
assets/Trump_WEF_2018_10s.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4fb796c2bb95538eab22d9b68a31add560305b6d5ccbf150c3f96e7671b6db64
3
+ size 161053
assets/audio_cases/assistant_ref.mp4 ADDED
Binary file (65.5 kB). View file
 
assets/audio_cases/assistant_response.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d46268e3beb78b4287a896a09b2df0f895629ecbdcdc4cf3c519fe040084860f
3
+ size 269504
assets/audio_cases/elon_musk__000_assistant_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff6dced2e686b743f39eee36aef1410913c8d31459bb564dbbf8f81ef8a2da88
3
+ size 1762604
assets/audio_cases/elon_musk__system_ref_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c4109b2d685e1923ed66433eb08c92047a1f67510629a27edf49af4e5c606dd
3
+ size 539032
assets/audio_cases/elon_musk_ref.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:206c48ec4b08898fbfbfb1ea1fec058750c39c97cd2e5088b15b61fb194d6f7e
3
+ size 165179
assets/audio_cases/elon_musk_response.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d83c3a977fd444351710c9ba2c347c90efd49ed990276c5309867374df373a4f
3
+ size 388534
assets/audio_cases/hermione__000_assistant_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfd18a2ee9e27fdcd65e2d9bf0fe0b3c9ebc28cda6c43279c12e077889c2b88d
3
+ size 1534124
assets/audio_cases/hermione__system_ref_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46bd82796ce5ebc15b29bc21c1de38284cfa972b2f27cca1f17086516a757dee
3
+ size 197322
assets/audio_cases/minicpm_assistant__000_assistant_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe3b793a6436682d1e684e0f4c158718208ed38926880e01ee84f5aa61c78331
3
+ size 1246124
assets/audio_cases/minicpm_assistant__system_ref_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad576b50fd2f53ad4bb317b97ed33bc7027071e7e0811a2a2110d995614f1f42
3
+ size 192556
assets/audio_cases/paimon__000_assistant_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ddd9d8358950a8dab385b8031cb8371a832460f3db4d91e399373705158f346
3
+ size 697004
assets/audio_cases/paimon__system_ref_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9625e7115ff1f47cf842fecbb31db82057ff1863c080870539c31107aa93b9d
3
+ size 479304
assets/audio_cases/readme.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ This directory stores audio wav files for hf readme page.
assets/bajie.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16aa8ca3da7dad53680bac68cfde569e11e2f9ef5387b3ae60d68626e94db9d7
3
+ size 636512
assets/fossil.png ADDED

Git LFS Details

  • SHA256: b8b3f1668da6e2b503ecea5a6fd40c1a2a666b4bd07b903ba0728fd2fc9f74fb
  • Pointer size: 131 Bytes
  • Size of remote file: 466 kB
assets/haimianbaobao.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27405cf5977f04d3f248693f9b978654fad4f02f931d9746006bffb0ed7b66e1
3
+ size 343120
assets/highway.png ADDED

Git LFS Details

  • SHA256: 87c32da6ee77730423ec5fc29d7110878ab18a35791eb11a803088976c3b1f76
  • Pointer size: 131 Bytes
  • Size of remote file: 841 kB
assets/nezha.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe5d8932013ff30a9d8114a6d62e5342999d8c2ddf8509ecfeb1ead71cacf432
3
+ size 457802
assets/omni_duplex1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:31622e1efd9a7b197a340266037b45aeec13b3b27f010f1ea1d22d9c6e69405f
3
+ size 7295040
assets/omni_duplex2.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c04eaef27a821e18db3686fdcc9d4b1dafd441e08f6a0e12d4075b81cb04517e
3
+ size 29285216
assets/sunwukong.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3bdb6c175bd3b2bb02fe7a8cf0ced847d41ab552b2e318bc3c26ee477255eff7
3
+ size 644650
assets/system_ref_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c4109b2d685e1923ed66433eb08c92047a1f67510629a27edf49af4e5c606dd
3
+ size 539032
assets/system_ref_audio_2.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a65d17099239711601cb17e28b7aa7b6149acd153b92fd0366c23902bd4f687
3
+ size 341192
assets/token2wav/campplus.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6ac6a63997761ae2997373e2ee1c47040854b4b759ea41ec48e4e42df0f4d73
3
+ size 28303423
assets/token2wav/flow.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:15ccff24256ff61537c7f8b51e025116b83405f3fb017b54b008fc97da115446
3
+ size 623466603
assets/token2wav/flow.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ flow: !new:cosyvoice2.flow.flow.CausalMaskedDiffWithXvec
2
+ input_size: 512
3
+ output_size: 80
4
+ spk_embed_dim: 192
5
+ output_type: 'mel'
6
+ vocab_size: 6561
7
+ encoder: !new:cosyvoice2.transformer.upsample_encoder_v2.UpsampleConformerEncoderV2
8
+ input_size: 512
9
+ output_size: 512
10
+ input_layer: 'linear'
11
+ pre_lookahead_len: 3
12
+ num_blocks: 6
13
+ num_up_blocks: 4
14
+ up_stride: 2
15
+ up_scale_factor: 2
16
+ attention_heads: 8
17
+ pos_enc_layer_type: 'rel_pos_espnet'
18
+ selfattention_layer_type: 'rel_selfattn'
19
+ key_bias: true
20
+ linear_units: 2048
21
+ dropout_rate: 0.1
22
+ positional_dropout_rate: 0.1
23
+ attention_dropout_rate: 0.1
24
+ normalize_before: True
25
+ decoder: !new:cosyvoice2.flow.flow_matching.CausalConditionalCFM
26
+ inference_cfg_rate: 0.7
27
+ estimator: !new:cosyvoice2.flow.decoder_dit.DiT
28
+ in_channels: 320
29
+ out_channels: 80
30
+ mlp_ratio: 4.0
31
+ depth: 16
32
+ num_heads: 8
33
+ head_dim: 64
34
+ hidden_size: 512
assets/token2wav/hift.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3386cc880324d4e98e05987b99107f49e40ed925b8ecc87c1f4939432d429879
3
+ size 83390254
assets/token2wav/speech_tokenizer_v2_25hz.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d43342aa12163a80bf07bffb94c9de2e120a8df2f9917cd2f642e7f4219c6f71
3
+ size 496082973
chat_template.jinja ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
27
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
28
+ {%- elif message.role == "assistant" %}
29
+ {%- set content = message.content %}
30
+ {%- set reasoning_content = '' %}
31
+ {%- if message.reasoning_content is defined and message.reasoning_content is not none %}
32
+ {%- set reasoning_content = message.reasoning_content %}
33
+ {%- else %}
34
+ {%- if '</think>' in message.content %}
35
+ {%- set content = message.content.split('</think>')[-1].lstrip('\n') %}
36
+ {%- set reasoning_content = message.content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
37
+ {%- endif %}
38
+ {%- endif %}
39
+ {%- if loop.index0 > ns.last_query_index %}
40
+ {%- if loop.last or (not loop.last and reasoning_content) %}
41
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
42
+ {%- else %}
43
+ {{- '<|im_start|>' + message.role + '\n' + content }}
44
+ {%- endif %}
45
+ {%- else %}
46
+ {{- '<|im_start|>' + message.role + '\n' + content }}
47
+ {%- endif %}
48
+ {%- if message.tool_calls %}
49
+ {%- for tool_call in message.tool_calls %}
50
+ {%- if (loop.first and content) or (not loop.first) %}
51
+ {{- '\n' }}
52
+ {%- endif %}
53
+ {%- if tool_call.function %}
54
+ {%- set tool_call = tool_call.function %}
55
+ {%- endif %}
56
+ {{- '<tool_call>\n{"name": "' }}
57
+ {{- tool_call.name }}
58
+ {{- '", "arguments": ' }}
59
+ {%- if tool_call.arguments is string %}
60
+ {{- tool_call.arguments }}
61
+ {%- else %}
62
+ {{- tool_call.arguments | tojson }}
63
+ {%- endif %}
64
+ {{- '}\n</tool_call>' }}
65
+ {%- endfor %}
66
+ {%- endif %}
67
+ {{- '<|im_end|>\n' }}
68
+ {%- elif message.role == "tool" %}
69
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
70
+ {{- '<|im_start|>user' }}
71
+ {%- endif %}
72
+ {{- '\n<tool_response>\n' }}
73
+ {{- message.content }}
74
+ {{- '\n</tool_response>' }}
75
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
76
+ {{- '<|im_end|>\n' }}
77
+ {%- endif %}
78
+ {%- endif %}
79
+ {%- endfor %}
80
+ {%- if add_generation_prompt %}
81
+ {{- '<|im_start|>assistant\n' }}
82
+ {%- if enable_thinking is defined and enable_thinking is false %}
83
+ {{- '<think>\n\n</think>\n\n' }}
84
+ {%- endif %}
85
+ {%- if use_tts_template is defined and use_tts_template is true %}
86
+ {{- '<|tts_bos|>' }}
87
+ {%- endif %}
88
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MiniCPMO"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "audio_chunk_length": 1.0,
8
+ "audio_config": {
9
+ "_attn_implementation_autoset": true,
10
+ "_name_or_path": "openai/whisper-medium",
11
+ "activation_dropout": 0.0,
12
+ "activation_function": "gelu",
13
+ "apply_spec_augment": false,
14
+ "architectures": [
15
+ "MiniCPMWhisperEncoder"
16
+ ],
17
+ "attention_dropout": 0.0,
18
+ "begin_suppress_tokens": [
19
+ 220,
20
+ 50257
21
+ ],
22
+ "bos_token_id": 50257,
23
+ "classifier_proj_size": 256,
24
+ "d_model": 1024,
25
+ "decoder_attention_heads": 16,
26
+ "decoder_ffn_dim": 4096,
27
+ "decoder_layerdrop": 0.0,
28
+ "decoder_layers": 24,
29
+ "decoder_start_token_id": 50258,
30
+ "dropout": 0.0,
31
+ "dtype": "float32",
32
+ "encoder_attention_heads": 16,
33
+ "encoder_ffn_dim": 4096,
34
+ "encoder_layerdrop": 0.0,
35
+ "encoder_layers": 24,
36
+ "eos_token_id": 50257,
37
+ "forced_decoder_ids": [
38
+ [
39
+ 1,
40
+ 50259
41
+ ],
42
+ [
43
+ 2,
44
+ 50359
45
+ ],
46
+ [
47
+ 3,
48
+ 50363
49
+ ]
50
+ ],
51
+ "init_std": 0.02,
52
+ "mask_feature_length": 10,
53
+ "mask_feature_min_masks": 0,
54
+ "mask_feature_prob": 0.0,
55
+ "mask_time_length": 10,
56
+ "mask_time_min_masks": 2,
57
+ "mask_time_prob": 0.05,
58
+ "max_length": 448,
59
+ "max_source_positions": 1500,
60
+ "max_target_positions": 448,
61
+ "median_filter_width": 7,
62
+ "model_type": "whisper",
63
+ "num_hidden_layers": 24,
64
+ "num_mel_bins": 80,
65
+ "pad_token_id": 50257,
66
+ "scale_embedding": false,
67
+ "suppress_tokens": [
68
+ 1,
69
+ 2,
70
+ 7,
71
+ 8,
72
+ 9,
73
+ 10,
74
+ 14,
75
+ 25,
76
+ 26,
77
+ 27,
78
+ 28,
79
+ 29,
80
+ 31,
81
+ 58,
82
+ 59,
83
+ 60,
84
+ 61,
85
+ 62,
86
+ 63,
87
+ 90,
88
+ 91,
89
+ 92,
90
+ 93,
91
+ 359,
92
+ 503,
93
+ 522,
94
+ 542,
95
+ 873,
96
+ 893,
97
+ 902,
98
+ 918,
99
+ 922,
100
+ 931,
101
+ 1350,
102
+ 1853,
103
+ 1982,
104
+ 2460,
105
+ 2627,
106
+ 3246,
107
+ 3253,
108
+ 3268,
109
+ 3536,
110
+ 3846,
111
+ 3961,
112
+ 4183,
113
+ 4667,
114
+ 6585,
115
+ 6647,
116
+ 7273,
117
+ 9061,
118
+ 9383,
119
+ 10428,
120
+ 10929,
121
+ 11938,
122
+ 12033,
123
+ 12331,
124
+ 12562,
125
+ 13793,
126
+ 14157,
127
+ 14635,
128
+ 15265,
129
+ 15618,
130
+ 16553,
131
+ 16604,
132
+ 18362,
133
+ 18956,
134
+ 20075,
135
+ 21675,
136
+ 22520,
137
+ 26130,
138
+ 26161,
139
+ 26435,
140
+ 28279,
141
+ 29464,
142
+ 31650,
143
+ 32302,
144
+ 32470,
145
+ 36865,
146
+ 42863,
147
+ 47425,
148
+ 49870,
149
+ 50254,
150
+ 50258,
151
+ 50358,
152
+ 50359,
153
+ 50360,
154
+ 50361,
155
+ 50362
156
+ ],
157
+ "use_cache": true,
158
+ "use_weighted_layer_sum": false,
159
+ "vocab_size": 51865
160
+ },
161
+ "audio_pool_step": 5,
162
+ "auto_map": {
163
+ "AutoConfig": "configuration_minicpmo.MiniCPMOConfig",
164
+ "AutoModel": "modeling_minicpmo.MiniCPMO",
165
+ "AutoModelForCausalLM": "modeling_minicpmo.MiniCPMO"
166
+ },
167
+ "batch_vision_input": true,
168
+ "bos_token_id": 151643,
169
+ "drop_vision_last_layer": false,
170
+ "dtype": "bfloat16",
171
+ "eos_token_id": 151645,
172
+ "head_dim": 128,
173
+ "hidden_act": "silu",
174
+ "hidden_size": 4096,
175
+ "image_size": 448,
176
+ "init_audio": true,
177
+ "init_tts": true,
178
+ "init_vision": true,
179
+ "initializer_range": 0.02,
180
+ "intermediate_size": 12288,
181
+ "layer_types": [
182
+ "full_attention",
183
+ "full_attention",
184
+ "full_attention",
185
+ "full_attention",
186
+ "full_attention",
187
+ "full_attention",
188
+ "full_attention",
189
+ "full_attention",
190
+ "full_attention",
191
+ "full_attention",
192
+ "full_attention",
193
+ "full_attention",
194
+ "full_attention",
195
+ "full_attention",
196
+ "full_attention",
197
+ "full_attention",
198
+ "full_attention",
199
+ "full_attention",
200
+ "full_attention",
201
+ "full_attention",
202
+ "full_attention",
203
+ "full_attention",
204
+ "full_attention",
205
+ "full_attention",
206
+ "full_attention",
207
+ "full_attention",
208
+ "full_attention",
209
+ "full_attention",
210
+ "full_attention",
211
+ "full_attention",
212
+ "full_attention",
213
+ "full_attention",
214
+ "full_attention",
215
+ "full_attention",
216
+ "full_attention",
217
+ "full_attention"
218
+ ],
219
+ "listen_speak_type": "asr",
220
+ "max_position_embeddings": 40960,
221
+ "max_window_layers": 36,
222
+ "model_type": "minicpmo",
223
+ "num_attention_heads": 32,
224
+ "num_hidden_layers": 36,
225
+ "num_key_value_heads": 8,
226
+ "patch_size": 14,
227
+ "query_num": 64,
228
+ "rms_norm_eps": 1e-06,
229
+ "rope_scaling": null,
230
+ "rope_theta": 1000000,
231
+ "slice_config": {
232
+ "max_slice_nums": 1,
233
+ "model_type": "minicpmv",
234
+ "patch_size": 14,
235
+ "scale_resolution": 448
236
+ },
237
+ "slice_mode": true,
238
+ "sliding_window": null,
239
+ "stream_input": true,
240
+ "tie_word_embeddings": false,
241
+ "transformers_version": "4.57.0",
242
+ "tts_config": {
243
+ "_attn_implementation_autoset": true,
244
+ "attention_type": "full_attention",
245
+ "attn_implementation": "sdpa",
246
+ "audio_bos_token_id": 151687,
247
+ "audio_tokenizer_sample_rate": 16000,
248
+ "audio_tokenizer_type": "s3tokenizer",
249
+ "aug_layer_loss_weight": false,
250
+ "aug_loss_weight": false,
251
+ "backbone_model": "llama",
252
+ "condition_type": "hidden_text_merge",
253
+ "cosyvoice_config_path": null,
254
+ "cosyvoice_model_dir": null,
255
+ "filter_tts_loss": false,
256
+ "hidden_act": "silu",
257
+ "hidden_size": 768,
258
+ "interleaved": false,
259
+ "intermediate_size": 3072,
260
+ "llm_dim": 4096,
261
+ "llm_dim_model_base": 256,
262
+ "llm_down_scale": false,
263
+ "llm_hidden_size": 4096,
264
+ "llm_intermediate_size": 768,
265
+ "long_weight": 0.1,
266
+ "max_position_embeddings": 4096,
267
+ "model_type": "minicpmtts",
268
+ "normalize_projected_hidden": true,
269
+ "num_attention_heads": 12,
270
+ "num_audio_tokens": 6562,
271
+ "num_hidden_layers": 20,
272
+ "num_key_value_heads": 12,
273
+ "num_mel_bins": 100,
274
+ "num_text_tokens": 152064,
275
+ "num_vq": 1,
276
+ "projector_type": "mlp",
277
+ "recomputed_chunks": 1,
278
+ "s3_stream_chunk_size": 25,
279
+ "s3_stream_generate": false,
280
+ "s3_stream_n_timesteps": 10,
281
+ "s3_stream_prelook_size": 3,
282
+ "short_weight": 0.1,
283
+ "streaming": false,
284
+ "streaming_audio_chunk_size": 50,
285
+ "streaming_sliding_window": false,
286
+ "streaming_sliding_window_audio_frame_rate": 50,
287
+ "streaming_sliding_window_audio_init_text_length": 10,
288
+ "streaming_sliding_window_audio_window_size": 300,
289
+ "streaming_sliding_window_average_speed": 5,
290
+ "streaming_sliding_window_fast_speed": 7,
291
+ "streaming_sliding_window_max_text_len": 500,
292
+ "streaming_sliding_window_slow_speed": 3,
293
+ "streaming_sliding_window_text_window_size": 50,
294
+ "streaming_text_chunk_max": 7,
295
+ "streaming_text_chunk_min": 3,
296
+ "streaming_text_reserved_len": 300,
297
+ "text_eos_token_id": 151692,
298
+ "tts_filter_loss_fix": false,
299
+ "use_llm_hidden_state": false,
300
+ "use_text": true,
301
+ "window_size": 2
302
+ },
303
+ "use_cache": true,
304
+ "use_image_id": true,
305
+ "use_sliding_window": false,
306
+ "version": "4.5",
307
+ "vision_batch_size": 16,
308
+ "vision_config": {
309
+ "_attn_implementation_autoset": true,
310
+ "attention_dropout": 0.0,
311
+ "hidden_act": "gelu_pytorch_tanh",
312
+ "hidden_size": 1152,
313
+ "image_size": 980,
314
+ "intermediate_size": 4304,
315
+ "layer_norm_eps": 1e-06,
316
+ "model_type": "siglip_vision_model",
317
+ "num_attention_heads": 16,
318
+ "num_channels": 3,
319
+ "num_hidden_layers": 27,
320
+ "patch_size": 14
321
+ },
322
+ "vocab_size": 151748,
323
+ "torch_dtype": "bfloat16"
324
+ }
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"Pytorch","task":"any-to-any"}
configuration_minicpmo.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ # Copyright 2026 The OpenBMB Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ from typing import Union
19
+
20
+ from transformers import PretrainedConfig
21
+ from transformers import Qwen3Config
22
+ from transformers import WhisperConfig
23
+ from transformers.utils import logging
24
+
25
+ from .modeling_navit_siglip import SiglipVisionConfig
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class MiniCPMVSliceConfig(PretrainedConfig):
31
+ model_type = "minicpmv"
32
+
33
+ def __init__(
34
+ self,
35
+ patch_size=14,
36
+ max_slice_nums=9,
37
+ scale_resolution=448,
38
+ **kwargs,
39
+ ):
40
+ super().__init__(**kwargs)
41
+ self.patch_size = patch_size
42
+ self.max_slice_nums = max_slice_nums
43
+ self.scale_resolution = scale_resolution
44
+
45
+ @classmethod
46
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
47
+ cls._set_token_in_kwargs(kwargs)
48
+
49
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
50
+
51
+ if config_dict.get("model_type") == "minicpmv":
52
+ config_dict = config_dict["slice_config"]
53
+
54
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
55
+ logger.warning(
56
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
57
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
58
+ )
59
+
60
+ return cls.from_dict(config_dict, **kwargs)
61
+
62
+
63
+ class MiniCPMTTSConfig(PretrainedConfig):
64
+ model_type = "minicpmtts"
65
+
66
+ def __init__(
67
+ self,
68
+ llm_dim: int = 2560,
69
+ llm_intermediate_size: int = 768,
70
+ llm_down_scale: bool = False,
71
+ llm_dim_model_base: int = 256,
72
+ projector_type: str = "mlp",
73
+ hidden_act: str = "silu",
74
+ aug_loss_weight: bool = False,
75
+ aug_layer_loss_weight: bool = False,
76
+ filter_tts_loss: bool = False,
77
+ tts_filter_loss_fix: bool = False,
78
+ long_weight: float = 0.1,
79
+ short_weight: float = 0.1,
80
+ hidden_size: int = 768,
81
+ intermediate_size: int = 3072,
82
+ num_attention_heads: int = 12,
83
+ num_hidden_layers: int = 20,
84
+ num_key_value_heads: int = 12,
85
+ max_position_embeddings: int = 4096,
86
+ num_audio_tokens: int = 4097,
87
+ num_text_tokens: int = 21178,
88
+ num_mel_bins: int = 100,
89
+ num_vq: int = 1,
90
+ use_llm_hidden_state: bool = False,
91
+ audio_bos_token_id: int = 21132,
92
+ text_eos_token_id: int = 21133,
93
+ use_text: bool = True,
94
+ streaming: bool = False,
95
+ streaming_text_chunk_min: int = 3,
96
+ streaming_text_chunk_max: int = 7,
97
+ streaming_text_reserved_len: int = 300,
98
+ streaming_audio_chunk_size: int = 50,
99
+ attn_implementation: str = "sdpa",
100
+ condition_type: str = "llm_hidden",
101
+ backbone_model: str = "llama",
102
+ audio_tokenizer_type: str = "wavtokenizer",
103
+ audio_tokenizer_sample_rate: int = 24000,
104
+ streaming_sliding_window: bool = False,
105
+ streaming_sliding_window_max_text_len: int = 500,
106
+ streaming_sliding_window_average_speed: int = 5,
107
+ streaming_sliding_window_fast_speed: int = 7,
108
+ streaming_sliding_window_slow_speed: int = 3,
109
+ streaming_sliding_window_audio_frame_rate: int = 50,
110
+ streaming_sliding_window_audio_init_text_length: int = 10,
111
+ streaming_sliding_window_audio_window_size: int = 300,
112
+ normalize_projected_hidden: bool = False,
113
+ interleaved: bool = False,
114
+ attention_type: str = "sliding_recompute",
115
+ recomputed_chunks: int = 1,
116
+ window_size: int = 2,
117
+ **kwargs,
118
+ ):
119
+ super().__init__(**kwargs)
120
+
121
+ self.llm_dim = llm_dim
122
+ self.llm_hidden_size = llm_dim
123
+ self.llm_intermediate_size = llm_intermediate_size
124
+ self.llm_down_scale = llm_down_scale
125
+ self.llm_dim_model_base = llm_dim_model_base
126
+ self.projector_type = projector_type
127
+ self.aug_loss_weight = aug_loss_weight
128
+ self.aug_layer_loss_weight = aug_layer_loss_weight
129
+ self.tts_filter_loss_fix = tts_filter_loss_fix
130
+ self.filter_tts_loss = filter_tts_loss
131
+ self.long_weight = long_weight
132
+ self.short_weight = short_weight
133
+ self.hidden_act = hidden_act
134
+
135
+ self.hidden_size = hidden_size
136
+ self.intermediate_size = intermediate_size
137
+ self.num_attention_heads = num_attention_heads
138
+ self.num_hidden_layers = num_hidden_layers
139
+ self.num_key_value_heads = num_key_value_heads
140
+ self.max_position_embeddings = max_position_embeddings
141
+ self.num_audio_tokens = num_audio_tokens
142
+ self.num_text_tokens = num_text_tokens
143
+ self.num_mel_bins = num_mel_bins
144
+ self.num_vq = num_vq
145
+ self.use_llm_hidden_state = use_llm_hidden_state
146
+ self.audio_bos_token_id = audio_bos_token_id
147
+ self.text_eos_token_id = text_eos_token_id
148
+ self.use_text = use_text
149
+ self.streaming = streaming
150
+ self.streaming_text_chunk_min = streaming_text_chunk_min
151
+ self.streaming_text_chunk_max = streaming_text_chunk_max
152
+ self.streaming_text_reserved_len = streaming_text_reserved_len
153
+ self.streaming_audio_chunk_size = streaming_audio_chunk_size
154
+ self.attn_implementation = attn_implementation
155
+ self.condition_type = condition_type
156
+ self.backbone_model = backbone_model
157
+ self.audio_tokenizer_type = audio_tokenizer_type
158
+ self.audio_tokenizer_sample_rate = audio_tokenizer_sample_rate
159
+
160
+ self.streaming_sliding_window = streaming_sliding_window
161
+ self.streaming_sliding_window_max_text_len = streaming_sliding_window_max_text_len
162
+ self.streaming_sliding_window_average_speed = streaming_sliding_window_average_speed
163
+ self.streaming_sliding_window_fast_speed = streaming_sliding_window_fast_speed
164
+ self.streaming_sliding_window_slow_speed = streaming_sliding_window_slow_speed
165
+ self.streaming_sliding_window_audio_frame_rate = streaming_sliding_window_audio_frame_rate
166
+ self.streaming_sliding_window_audio_init_text_length = streaming_sliding_window_audio_init_text_length
167
+ self.streaming_sliding_window_audio_window_size = streaming_sliding_window_audio_window_size
168
+
169
+ self.normalize_projected_hidden = normalize_projected_hidden
170
+
171
+ self.interleaved = interleaved
172
+ self.attention_type = attention_type
173
+ self.recomputed_chunks = recomputed_chunks
174
+ self.window_size = window_size
175
+
176
+
177
+ class MiniCPMOConfig(Qwen3Config):
178
+ model_type = "minicpmo"
179
+ keys_to_ignore_at_inference = ["past_key_values"]
180
+
181
+ default_vision_config = {
182
+ "hidden_size": 1152,
183
+ "image_size": 980,
184
+ "intermediate_size": 4304,
185
+ "model_type": "siglip",
186
+ "num_attention_heads": 16,
187
+ "num_hidden_layers": 27,
188
+ "patch_size": 14,
189
+ }
190
+
191
+ def __init__(
192
+ self,
193
+ use_cache=True,
194
+ query_num=64,
195
+ image_size=448,
196
+ drop_vision_last_layer=True,
197
+ batch_vision_input=True,
198
+ slice_config=None,
199
+ vision_config=None,
200
+ audio_config=None,
201
+ tts_config=None,
202
+ use_image_id=True,
203
+ vision_batch_size=16,
204
+ audio_pool_step=5,
205
+ audio_chunk_length=1.0,
206
+ stream_input=False,
207
+ listen_speak_type="asr",
208
+ init_vision=True,
209
+ init_audio=True,
210
+ init_tts=True,
211
+ **kwargs,
212
+ ):
213
+ self.use_cache = use_cache
214
+ self.query_num = query_num
215
+ self.image_size = image_size
216
+ self.drop_vision_last_layer = drop_vision_last_layer
217
+ self.batch_vision_input = batch_vision_input
218
+ self.use_image_id = use_image_id
219
+ self.vision_batch_size = vision_batch_size
220
+ self.audio_pool_step = audio_pool_step
221
+ self.audio_chunk_length = audio_chunk_length
222
+ self.stream_input = stream_input
223
+ self.listen_speak_type = listen_speak_type
224
+
225
+ self.init_vision = init_vision
226
+ self.init_audio = init_audio
227
+ self.init_tts = init_tts
228
+
229
+ if slice_config is None:
230
+ self.slice_config = MiniCPMVSliceConfig(max_slice_nums=1)
231
+ else:
232
+ self.slice_config = MiniCPMVSliceConfig(**slice_config)
233
+ self.slice_mode = True
234
+
235
+ # same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit add tgt_sizes
236
+ if vision_config is None:
237
+ self.vision_config = SiglipVisionConfig(**self.default_vision_config)
238
+ logger.info("vision_config is None, using default vision config")
239
+ elif isinstance(vision_config, dict):
240
+ self.vision_config = SiglipVisionConfig(**vision_config)
241
+ elif isinstance(vision_config, SiglipVisionConfig):
242
+ self.vision_config = vision_config
243
+
244
+ if audio_config is None:
245
+ self.audio_config = WhisperConfig()
246
+ elif isinstance(audio_config, dict):
247
+ self.audio_config = WhisperConfig(**audio_config)
248
+ elif isinstance(audio_config, WhisperConfig):
249
+ self.audio_config = audio_config
250
+
251
+ if tts_config is None:
252
+ self.tts_config = MiniCPMTTSConfig()
253
+ elif isinstance(tts_config, dict):
254
+ self.tts_config = MiniCPMTTSConfig(**tts_config)
255
+ elif isinstance(tts_config, MiniCPMTTSConfig):
256
+ self.tts_config = tts_config
257
+
258
+ self.patch_size = self.vision_config.patch_size
259
+
260
+ super().__init__(**kwargs)
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.57.0"
13
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:851d5dd243ff02bfe8bd97b3b8f43dc499c3f94b4bf1b91798f992697938b54a
3
+ size 4900718032
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:537e2b3eac1f6e4192ac075e4a8ef721c091769144f5801e6d8f3b361b641fdd
3
+ size 4915960936
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed4f427cfa50c84b87f57f5617f7b7d017619c8aae6be60b6599581158daf5b6
3
+ size 4983069056
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17ef5669ee1163db56515c0d72f24c5c38e79c1ef96dd75a8886f7354ca2f1a6
3
+ size 3248573944
model-tts.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:902e46ed220539517708cc95017e3ed594025d22df5815be236cb15ca587772f
3
+ size 695415076
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_minicpmo.py ADDED
The diff for this file is too large to render. See raw diff
 
modeling_navit_siglip.py ADDED
@@ -0,0 +1,981 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google AI and The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Siglip model."""
16
+ # Copied from HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit and add tgt_sizes
17
+
18
+
19
+ import math
20
+ import os
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import Optional
24
+ from typing import Tuple
25
+ from typing import Union
26
+
27
+ import numpy as np
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn.init import _calculate_fan_in_and_fan_out
33
+ from transformers.activations import ACT2FN
34
+ from transformers.configuration_utils import PretrainedConfig
35
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
36
+ from transformers.modeling_outputs import BaseModelOutput
37
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import add_start_docstrings
40
+ from transformers.utils import add_start_docstrings_to_model_forward
41
+ from transformers.utils import is_flash_attn_2_available
42
+ from transformers.utils import logging
43
+ from transformers.utils import ModelOutput
44
+ from transformers.utils import replace_return_docstrings
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ class SiglipVisionConfig(PretrainedConfig):
50
+ r"""
51
+ This is the configuration class to store the configuration of a [`SiglipVisionModel`]. It is used to instantiate a
52
+ Siglip vision encoder according to the specified arguments, defining the model architecture. Instantiating a
53
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip
54
+ [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
55
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
56
+ documentation from [`PretrainedConfig`] for more information.
57
+ Args:
58
+ hidden_size (`int`, *optional*, defaults to 768):
59
+ Dimensionality of the encoder layers and the pooler layer.
60
+ intermediate_size (`int`, *optional*, defaults to 3072):
61
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
62
+ num_hidden_layers (`int`, *optional*, defaults to 12):
63
+ Number of hidden layers in the Transformer encoder.
64
+ num_attention_heads (`int`, *optional*, defaults to 12):
65
+ Number of attention heads for each attention layer in the Transformer encoder.
66
+ num_channels (`int`, *optional*, defaults to 3):
67
+ Number of channels in the input images.
68
+ image_size (`int`, *optional*, defaults to 224):
69
+ The size (resolution) of each image.
70
+ patch_size (`int`, *optional*, defaults to 16):
71
+ The size (resolution) of each patch.
72
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
73
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
74
+ `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
75
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
76
+ The epsilon used by the layer normalization layers.
77
+ attention_dropout (`float`, *optional*, defaults to 0.0):
78
+ The dropout ratio for the attention probabilities.
79
+ Example:
80
+ ```python
81
+ >>> from transformers import SiglipVisionConfig, SiglipVisionModel
82
+ >>> # Initializing a SiglipVisionConfig with google/siglip-base-patch16-224 style configuration
83
+ >>> configuration = SiglipVisionConfig()
84
+ >>> # Initializing a SiglipVisionModel (with random weights) from the google/siglip-base-patch16-224 style configuration
85
+ >>> model = SiglipVisionModel(configuration)
86
+ >>> # Accessing the model configuration
87
+ >>> configuration = model.config
88
+ ```"""
89
+
90
+ model_type = "siglip_vision_model"
91
+
92
+ def __init__(
93
+ self,
94
+ hidden_size=768,
95
+ intermediate_size=3072,
96
+ num_hidden_layers=12,
97
+ num_attention_heads=12,
98
+ num_channels=3,
99
+ image_size=224,
100
+ patch_size=16,
101
+ hidden_act="gelu_pytorch_tanh",
102
+ layer_norm_eps=1e-6,
103
+ attention_dropout=0.0,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(**kwargs)
107
+
108
+ self.hidden_size = hidden_size
109
+ self.intermediate_size = intermediate_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.num_channels = num_channels
113
+ self.patch_size = patch_size
114
+ self.image_size = image_size
115
+ self.attention_dropout = attention_dropout
116
+ self.layer_norm_eps = layer_norm_eps
117
+ self.hidden_act = hidden_act
118
+
119
+ @classmethod
120
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
121
+ cls._set_token_in_kwargs(kwargs)
122
+
123
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
124
+
125
+ # get the vision config dict if we are loading from SiglipConfig
126
+ if config_dict.get("model_type") == "siglip":
127
+ config_dict = config_dict["vision_config"]
128
+
129
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
130
+ logger.warning(
131
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
132
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
133
+ )
134
+
135
+ return cls.from_dict(config_dict, **kwargs)
136
+
137
+
138
+ _CHECKPOINT_FOR_DOC = "google/siglip-base-patch16-224"
139
+
140
+ SIGLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
141
+ "google/siglip-base-patch16-224",
142
+ # See all SigLIP models at https://huggingface.co/models?filter=siglip
143
+ ]
144
+
145
+ if is_flash_attn_2_available():
146
+ from flash_attn import flash_attn_func
147
+ from flash_attn import flash_attn_varlen_func
148
+ from flash_attn.bert_padding import index_first_axis # noqa
149
+ from flash_attn.bert_padding import pad_input
150
+ from flash_attn.bert_padding import unpad_input
151
+
152
+
153
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
154
+ def _get_unpad_data(attention_mask):
155
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
156
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
157
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
158
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
159
+ return (
160
+ indices,
161
+ cu_seqlens,
162
+ max_seqlen_in_batch,
163
+ )
164
+
165
+
166
+ def _trunc_normal_(tensor, mean, std, a, b):
167
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
168
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
169
+ def norm_cdf(x):
170
+ # Computes standard normal cumulative distribution function
171
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
172
+
173
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
174
+ warnings.warn(
175
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
176
+ "The distribution of values may be incorrect.",
177
+ stacklevel=2,
178
+ )
179
+
180
+ # Values are generated by using a truncated uniform distribution and
181
+ # then using the inverse CDF for the normal distribution.
182
+ # Get upper and lower cdf values
183
+ l = norm_cdf((a - mean) / std)
184
+ u = norm_cdf((b - mean) / std)
185
+
186
+ # Uniformly fill tensor with values from [l, u], then translate to
187
+ # [2l-1, 2u-1].
188
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
189
+
190
+ # Use inverse cdf transform for normal distribution to get truncated
191
+ # standard normal
192
+ if tensor.dtype in [torch.float16, torch.bfloat16]:
193
+ # The `erfinv_` op is not (yet?) defined in float16+cpu, bfloat16+gpu
194
+ og_dtype = tensor.dtype
195
+ tensor = tensor.to(torch.float32)
196
+ tensor.erfinv_()
197
+ tensor = tensor.to(og_dtype)
198
+ else:
199
+ tensor.erfinv_()
200
+
201
+ # Transform to proper mean, std
202
+ tensor.mul_(std * math.sqrt(2.0))
203
+ tensor.add_(mean)
204
+
205
+ # Clamp to ensure it's in the proper range
206
+ if tensor.dtype == torch.float16:
207
+ # The `clamp_` op is not (yet?) defined in float16+cpu
208
+ tensor = tensor.to(torch.float32)
209
+ tensor.clamp_(min=a, max=b)
210
+ tensor = tensor.to(torch.float16)
211
+ else:
212
+ tensor.clamp_(min=a, max=b)
213
+
214
+
215
+ def trunc_normal_tf_(
216
+ tensor: torch.Tensor,
217
+ mean: float = 0.0,
218
+ std: float = 1.0,
219
+ a: float = -2.0,
220
+ b: float = 2.0,
221
+ ) -> torch.Tensor:
222
+ """Fills the input Tensor with values drawn from a truncated
223
+ normal distribution. The values are effectively drawn from the
224
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
225
+ with values outside :math:`[a, b]` redrawn until they are within
226
+ the bounds. The method used for generating the random values works
227
+ best when :math:`a \\leq \text{mean} \\leq b`.
228
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
229
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
230
+ and the result is subsquently scaled and shifted by the mean and std args.
231
+ Args:
232
+ tensor: an n-dimensional `torch.Tensor`
233
+ mean: the mean of the normal distribution
234
+ std: the standard deviation of the normal distribution
235
+ a: the minimum cutoff value
236
+ b: the maximum cutoff value
237
+ """
238
+ with torch.no_grad():
239
+ _trunc_normal_(tensor, 0, 1.0, a, b)
240
+ tensor.mul_(std).add_(mean)
241
+
242
+
243
+ def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
244
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
245
+ if mode == "fan_in":
246
+ denom = fan_in
247
+ elif mode == "fan_out":
248
+ denom = fan_out
249
+ elif mode == "fan_avg":
250
+ denom = (fan_in + fan_out) / 2
251
+
252
+ variance = scale / denom
253
+
254
+ if distribution == "truncated_normal":
255
+ # constant is stddev of standard normal truncated to (-2, 2)
256
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
257
+ elif distribution == "normal":
258
+ with torch.no_grad():
259
+ tensor.normal_(std=math.sqrt(variance))
260
+ elif distribution == "uniform":
261
+ bound = math.sqrt(3 * variance)
262
+ with torch.no_grad():
263
+ tensor.uniform_(-bound, bound)
264
+ else:
265
+ raise ValueError(f"invalid distribution {distribution}")
266
+
267
+
268
+ def lecun_normal_(tensor):
269
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
270
+
271
+
272
+ def default_flax_embed_init(tensor):
273
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
274
+
275
+
276
+ @dataclass
277
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
278
+ class SiglipVisionModelOutput(ModelOutput):
279
+ """
280
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
281
+ Args:
282
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
283
+ The image embeddings obtained by applying the projection layer to the pooler_output.
284
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
285
+ Sequence of hidden-states at the output of the last layer of the model.
286
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
287
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
288
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
289
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
290
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
291
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
292
+ sequence_length)`.
293
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
294
+ heads.
295
+ """
296
+
297
+ image_embeds: Optional[torch.FloatTensor] = None
298
+ last_hidden_state: torch.FloatTensor = None
299
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
300
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
301
+
302
+
303
+ class SiglipVisionEmbeddings(nn.Module):
304
+ def __init__(self, config: SiglipVisionConfig):
305
+ super().__init__()
306
+ self.config = config
307
+ self.embed_dim = config.hidden_size
308
+ self.image_size = config.image_size
309
+ self.patch_size = config.patch_size
310
+
311
+ self.patch_embedding = nn.Conv2d(
312
+ in_channels=config.num_channels,
313
+ out_channels=self.embed_dim,
314
+ kernel_size=self.patch_size,
315
+ stride=self.patch_size,
316
+ padding="valid",
317
+ )
318
+
319
+ self.num_patches_per_side = self.image_size // self.patch_size
320
+ self.num_patches = self.num_patches_per_side**2
321
+ self.num_positions = self.num_patches
322
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
323
+
324
+ def forward(
325
+ self,
326
+ pixel_values: torch.FloatTensor,
327
+ patch_attention_mask: torch.BoolTensor,
328
+ tgt_sizes: Optional[torch.IntTensor] = None,
329
+ ) -> torch.Tensor:
330
+ batch_size = pixel_values.size(0)
331
+
332
+ patch_embeds = self.patch_embedding(pixel_values)
333
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
334
+
335
+ max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3)
336
+ max_nb_patches_h, max_nb_patches_w = (
337
+ max_im_h // self.patch_size,
338
+ max_im_w // self.patch_size,
339
+ )
340
+ boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
341
+ position_ids = torch.full(
342
+ size=(
343
+ batch_size,
344
+ max_nb_patches_h * max_nb_patches_w,
345
+ ),
346
+ fill_value=0,
347
+ )
348
+
349
+ for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
350
+ if tgt_sizes is not None:
351
+ nb_patches_h = tgt_sizes[batch_idx][0]
352
+ nb_patches_w = tgt_sizes[batch_idx][1]
353
+ else:
354
+ nb_patches_h = p_attn_mask[:, 0].sum()
355
+ nb_patches_w = p_attn_mask[0].sum()
356
+
357
+ fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
358
+ fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
359
+
360
+ bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
361
+ bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
362
+
363
+ pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
364
+ position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
365
+
366
+ position_ids = position_ids.to(self.position_embedding.weight.device)
367
+
368
+ embeddings = embeddings + self.position_embedding(position_ids)
369
+ return embeddings
370
+
371
+
372
+ class SiglipAttention(nn.Module):
373
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
374
+
375
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
376
+ def __init__(self, config):
377
+ super().__init__()
378
+ self.config = config
379
+ self.embed_dim = config.hidden_size
380
+ self.num_heads = config.num_attention_heads
381
+ self.head_dim = self.embed_dim // self.num_heads
382
+ if self.head_dim * self.num_heads != self.embed_dim:
383
+ raise ValueError(
384
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
385
+ f" {self.num_heads})."
386
+ )
387
+ self.scale = self.head_dim**-0.5
388
+ self.dropout = config.attention_dropout
389
+
390
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
391
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
392
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
393
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
394
+
395
+ def forward(
396
+ self,
397
+ hidden_states: torch.Tensor,
398
+ attention_mask: Optional[torch.Tensor] = None,
399
+ output_attentions: Optional[bool] = False,
400
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
401
+ """Input shape: Batch x Time x Channel"""
402
+
403
+ batch_size, q_len, _ = hidden_states.size()
404
+
405
+ query_states = self.q_proj(hidden_states)
406
+ key_states = self.k_proj(hidden_states)
407
+ value_states = self.v_proj(hidden_states)
408
+
409
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
410
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
411
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
412
+
413
+ k_v_seq_len = key_states.shape[-2]
414
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
415
+
416
+ if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
417
+ raise ValueError(
418
+ f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
419
+ f" {attn_weights.size()}"
420
+ )
421
+
422
+ if attention_mask is not None:
423
+ if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
424
+ raise ValueError(
425
+ f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
426
+ )
427
+ attn_weights = attn_weights + attention_mask
428
+
429
+ # upcast attention to fp32
430
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
431
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
432
+ attn_output = torch.matmul(attn_weights, value_states)
433
+
434
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
435
+ raise ValueError(
436
+ f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
437
+ f" {attn_output.size()}"
438
+ )
439
+
440
+ attn_output = attn_output.transpose(1, 2).contiguous()
441
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
442
+
443
+ attn_output = self.out_proj(attn_output)
444
+
445
+ return attn_output, attn_weights
446
+
447
+
448
+ class SiglipFlashAttention2(SiglipAttention):
449
+ """
450
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
451
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
452
+ flash attention and deal with padding tokens in case the input contains any of them.
453
+ """
454
+
455
+ def __init__(self, *args, **kwargs):
456
+ super().__init__(*args, **kwargs)
457
+ self.is_causal = False # Hack to make sure we don't use a causal mask
458
+
459
+ def forward(
460
+ self,
461
+ hidden_states: torch.Tensor,
462
+ attention_mask: Optional[torch.LongTensor] = None,
463
+ position_ids: Optional[torch.LongTensor] = None,
464
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
465
+ output_attentions: bool = False,
466
+ use_cache: bool = False,
467
+ **kwargs,
468
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
469
+ output_attentions = False
470
+
471
+ bsz, q_len, _ = hidden_states.size()
472
+
473
+ query_states = self.q_proj(hidden_states)
474
+ key_states = self.k_proj(hidden_states)
475
+ value_states = self.v_proj(hidden_states)
476
+
477
+ # Flash attention requires the input to have the shape
478
+ # batch_size x seq_length x head_dim x hidden_dim
479
+ # therefore we just need to keep the original shape
480
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
481
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
482
+ value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
483
+
484
+ kv_seq_len = key_states.shape[-2]
485
+ if past_key_value is not None:
486
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
487
+ # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
488
+ # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
489
+
490
+ # if past_key_value is not None:
491
+ # cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
492
+ # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
493
+
494
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
495
+ # to be able to avoid many of these transpose/reshape/view.
496
+ query_states = query_states.transpose(1, 2)
497
+ key_states = key_states.transpose(1, 2)
498
+ value_states = value_states.transpose(1, 2)
499
+
500
+ dropout_rate = self.dropout if self.training else 0.0
501
+
502
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
503
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
504
+ # cast them back in the correct dtype just to be sure everything works as expected.
505
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
506
+ # in fp32. (LlamaRMSNorm handles it correctly)
507
+
508
+ input_dtype = query_states.dtype
509
+ if input_dtype == torch.float32:
510
+ if torch.is_autocast_enabled():
511
+ target_dtype = torch.get_autocast_gpu_dtype()
512
+ # Handle the case where the model is quantized
513
+ elif hasattr(self.config, "_pre_quantization_dtype"):
514
+ target_dtype = self.config._pre_quantization_dtype
515
+ else:
516
+ target_dtype = self.q_proj.weight.dtype
517
+
518
+ logger.warning_once(
519
+ "The input hidden states seems to be silently casted in float32, this might be related to the fact"
520
+ " you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
521
+ f" {target_dtype}."
522
+ )
523
+
524
+ query_states = query_states.to(target_dtype)
525
+ key_states = key_states.to(target_dtype)
526
+ value_states = value_states.to(target_dtype)
527
+
528
+ attn_output = self._flash_attention_forward(
529
+ query_states,
530
+ key_states,
531
+ value_states,
532
+ attention_mask,
533
+ q_len,
534
+ dropout=dropout_rate,
535
+ )
536
+
537
+ attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
538
+ attn_output = self.out_proj(attn_output)
539
+
540
+ if not output_attentions:
541
+ attn_weights = None
542
+
543
+ return attn_output, attn_weights
544
+
545
+ def _flash_attention_forward(
546
+ self,
547
+ query_states,
548
+ key_states,
549
+ value_states,
550
+ attention_mask,
551
+ query_length,
552
+ dropout=0.0,
553
+ softmax_scale=None,
554
+ ):
555
+ """
556
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
557
+ first unpad the input, then computes the attention scores and pad the final attention scores.
558
+ Args:
559
+ query_states (`torch.Tensor`):
560
+ Input query states to be passed to Flash Attention API
561
+ key_states (`torch.Tensor`):
562
+ Input key states to be passed to Flash Attention API
563
+ value_states (`torch.Tensor`):
564
+ Input value states to be passed to Flash Attention API
565
+ attention_mask (`torch.Tensor`):
566
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
567
+ position of padding tokens and 1 for the position of non-padding tokens.
568
+ dropout (`int`, *optional*):
569
+ Attention dropout
570
+ softmax_scale (`float`, *optional*):
571
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
572
+ """
573
+
574
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
575
+ causal = self.is_causal and query_length != 1
576
+
577
+ # Contains at least one padding token in the sequence
578
+ if attention_mask is not None:
579
+ batch_size = query_states.shape[0]
580
+ (
581
+ query_states,
582
+ key_states,
583
+ value_states,
584
+ indices_q,
585
+ cu_seq_lens,
586
+ max_seq_lens,
587
+ ) = self._upad_input(query_states, key_states, value_states, attention_mask, query_length)
588
+
589
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
590
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
591
+
592
+ attn_output_unpad = flash_attn_varlen_func(
593
+ query_states,
594
+ key_states,
595
+ value_states,
596
+ cu_seqlens_q=cu_seqlens_q,
597
+ cu_seqlens_k=cu_seqlens_k,
598
+ max_seqlen_q=max_seqlen_in_batch_q,
599
+ max_seqlen_k=max_seqlen_in_batch_k,
600
+ dropout_p=dropout,
601
+ softmax_scale=softmax_scale,
602
+ causal=causal,
603
+ )
604
+
605
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
606
+ else:
607
+ attn_output = flash_attn_func(
608
+ query_states,
609
+ key_states,
610
+ value_states,
611
+ dropout,
612
+ softmax_scale=softmax_scale,
613
+ causal=causal,
614
+ )
615
+
616
+ return attn_output
617
+
618
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
619
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
620
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
621
+
622
+ key_layer = index_first_axis(
623
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
624
+ indices_k,
625
+ )
626
+ value_layer = index_first_axis(
627
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
628
+ indices_k,
629
+ )
630
+ if query_length == kv_seq_len:
631
+ query_layer = index_first_axis(
632
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
633
+ indices_k,
634
+ )
635
+ cu_seqlens_q = cu_seqlens_k
636
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
637
+ indices_q = indices_k
638
+ elif query_length == 1:
639
+ max_seqlen_in_batch_q = 1
640
+ cu_seqlens_q = torch.arange(
641
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
642
+ ) # There is a memcpy here, that is very bad.
643
+ indices_q = cu_seqlens_q[:-1]
644
+ query_layer = query_layer.squeeze(1)
645
+ else:
646
+ # The -q_len: slice assumes left padding.
647
+ attention_mask = attention_mask[:, -query_length:]
648
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
649
+
650
+ return (
651
+ query_layer,
652
+ key_layer,
653
+ value_layer,
654
+ indices_q,
655
+ (cu_seqlens_q, cu_seqlens_k),
656
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
657
+ )
658
+
659
+
660
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
661
+ class SiglipMLP(nn.Module):
662
+ def __init__(self, config):
663
+ super().__init__()
664
+ self.config = config
665
+ self.activation_fn = ACT2FN[config.hidden_act]
666
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
667
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
668
+
669
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
670
+ hidden_states = self.fc1(hidden_states)
671
+ hidden_states = self.activation_fn(hidden_states)
672
+ hidden_states = self.fc2(hidden_states)
673
+ return hidden_states
674
+
675
+
676
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
677
+ class SiglipEncoderLayer(nn.Module):
678
+ def __init__(self, config: SiglipVisionConfig):
679
+ super().__init__()
680
+ self.embed_dim = config.hidden_size
681
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
682
+ self.self_attn = SiglipAttention(config) if not self._use_flash_attention_2 else SiglipFlashAttention2(config)
683
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
684
+ self.mlp = SiglipMLP(config)
685
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
686
+
687
+ def forward(
688
+ self,
689
+ hidden_states: torch.Tensor,
690
+ attention_mask: torch.Tensor,
691
+ output_attentions: Optional[bool] = False,
692
+ ) -> Tuple[torch.FloatTensor]:
693
+ """
694
+ Args:
695
+ hidden_states (`torch.FloatTensor`):
696
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
697
+ attention_mask (`torch.FloatTensor`):
698
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
699
+ output_attentions (`bool`, *optional*, defaults to `False`):
700
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
701
+ returned tensors for more detail.
702
+ """
703
+ residual = hidden_states
704
+
705
+ hidden_states = self.layer_norm1(hidden_states)
706
+ hidden_states, attn_weights = self.self_attn(
707
+ hidden_states=hidden_states,
708
+ attention_mask=attention_mask,
709
+ output_attentions=output_attentions,
710
+ )
711
+ hidden_states = residual + hidden_states
712
+
713
+ residual = hidden_states
714
+ hidden_states = self.layer_norm2(hidden_states)
715
+ hidden_states = self.mlp(hidden_states)
716
+ hidden_states = residual + hidden_states
717
+
718
+ outputs = (hidden_states,)
719
+
720
+ if output_attentions:
721
+ outputs += (attn_weights,)
722
+
723
+ return outputs
724
+
725
+
726
+ class SiglipPreTrainedModel(PreTrainedModel):
727
+ """
728
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
729
+ models.
730
+ """
731
+
732
+ config_class = SiglipVisionConfig
733
+ base_model_prefix = "siglip"
734
+ supports_gradient_checkpointing = True
735
+
736
+ def _init_weights(self, module):
737
+ """Initialize the weights"""
738
+
739
+ if isinstance(module, SiglipVisionEmbeddings):
740
+ width = self.config.hidden_size
741
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
742
+ elif isinstance(module, nn.Embedding):
743
+ default_flax_embed_init(module.weight)
744
+ elif isinstance(module, SiglipAttention):
745
+ nn.init.normal_(module.q_proj.weight)
746
+ nn.init.normal_(module.k_proj.weight)
747
+ nn.init.normal_(module.v_proj.weight)
748
+ nn.init.normal_(module.out_proj.weight)
749
+ nn.init.zeros_(module.q_proj.bias)
750
+ nn.init.zeros_(module.k_proj.bias)
751
+ nn.init.zeros_(module.v_proj.bias)
752
+ nn.init.zeros_(module.out_proj.bias)
753
+ elif isinstance(module, SiglipMLP):
754
+ nn.init.normal_(module.fc1.weight)
755
+ nn.init.normal_(module.fc2.weight)
756
+ nn.init.normal_(module.fc1.bias, std=1e-6)
757
+ nn.init.normal_(module.fc2.bias, std=1e-6)
758
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
759
+ lecun_normal_(module.weight)
760
+ if module.bias is not None:
761
+ nn.init.zeros_(module.bias)
762
+ elif isinstance(module, nn.LayerNorm):
763
+ module.bias.data.zero_()
764
+ module.weight.data.fill_(1.0)
765
+
766
+
767
+ SIGLIP_START_DOCSTRING = r"""
768
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
769
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
770
+ etc.)
771
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
772
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
773
+ and behavior.
774
+ Parameters:
775
+ config ([`SiglipVisionConfig`]): Model configuration class with all the parameters of the model.
776
+ Initializing with a config file does not load the weights associated with the model, only the
777
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
778
+ """
779
+
780
+
781
+ SIGLIP_VISION_INPUTS_DOCSTRING = r"""
782
+ Args:
783
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
784
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
785
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
786
+ output_attentions (`bool`, *optional*):
787
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
788
+ tensors for more detail.
789
+ output_hidden_states (`bool`, *optional*):
790
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
791
+ more detail.
792
+ return_dict (`bool`, *optional*):
793
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
794
+ """
795
+
796
+
797
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
798
+ class SiglipEncoder(nn.Module):
799
+ """
800
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
801
+ [`SiglipEncoderLayer`].
802
+ Args:
803
+ config: SiglipConfig
804
+ """
805
+
806
+ def __init__(self, config: SiglipVisionConfig):
807
+ super().__init__()
808
+ self.config = config
809
+ self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
810
+ self.gradient_checkpointing = False
811
+
812
+ # Ignore copy
813
+ def forward(
814
+ self,
815
+ inputs_embeds,
816
+ attention_mask: Optional[torch.Tensor] = None,
817
+ output_attentions: Optional[bool] = None,
818
+ output_hidden_states: Optional[bool] = None,
819
+ return_dict: Optional[bool] = None,
820
+ ) -> Union[Tuple, BaseModelOutput]:
821
+ r"""
822
+ Args:
823
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
824
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
825
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
826
+ than the model's internal embedding lookup matrix.
827
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
828
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
829
+ - 1 for tokens that are **not masked**,
830
+ - 0 for tokens that are **masked**.
831
+ [What are attention masks?](../glossary#attention-mask)
832
+ output_attentions (`bool`, *optional*):
833
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
834
+ returned tensors for more detail.
835
+ output_hidden_states (`bool`, *optional*):
836
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
837
+ for more detail.
838
+ return_dict (`bool`, *optional*):
839
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
840
+ """
841
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
842
+ output_hidden_states = (
843
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
844
+ )
845
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
846
+
847
+ encoder_states = () if output_hidden_states else None
848
+ all_attentions = () if output_attentions else None
849
+
850
+ hidden_states = inputs_embeds
851
+ for encoder_layer in self.layers:
852
+ if output_hidden_states:
853
+ encoder_states = encoder_states + (hidden_states,)
854
+ if self.gradient_checkpointing and self.training:
855
+ layer_outputs = self._gradient_checkpointing_func(
856
+ encoder_layer.__call__,
857
+ hidden_states,
858
+ attention_mask,
859
+ output_attentions,
860
+ )
861
+ else:
862
+ layer_outputs = encoder_layer(
863
+ hidden_states,
864
+ attention_mask,
865
+ output_attentions=output_attentions,
866
+ )
867
+
868
+ hidden_states = layer_outputs[0]
869
+
870
+ if output_attentions:
871
+ all_attentions = all_attentions + (layer_outputs[1],)
872
+
873
+ if output_hidden_states:
874
+ encoder_states = encoder_states + (hidden_states,)
875
+
876
+ if not return_dict:
877
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
878
+ return BaseModelOutput(
879
+ last_hidden_state=hidden_states,
880
+ hidden_states=encoder_states,
881
+ attentions=all_attentions,
882
+ )
883
+
884
+
885
+ @add_start_docstrings(
886
+ """The vision model from SigLIP without any head or projection on top.""",
887
+ SIGLIP_START_DOCSTRING,
888
+ )
889
+ class SiglipVisionTransformer(SiglipPreTrainedModel):
890
+ config_class = SiglipVisionConfig
891
+ main_input_name = "pixel_values"
892
+ _supports_flash_attn_2 = True
893
+ _no_split_modules = []
894
+
895
+ def __init__(self, config: SiglipVisionConfig):
896
+ super().__init__(config)
897
+ self.config = config
898
+ embed_dim = config.hidden_size
899
+
900
+ self.embeddings = SiglipVisionEmbeddings(config)
901
+ self.encoder = SiglipEncoder(config)
902
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
903
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
904
+
905
+ # Initialize weights and apply final processing
906
+ self.post_init()
907
+
908
+ def get_input_embeddings(self) -> nn.Module:
909
+ return self.embeddings.patch_embedding
910
+
911
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
912
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
913
+ def forward(
914
+ self,
915
+ pixel_values,
916
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
917
+ tgt_sizes: Optional[torch.IntTensor] = None,
918
+ output_attentions: Optional[bool] = None,
919
+ output_hidden_states: Optional[bool] = None,
920
+ return_dict: Optional[bool] = None,
921
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
922
+ r"""
923
+ Returns:
924
+ """
925
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
926
+ output_hidden_states = (
927
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
928
+ )
929
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
930
+
931
+ batch_size = pixel_values.size(0)
932
+ if patch_attention_mask is None:
933
+ patch_attention_mask = torch.ones(
934
+ size=(
935
+ batch_size,
936
+ pixel_values.size(2) // self.config.patch_size,
937
+ pixel_values.size(3) // self.config.patch_size,
938
+ ),
939
+ dtype=torch.bool,
940
+ device=pixel_values.device,
941
+ )
942
+
943
+ hidden_states = self.embeddings(
944
+ pixel_values=pixel_values,
945
+ patch_attention_mask=patch_attention_mask,
946
+ tgt_sizes=tgt_sizes,
947
+ )
948
+
949
+ patch_attention_mask = patch_attention_mask.view(batch_size, -1)
950
+ # The call to `_upad_input` in `_flash_attention_forward` is expensive
951
+ # So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
952
+ # avoiding passing the attention_mask, which is equivalent to attending to the full sequence
953
+ if not torch.any(~patch_attention_mask):
954
+ attention_mask = None
955
+ else:
956
+ attention_mask = (
957
+ _prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
958
+ if not self._use_flash_attention_2
959
+ else patch_attention_mask
960
+ )
961
+
962
+ encoder_outputs = self.encoder(
963
+ inputs_embeds=hidden_states,
964
+ attention_mask=attention_mask,
965
+ output_attentions=output_attentions,
966
+ output_hidden_states=output_hidden_states,
967
+ return_dict=return_dict,
968
+ )
969
+
970
+ last_hidden_state = encoder_outputs[0]
971
+ last_hidden_state = self.post_layernorm(last_hidden_state)
972
+
973
+ if not return_dict:
974
+ return (last_hidden_state, None) + encoder_outputs[1:]
975
+
976
+ return BaseModelOutputWithPooling(
977
+ last_hidden_state=last_hidden_state,
978
+ pooler_output=None,
979
+ hidden_states=encoder_outputs.hidden_states,
980
+ attentions=encoder_outputs.attentions,
981
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "audio_pool_step": 5,
3
+ "auto_map": {
4
+ "AutoFeatureExtractor": "processing_minicpmo.MiniCPMAAudioProcessor",
5
+ "AutoImageProcessor": "processing_minicpmo.MiniCPMVImageProcessor",
6
+ "AutoProcessor": "processing_minicpmo.MiniCPMOProcessor"
7
+ },
8
+ "chunk_length": 30,
9
+ "dither": 0.0,
10
+ "dynamic_log_norm": true,
11
+ "dynamic_range_db": 8.0,
12
+ "feature_extractor_type": "MiniCPMAAudioProcessor",
13
+ "feature_size": 80,
14
+ "hop_length": 160,
15
+ "im_end": "</image>",
16
+ "im_id_end": "</image_id>",
17
+ "im_id_start": "<image_id>",
18
+ "im_start": "<image>",
19
+ "image_feature_size": 64,
20
+ "image_processor_type": "MiniCPMVImageProcessor",
21
+ "log_floor_db": -10.0,
22
+ "max_slice_nums": 9,
23
+ "n_fft": 400,
24
+ "n_samples": 480000,
25
+ "nb_max_frames": 3000,
26
+ "norm_mean": [
27
+ 0.5,
28
+ 0.5,
29
+ 0.5
30
+ ],
31
+ "norm_std": [
32
+ 0.5,
33
+ 0.5,
34
+ 0.5
35
+ ],
36
+ "padding_side": "right",
37
+ "padding_value": 0.0,
38
+ "patch_size": 14,
39
+ "processor_class": "MiniCPMOProcessor",
40
+ "return_attention_mask": false,
41
+ "sampling_rate": 16000,
42
+ "scale_resolution": 448,
43
+ "slice_end": "</slice>",
44
+ "slice_mode": true,
45
+ "slice_start": "<slice>",
46
+ "unk": "<unk>",
47
+ "use_image_id": true,
48
+ "version": 4.5
49
+ }