Upload folder using huggingface_hub
Browse files- .gitattributes +2 -0
- README.md +9 -0
- added_tokens.json +4 -0
- config.json +283 -0
- generation_config.json +9 -0
- model.safetensors +3 -0
- special_tokens_map.json +42 -0
- text_model/README.md +256 -0
- text_model/chat_template.json +3 -0
- text_model/config.json +264 -0
- text_model/generation_config.json +13 -0
- text_model/model-00001-of-00007.safetensors +3 -0
- text_model/model-00002-of-00007.safetensors +3 -0
- text_model/model-00003-of-00007.safetensors +3 -0
- text_model/model-00004-of-00007.safetensors +3 -0
- text_model/model-00005-of-00007.safetensors +3 -0
- text_model/model-00006-of-00007.safetensors +3 -0
- text_model/model-00007-of-00007.safetensors +3 -0
- text_model/model.safetensors.index.json +0 -0
- text_model/preprocessor_config.json +29 -0
- text_model/processor_config.json +4 -0
- text_model/recipe.yaml +12 -0
- text_model/special_tokens_map.json +33 -0
- text_model/tokenizer.json +3 -0
- text_model/tokenizer_config.json +0 -0
- tokenizer.json +3 -0
- tokenizer.model +3 -0
- tokenizer_config.json +0 -0
- ultravox_config.py +201 -0
- ultravox_model.py +976 -0
- ultravox_pipeline.py +130 -0
- ultravox_processing.py +382 -0
- ultravox_tokenizer.py +25 -0
.gitattributes
CHANGED
@@ -33,3 +33,5 @@ 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 |
+
text_model/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
37 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language:
|
3 |
+
- tr
|
4 |
+
license: mit
|
5 |
+
library_name: transformers
|
6 |
+
metrics:
|
7 |
+
- bleu
|
8 |
+
pipeline_tag: audio-text-to-text
|
9 |
+
---
|
added_tokens.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"<image_soft_token>": 262144,
|
3 |
+
"<|audio|>": 262145
|
4 |
+
}
|
config.json
ADDED
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"UltravoxModel"
|
4 |
+
],
|
5 |
+
"audio_config": {
|
6 |
+
"_name_or_path": "openai/whisper-large-v3-turbo",
|
7 |
+
"activation_dropout": 0.0,
|
8 |
+
"activation_function": "gelu",
|
9 |
+
"apply_spec_augment": false,
|
10 |
+
"architectures": [
|
11 |
+
"WhisperForConditionalGeneration"
|
12 |
+
],
|
13 |
+
"attention_dropout": 0.0,
|
14 |
+
"bos_token_id": 50257,
|
15 |
+
"classifier_proj_size": 256,
|
16 |
+
"d_model": 1280,
|
17 |
+
"decoder_attention_heads": 20,
|
18 |
+
"decoder_ffn_dim": 5120,
|
19 |
+
"decoder_layerdrop": 0.0,
|
20 |
+
"decoder_layers": 4,
|
21 |
+
"decoder_start_token_id": 50258,
|
22 |
+
"dropout": 0.0,
|
23 |
+
"encoder_attention_heads": 20,
|
24 |
+
"encoder_ffn_dim": 5120,
|
25 |
+
"encoder_layerdrop": 0.0,
|
26 |
+
"encoder_layers": 32,
|
27 |
+
"eos_token_id": 50257,
|
28 |
+
"init_std": 0.02,
|
29 |
+
"mask_feature_length": 10,
|
30 |
+
"mask_feature_min_masks": 0,
|
31 |
+
"mask_feature_prob": 0.0,
|
32 |
+
"mask_time_length": 10,
|
33 |
+
"mask_time_min_masks": 2,
|
34 |
+
"mask_time_prob": 0.05,
|
35 |
+
"max_source_positions": 1500,
|
36 |
+
"max_target_positions": 448,
|
37 |
+
"median_filter_width": 7,
|
38 |
+
"model_type": "whisper",
|
39 |
+
"num_hidden_layers": 32,
|
40 |
+
"num_mel_bins": 128,
|
41 |
+
"pad_token_id": 50257,
|
42 |
+
"scale_embedding": false,
|
43 |
+
"torch_dtype": "float16",
|
44 |
+
"use_cache": true,
|
45 |
+
"use_weighted_layer_sum": false,
|
46 |
+
"vocab_size": 51866
|
47 |
+
},
|
48 |
+
"audio_latency_block_size": null,
|
49 |
+
"audio_model_id": null,
|
50 |
+
"audio_token_index": 262145,
|
51 |
+
"auto_map": {
|
52 |
+
"AutoConfig": "ultravox_config.UltravoxConfig",
|
53 |
+
"AutoModel": "ultravox_model.UltravoxModel",
|
54 |
+
"AutoProcessor": "ultravox_processing.UltravoxProcessor"
|
55 |
+
},
|
56 |
+
"custom_pipelines": {
|
57 |
+
"ultravox-pipeline": {
|
58 |
+
"impl": "ultravox_pipeline.UltravoxPipeline",
|
59 |
+
"pt": [
|
60 |
+
"AutoModel"
|
61 |
+
],
|
62 |
+
"tf": [],
|
63 |
+
"type": "multimodal"
|
64 |
+
}
|
65 |
+
},
|
66 |
+
"hidden_size": 4096,
|
67 |
+
"ignore_index": -100,
|
68 |
+
"initializer_range": 0.02,
|
69 |
+
"model_type": "ultravox",
|
70 |
+
"norm_init": 0.4,
|
71 |
+
"pad_token_id": 1,
|
72 |
+
"projector_act": "swiglu",
|
73 |
+
"projector_ln_mid": true,
|
74 |
+
"stack_factor": 8,
|
75 |
+
"text_model_id": "./text_model",
|
76 |
+
"torch_dtype": "float16",
|
77 |
+
"transformers_version": "4.51.3",
|
78 |
+
"vocab_size": 262208,
|
79 |
+
"quantization_config": {
|
80 |
+
"config_groups": {
|
81 |
+
"group_0": {
|
82 |
+
"input_activations": {
|
83 |
+
"actorder": null,
|
84 |
+
"block_structure": null,
|
85 |
+
"dynamic": true,
|
86 |
+
"group_size": null,
|
87 |
+
"num_bits": 8,
|
88 |
+
"observer": null,
|
89 |
+
"observer_kwargs": {},
|
90 |
+
"strategy": "token",
|
91 |
+
"symmetric": true,
|
92 |
+
"type": "int"
|
93 |
+
},
|
94 |
+
"output_activations": null,
|
95 |
+
"targets": [
|
96 |
+
"Linear"
|
97 |
+
],
|
98 |
+
"weights": {
|
99 |
+
"actorder": null,
|
100 |
+
"block_structure": null,
|
101 |
+
"dynamic": false,
|
102 |
+
"group_size": null,
|
103 |
+
"num_bits": 8,
|
104 |
+
"observer": "mse",
|
105 |
+
"observer_kwargs": {},
|
106 |
+
"strategy": "channel",
|
107 |
+
"symmetric": true,
|
108 |
+
"type": "int"
|
109 |
+
}
|
110 |
+
}
|
111 |
+
},
|
112 |
+
"format": "int-quantized",
|
113 |
+
"global_compression_ratio": null,
|
114 |
+
"ignore": [
|
115 |
+
"vision_tower.vision_model.encoder.layers.0.self_attn.k_proj",
|
116 |
+
"vision_tower.vision_model.encoder.layers.0.self_attn.v_proj",
|
117 |
+
"vision_tower.vision_model.encoder.layers.0.self_attn.q_proj",
|
118 |
+
"vision_tower.vision_model.encoder.layers.0.self_attn.out_proj",
|
119 |
+
"vision_tower.vision_model.encoder.layers.0.mlp.fc1",
|
120 |
+
"vision_tower.vision_model.encoder.layers.0.mlp.fc2",
|
121 |
+
"vision_tower.vision_model.encoder.layers.1.self_attn.k_proj",
|
122 |
+
"vision_tower.vision_model.encoder.layers.1.self_attn.v_proj",
|
123 |
+
"vision_tower.vision_model.encoder.layers.1.self_attn.q_proj",
|
124 |
+
"vision_tower.vision_model.encoder.layers.1.self_attn.out_proj",
|
125 |
+
"vision_tower.vision_model.encoder.layers.1.mlp.fc1",
|
126 |
+
"vision_tower.vision_model.encoder.layers.1.mlp.fc2",
|
127 |
+
"vision_tower.vision_model.encoder.layers.2.self_attn.k_proj",
|
128 |
+
"vision_tower.vision_model.encoder.layers.2.self_attn.v_proj",
|
129 |
+
"vision_tower.vision_model.encoder.layers.2.self_attn.q_proj",
|
130 |
+
"vision_tower.vision_model.encoder.layers.2.self_attn.out_proj",
|
131 |
+
"vision_tower.vision_model.encoder.layers.2.mlp.fc1",
|
132 |
+
"vision_tower.vision_model.encoder.layers.2.mlp.fc2",
|
133 |
+
"vision_tower.vision_model.encoder.layers.3.self_attn.k_proj",
|
134 |
+
"vision_tower.vision_model.encoder.layers.3.self_attn.v_proj",
|
135 |
+
"vision_tower.vision_model.encoder.layers.3.self_attn.q_proj",
|
136 |
+
"vision_tower.vision_model.encoder.layers.3.self_attn.out_proj",
|
137 |
+
"vision_tower.vision_model.encoder.layers.3.mlp.fc1",
|
138 |
+
"vision_tower.vision_model.encoder.layers.3.mlp.fc2",
|
139 |
+
"vision_tower.vision_model.encoder.layers.4.self_attn.k_proj",
|
140 |
+
"vision_tower.vision_model.encoder.layers.4.self_attn.v_proj",
|
141 |
+
"vision_tower.vision_model.encoder.layers.4.self_attn.q_proj",
|
142 |
+
"vision_tower.vision_model.encoder.layers.4.self_attn.out_proj",
|
143 |
+
"vision_tower.vision_model.encoder.layers.4.mlp.fc1",
|
144 |
+
"vision_tower.vision_model.encoder.layers.4.mlp.fc2",
|
145 |
+
"vision_tower.vision_model.encoder.layers.5.self_attn.k_proj",
|
146 |
+
"vision_tower.vision_model.encoder.layers.5.self_attn.v_proj",
|
147 |
+
"vision_tower.vision_model.encoder.layers.5.self_attn.q_proj",
|
148 |
+
"vision_tower.vision_model.encoder.layers.5.self_attn.out_proj",
|
149 |
+
"vision_tower.vision_model.encoder.layers.5.mlp.fc1",
|
150 |
+
"vision_tower.vision_model.encoder.layers.5.mlp.fc2",
|
151 |
+
"vision_tower.vision_model.encoder.layers.6.self_attn.k_proj",
|
152 |
+
"vision_tower.vision_model.encoder.layers.6.self_attn.v_proj",
|
153 |
+
"vision_tower.vision_model.encoder.layers.6.self_attn.q_proj",
|
154 |
+
"vision_tower.vision_model.encoder.layers.6.self_attn.out_proj",
|
155 |
+
"vision_tower.vision_model.encoder.layers.6.mlp.fc1",
|
156 |
+
"vision_tower.vision_model.encoder.layers.6.mlp.fc2",
|
157 |
+
"vision_tower.vision_model.encoder.layers.7.self_attn.k_proj",
|
158 |
+
"vision_tower.vision_model.encoder.layers.7.self_attn.v_proj",
|
159 |
+
"vision_tower.vision_model.encoder.layers.7.self_attn.q_proj",
|
160 |
+
"vision_tower.vision_model.encoder.layers.7.self_attn.out_proj",
|
161 |
+
"vision_tower.vision_model.encoder.layers.7.mlp.fc1",
|
162 |
+
"vision_tower.vision_model.encoder.layers.7.mlp.fc2",
|
163 |
+
"vision_tower.vision_model.encoder.layers.8.self_attn.k_proj",
|
164 |
+
"vision_tower.vision_model.encoder.layers.8.self_attn.v_proj",
|
165 |
+
"vision_tower.vision_model.encoder.layers.8.self_attn.q_proj",
|
166 |
+
"vision_tower.vision_model.encoder.layers.8.self_attn.out_proj",
|
167 |
+
"vision_tower.vision_model.encoder.layers.8.mlp.fc1",
|
168 |
+
"vision_tower.vision_model.encoder.layers.8.mlp.fc2",
|
169 |
+
"vision_tower.vision_model.encoder.layers.9.self_attn.k_proj",
|
170 |
+
"vision_tower.vision_model.encoder.layers.9.self_attn.v_proj",
|
171 |
+
"vision_tower.vision_model.encoder.layers.9.self_attn.q_proj",
|
172 |
+
"vision_tower.vision_model.encoder.layers.9.self_attn.out_proj",
|
173 |
+
"vision_tower.vision_model.encoder.layers.9.mlp.fc1",
|
174 |
+
"vision_tower.vision_model.encoder.layers.9.mlp.fc2",
|
175 |
+
"vision_tower.vision_model.encoder.layers.10.self_attn.k_proj",
|
176 |
+
"vision_tower.vision_model.encoder.layers.10.self_attn.v_proj",
|
177 |
+
"vision_tower.vision_model.encoder.layers.10.self_attn.q_proj",
|
178 |
+
"vision_tower.vision_model.encoder.layers.10.self_attn.out_proj",
|
179 |
+
"vision_tower.vision_model.encoder.layers.10.mlp.fc1",
|
180 |
+
"vision_tower.vision_model.encoder.layers.10.mlp.fc2",
|
181 |
+
"vision_tower.vision_model.encoder.layers.11.self_attn.k_proj",
|
182 |
+
"vision_tower.vision_model.encoder.layers.11.self_attn.v_proj",
|
183 |
+
"vision_tower.vision_model.encoder.layers.11.self_attn.q_proj",
|
184 |
+
"vision_tower.vision_model.encoder.layers.11.self_attn.out_proj",
|
185 |
+
"vision_tower.vision_model.encoder.layers.11.mlp.fc1",
|
186 |
+
"vision_tower.vision_model.encoder.layers.11.mlp.fc2",
|
187 |
+
"vision_tower.vision_model.encoder.layers.12.self_attn.k_proj",
|
188 |
+
"vision_tower.vision_model.encoder.layers.12.self_attn.v_proj",
|
189 |
+
"vision_tower.vision_model.encoder.layers.12.self_attn.q_proj",
|
190 |
+
"vision_tower.vision_model.encoder.layers.12.self_attn.out_proj",
|
191 |
+
"vision_tower.vision_model.encoder.layers.12.mlp.fc1",
|
192 |
+
"vision_tower.vision_model.encoder.layers.12.mlp.fc2",
|
193 |
+
"vision_tower.vision_model.encoder.layers.13.self_attn.k_proj",
|
194 |
+
"vision_tower.vision_model.encoder.layers.13.self_attn.v_proj",
|
195 |
+
"vision_tower.vision_model.encoder.layers.13.self_attn.q_proj",
|
196 |
+
"vision_tower.vision_model.encoder.layers.13.self_attn.out_proj",
|
197 |
+
"vision_tower.vision_model.encoder.layers.13.mlp.fc1",
|
198 |
+
"vision_tower.vision_model.encoder.layers.13.mlp.fc2",
|
199 |
+
"vision_tower.vision_model.encoder.layers.14.self_attn.k_proj",
|
200 |
+
"vision_tower.vision_model.encoder.layers.14.self_attn.v_proj",
|
201 |
+
"vision_tower.vision_model.encoder.layers.14.self_attn.q_proj",
|
202 |
+
"vision_tower.vision_model.encoder.layers.14.self_attn.out_proj",
|
203 |
+
"vision_tower.vision_model.encoder.layers.14.mlp.fc1",
|
204 |
+
"vision_tower.vision_model.encoder.layers.14.mlp.fc2",
|
205 |
+
"vision_tower.vision_model.encoder.layers.15.self_attn.k_proj",
|
206 |
+
"vision_tower.vision_model.encoder.layers.15.self_attn.v_proj",
|
207 |
+
"vision_tower.vision_model.encoder.layers.15.self_attn.q_proj",
|
208 |
+
"vision_tower.vision_model.encoder.layers.15.self_attn.out_proj",
|
209 |
+
"vision_tower.vision_model.encoder.layers.15.mlp.fc1",
|
210 |
+
"vision_tower.vision_model.encoder.layers.15.mlp.fc2",
|
211 |
+
"vision_tower.vision_model.encoder.layers.16.self_attn.k_proj",
|
212 |
+
"vision_tower.vision_model.encoder.layers.16.self_attn.v_proj",
|
213 |
+
"vision_tower.vision_model.encoder.layers.16.self_attn.q_proj",
|
214 |
+
"vision_tower.vision_model.encoder.layers.16.self_attn.out_proj",
|
215 |
+
"vision_tower.vision_model.encoder.layers.16.mlp.fc1",
|
216 |
+
"vision_tower.vision_model.encoder.layers.16.mlp.fc2",
|
217 |
+
"vision_tower.vision_model.encoder.layers.17.self_attn.k_proj",
|
218 |
+
"vision_tower.vision_model.encoder.layers.17.self_attn.v_proj",
|
219 |
+
"vision_tower.vision_model.encoder.layers.17.self_attn.q_proj",
|
220 |
+
"vision_tower.vision_model.encoder.layers.17.self_attn.out_proj",
|
221 |
+
"vision_tower.vision_model.encoder.layers.17.mlp.fc1",
|
222 |
+
"vision_tower.vision_model.encoder.layers.17.mlp.fc2",
|
223 |
+
"vision_tower.vision_model.encoder.layers.18.self_attn.k_proj",
|
224 |
+
"vision_tower.vision_model.encoder.layers.18.self_attn.v_proj",
|
225 |
+
"vision_tower.vision_model.encoder.layers.18.self_attn.q_proj",
|
226 |
+
"vision_tower.vision_model.encoder.layers.18.self_attn.out_proj",
|
227 |
+
"vision_tower.vision_model.encoder.layers.18.mlp.fc1",
|
228 |
+
"vision_tower.vision_model.encoder.layers.18.mlp.fc2",
|
229 |
+
"vision_tower.vision_model.encoder.layers.19.self_attn.k_proj",
|
230 |
+
"vision_tower.vision_model.encoder.layers.19.self_attn.v_proj",
|
231 |
+
"vision_tower.vision_model.encoder.layers.19.self_attn.q_proj",
|
232 |
+
"vision_tower.vision_model.encoder.layers.19.self_attn.out_proj",
|
233 |
+
"vision_tower.vision_model.encoder.layers.19.mlp.fc1",
|
234 |
+
"vision_tower.vision_model.encoder.layers.19.mlp.fc2",
|
235 |
+
"vision_tower.vision_model.encoder.layers.20.self_attn.k_proj",
|
236 |
+
"vision_tower.vision_model.encoder.layers.20.self_attn.v_proj",
|
237 |
+
"vision_tower.vision_model.encoder.layers.20.self_attn.q_proj",
|
238 |
+
"vision_tower.vision_model.encoder.layers.20.self_attn.out_proj",
|
239 |
+
"vision_tower.vision_model.encoder.layers.20.mlp.fc1",
|
240 |
+
"vision_tower.vision_model.encoder.layers.20.mlp.fc2",
|
241 |
+
"vision_tower.vision_model.encoder.layers.21.self_attn.k_proj",
|
242 |
+
"vision_tower.vision_model.encoder.layers.21.self_attn.v_proj",
|
243 |
+
"vision_tower.vision_model.encoder.layers.21.self_attn.q_proj",
|
244 |
+
"vision_tower.vision_model.encoder.layers.21.self_attn.out_proj",
|
245 |
+
"vision_tower.vision_model.encoder.layers.21.mlp.fc1",
|
246 |
+
"vision_tower.vision_model.encoder.layers.21.mlp.fc2",
|
247 |
+
"vision_tower.vision_model.encoder.layers.22.self_attn.k_proj",
|
248 |
+
"vision_tower.vision_model.encoder.layers.22.self_attn.v_proj",
|
249 |
+
"vision_tower.vision_model.encoder.layers.22.self_attn.q_proj",
|
250 |
+
"vision_tower.vision_model.encoder.layers.22.self_attn.out_proj",
|
251 |
+
"vision_tower.vision_model.encoder.layers.22.mlp.fc1",
|
252 |
+
"vision_tower.vision_model.encoder.layers.22.mlp.fc2",
|
253 |
+
"vision_tower.vision_model.encoder.layers.23.self_attn.k_proj",
|
254 |
+
"vision_tower.vision_model.encoder.layers.23.self_attn.v_proj",
|
255 |
+
"vision_tower.vision_model.encoder.layers.23.self_attn.q_proj",
|
256 |
+
"vision_tower.vision_model.encoder.layers.23.self_attn.out_proj",
|
257 |
+
"vision_tower.vision_model.encoder.layers.23.mlp.fc1",
|
258 |
+
"vision_tower.vision_model.encoder.layers.23.mlp.fc2",
|
259 |
+
"vision_tower.vision_model.encoder.layers.24.self_attn.k_proj",
|
260 |
+
"vision_tower.vision_model.encoder.layers.24.self_attn.v_proj",
|
261 |
+
"vision_tower.vision_model.encoder.layers.24.self_attn.q_proj",
|
262 |
+
"vision_tower.vision_model.encoder.layers.24.self_attn.out_proj",
|
263 |
+
"vision_tower.vision_model.encoder.layers.24.mlp.fc1",
|
264 |
+
"vision_tower.vision_model.encoder.layers.24.mlp.fc2",
|
265 |
+
"vision_tower.vision_model.encoder.layers.25.self_attn.k_proj",
|
266 |
+
"vision_tower.vision_model.encoder.layers.25.self_attn.v_proj",
|
267 |
+
"vision_tower.vision_model.encoder.layers.25.self_attn.q_proj",
|
268 |
+
"vision_tower.vision_model.encoder.layers.25.self_attn.out_proj",
|
269 |
+
"vision_tower.vision_model.encoder.layers.25.mlp.fc1",
|
270 |
+
"vision_tower.vision_model.encoder.layers.25.mlp.fc2",
|
271 |
+
"vision_tower.vision_model.encoder.layers.26.self_attn.k_proj",
|
272 |
+
"vision_tower.vision_model.encoder.layers.26.self_attn.v_proj",
|
273 |
+
"vision_tower.vision_model.encoder.layers.26.self_attn.q_proj",
|
274 |
+
"vision_tower.vision_model.encoder.layers.26.self_attn.out_proj",
|
275 |
+
"vision_tower.vision_model.encoder.layers.26.mlp.fc1",
|
276 |
+
"vision_tower.vision_model.encoder.layers.26.mlp.fc2",
|
277 |
+
"language_model.lm_head"
|
278 |
+
],
|
279 |
+
"kv_cache_scheme": null,
|
280 |
+
"quant_method": "compressed-tensors",
|
281 |
+
"quantization_status": "compressed"
|
282 |
+
}
|
283 |
+
}
|
generation_config.json
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"eos_token_id": [
|
4 |
+
1,
|
5 |
+
106
|
6 |
+
],
|
7 |
+
"pad_token_id": 1,
|
8 |
+
"transformers_version": "4.51.3"
|
9 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f9c35def43fee0574ac1fab9886f3b4501df0eb83afc64d33de235fa721c5504
|
3 |
+
size 1379925224
|
special_tokens_map.json
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
{
|
4 |
+
"content": "<|audio|>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false
|
9 |
+
}
|
10 |
+
],
|
11 |
+
"boi_token": "<start_of_image>",
|
12 |
+
"bos_token": {
|
13 |
+
"content": "<bos>",
|
14 |
+
"lstrip": false,
|
15 |
+
"normalized": false,
|
16 |
+
"rstrip": false,
|
17 |
+
"single_word": false
|
18 |
+
},
|
19 |
+
"eoi_token": "<end_of_image>",
|
20 |
+
"eos_token": {
|
21 |
+
"content": "<eos>",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": false,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": false
|
26 |
+
},
|
27 |
+
"image_token": "<image_soft_token>",
|
28 |
+
"pad_token": {
|
29 |
+
"content": "<eos>",
|
30 |
+
"lstrip": false,
|
31 |
+
"normalized": false,
|
32 |
+
"rstrip": false,
|
33 |
+
"single_word": false
|
34 |
+
},
|
35 |
+
"unk_token": {
|
36 |
+
"content": "<unk>",
|
37 |
+
"lstrip": false,
|
38 |
+
"normalized": false,
|
39 |
+
"rstrip": false,
|
40 |
+
"single_word": false
|
41 |
+
}
|
42 |
+
}
|
text_model/README.md
ADDED
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
tags:
|
3 |
+
- vllm
|
4 |
+
- vision
|
5 |
+
- w8a8
|
6 |
+
license: gemma
|
7 |
+
base_model: google/gemma-3-27b-it
|
8 |
+
library_name: transformers
|
9 |
+
---
|
10 |
+
|
11 |
+
# gemma-3-27b-it-quantized.w8a8
|
12 |
+
|
13 |
+
## Model Overview
|
14 |
+
- **Model Architecture:** google/gemma-3-27b-it
|
15 |
+
- **Input:** Vision-Text
|
16 |
+
- **Output:** Text
|
17 |
+
- **Model Optimizations:**
|
18 |
+
- **Weight quantization:** INT8
|
19 |
+
- **Activation quantization:** INT8
|
20 |
+
- **Release Date:** 6/4/2025
|
21 |
+
- **Version:** 1.0
|
22 |
+
- **Model Developers:** RedHatAI
|
23 |
+
|
24 |
+
Quantized version of [google/gemma-3-27b-it](https://huggingface.co/google/gemma-3-27b-it).
|
25 |
+
|
26 |
+
### Model Optimizations
|
27 |
+
|
28 |
+
This model was obtained by quantizing the weights of [google/gemma-3-27b-it](https://huggingface.co/google/gemma-3-27b-it) to INT8 data type, ready for inference with vLLM >= 0.8.0.
|
29 |
+
|
30 |
+
## Deployment
|
31 |
+
|
32 |
+
### Use with vLLM
|
33 |
+
|
34 |
+
This model can be deployed efficiently using the [vLLM](https://docs.vllm.ai/en/latest/) backend, as shown in the example below.
|
35 |
+
|
36 |
+
```python
|
37 |
+
from vllm import LLM, SamplingParams
|
38 |
+
from vllm.assets.image import ImageAsset
|
39 |
+
from transformers import AutoProcessor
|
40 |
+
|
41 |
+
# Define model name once
|
42 |
+
model_name = "RedHatAI/gemma-3-27b-it-quantized.w8a8"
|
43 |
+
|
44 |
+
# Load image and processor
|
45 |
+
image = ImageAsset("cherry_blossom").pil_image.convert("RGB")
|
46 |
+
processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True)
|
47 |
+
|
48 |
+
# Build multimodal prompt
|
49 |
+
chat = [
|
50 |
+
{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is the content of this image?"}]},
|
51 |
+
{"role": "assistant", "content": []}
|
52 |
+
]
|
53 |
+
prompt = processor.apply_chat_template(chat, add_generation_prompt=True)
|
54 |
+
|
55 |
+
# Initialize model
|
56 |
+
llm = LLM(model=model_name, trust_remote_code=True)
|
57 |
+
|
58 |
+
# Run inference
|
59 |
+
inputs = {"prompt": prompt, "multi_modal_data": {"image": [image]}}
|
60 |
+
outputs = llm.generate(inputs, SamplingParams(temperature=0.2, max_tokens=64))
|
61 |
+
|
62 |
+
# Display result
|
63 |
+
print("RESPONSE:", outputs[0].outputs[0].text)
|
64 |
+
```
|
65 |
+
|
66 |
+
vLLM also supports OpenAI-compatible serving. See the [documentation](https://docs.vllm.ai/en/latest/) for more details.
|
67 |
+
|
68 |
+
## Creation
|
69 |
+
|
70 |
+
This model was created with [llm-compressor](https://github.com/vllm-project/llm-compressor) by running the code snippet below:
|
71 |
+
|
72 |
+
<details>
|
73 |
+
<summary>Model Creation Code</summary>
|
74 |
+
|
75 |
+
```python
|
76 |
+
import base64
|
77 |
+
from io import BytesIO
|
78 |
+
import torch
|
79 |
+
from datasets import load_dataset
|
80 |
+
from transformers import AutoProcessor, Gemma3ForConditionalGeneration
|
81 |
+
from llmcompressor.modifiers.quantization import GPTQModifier
|
82 |
+
from llmcompressor.transformers import oneshot
|
83 |
+
|
84 |
+
|
85 |
+
# Load model.
|
86 |
+
model_id = "google/gemma-3-27b-it"
|
87 |
+
model = Gemma3ForConditionalGeneration.from_pretrained(
|
88 |
+
model_id,
|
89 |
+
device_map="auto",
|
90 |
+
torch_dtype="auto",
|
91 |
+
)
|
92 |
+
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
93 |
+
|
94 |
+
# Oneshot arguments
|
95 |
+
DATASET_ID = "neuralmagic/calibration"
|
96 |
+
DATASET_SPLIT = {"LLM": "train[:1024]"}
|
97 |
+
NUM_CALIBRATION_SAMPLES = 1024
|
98 |
+
MAX_SEQUENCE_LENGTH = 2048
|
99 |
+
|
100 |
+
# Load dataset and preprocess.
|
101 |
+
ds = load_dataset(DATASET_ID, split=DATASET_SPLIT)
|
102 |
+
ds = ds.shuffle(seed=42)
|
103 |
+
|
104 |
+
dampening_frac=0.05
|
105 |
+
|
106 |
+
def data_collator(batch):
|
107 |
+
assert len(batch) == 1, "Only batch size of 1 is supported for calibration"
|
108 |
+
item = batch[0]
|
109 |
+
collated = {}
|
110 |
+
import torch
|
111 |
+
|
112 |
+
|
113 |
+
for key, value in item.items():
|
114 |
+
if isinstance(value, torch.Tensor):
|
115 |
+
collated[key] = value.unsqueeze(0)
|
116 |
+
elif isinstance(value, list) and isinstance(value[0][0], int):
|
117 |
+
# Handle tokenized inputs like input_ids, attention_mask
|
118 |
+
collated[key] = torch.tensor(value)
|
119 |
+
elif isinstance(value, list) and isinstance(value[0][0], float):
|
120 |
+
# Handle possible float sequences
|
121 |
+
collated[key] = torch.tensor(value)
|
122 |
+
elif isinstance(value, list) and isinstance(value[0][0], torch.Tensor):
|
123 |
+
# Handle batched image data (e.g., pixel_values as [C, H, W])
|
124 |
+
collated[key] = torch.stack(value) # -> [1, C, H, W]
|
125 |
+
elif isinstance(value, torch.Tensor):
|
126 |
+
collated[key] = value
|
127 |
+
else:
|
128 |
+
print(f"[WARN] Unrecognized type in collator for key={key}, type={type(value)}")
|
129 |
+
|
130 |
+
return collated
|
131 |
+
|
132 |
+
|
133 |
+
|
134 |
+
# Recipe
|
135 |
+
recipe = [
|
136 |
+
GPTQModifier(
|
137 |
+
targets="Linear",
|
138 |
+
ignore=["re:.*lm_head.*", "re:.*embed_tokens.*", "re:vision_tower.*", "re:multi_modal_projector.*"],
|
139 |
+
sequential_update=True,
|
140 |
+
sequential_targets=["Gemma3DecoderLayer"],
|
141 |
+
dampening_frac=dampening_frac,
|
142 |
+
)
|
143 |
+
]
|
144 |
+
|
145 |
+
SAVE_DIR=f"{model_id.split('/')[1]}-quantized.w8a8"
|
146 |
+
|
147 |
+
# Perform oneshot
|
148 |
+
oneshot(
|
149 |
+
model=model,
|
150 |
+
tokenizer=model_id,
|
151 |
+
dataset=ds,
|
152 |
+
recipe=recipe,
|
153 |
+
max_seq_length=MAX_SEQUENCE_LENGTH,
|
154 |
+
num_calibration_samples=NUM_CALIBRATION_SAMPLES,
|
155 |
+
trust_remote_code_model=True,
|
156 |
+
data_collator=data_collator,
|
157 |
+
output_dir=SAVE_DIR
|
158 |
+
)
|
159 |
+
```
|
160 |
+
</details>
|
161 |
+
|
162 |
+
## Evaluation
|
163 |
+
|
164 |
+
The model was evaluated using [lm_evaluation_harness](https://github.com/neuralmagic/lm-evaluation-harness) for OpenLLM v1 text benchmark. The evaluations were conducted using the following commands:
|
165 |
+
|
166 |
+
<details>
|
167 |
+
<summary>Evaluation Commands</summary>
|
168 |
+
|
169 |
+
### OpenLLM v1
|
170 |
+
```
|
171 |
+
lm_eval \
|
172 |
+
--model vllm \
|
173 |
+
--model_args pretrained="<model_name>",dtype=auto,add_bos_token=True,max_model_len=4096,tensor_parallel_size=<n>,gpu_memory_utilization=0.8,enable_chunked_prefill=True,trust_remote_code=True,enforce_eager=True \
|
174 |
+
--tasks openllm \
|
175 |
+
--batch_size auto
|
176 |
+
```
|
177 |
+
</details>
|
178 |
+
|
179 |
+
|
180 |
+
### Accuracy
|
181 |
+
|
182 |
+
<table>
|
183 |
+
<thead>
|
184 |
+
<tr>
|
185 |
+
<th>Category</th>
|
186 |
+
<th>Metric</th>
|
187 |
+
<th>google/gemma-3-27b-it</th>
|
188 |
+
<th>RedHatAI/gemma-3-27b-it-quantized.w8a8</th>
|
189 |
+
<th>Recovery (%)</th>
|
190 |
+
</tr>
|
191 |
+
</thead>
|
192 |
+
<tbody>
|
193 |
+
<tr>
|
194 |
+
<td rowspan="7"><b>OpenLLM V1</b></td>
|
195 |
+
<td>ARC Challenge</td>
|
196 |
+
<td>72.53%</td>
|
197 |
+
<td>70.82%</td>
|
198 |
+
<td>97.65%</td>
|
199 |
+
</tr>
|
200 |
+
<tr>
|
201 |
+
<td>GSM8K</td>
|
202 |
+
<td>92.12%</td>
|
203 |
+
<td>85.75%</td>
|
204 |
+
<td>93.09%</td>
|
205 |
+
</tr>
|
206 |
+
<tr>
|
207 |
+
<td>Hellaswag</td>
|
208 |
+
<td>85.78%</td>
|
209 |
+
<td>85.05%</td>
|
210 |
+
<td>99.15%</td>
|
211 |
+
</tr>
|
212 |
+
<tr>
|
213 |
+
<td>MMLU</td>
|
214 |
+
<td>77.53%</td>
|
215 |
+
<td>76.37%</td>
|
216 |
+
<td>98.50%</td>
|
217 |
+
</tr>
|
218 |
+
<tr>
|
219 |
+
<td>Truthfulqa (mc2)</td>
|
220 |
+
<td>62.20%</td>
|
221 |
+
<td>61.73%</td>
|
222 |
+
<td>99.24%</td>
|
223 |
+
</tr>
|
224 |
+
<tr>
|
225 |
+
<td>Winogrande</td>
|
226 |
+
<td>79.40%</td>
|
227 |
+
<td>79.72%</td>
|
228 |
+
<td>100.40%</td>
|
229 |
+
</tr>
|
230 |
+
<tr>
|
231 |
+
<td><b>Average Score</b></td>
|
232 |
+
<td><b>78.26%</b></td>
|
233 |
+
<td><b>76.57%</b></td>
|
234 |
+
<td><b>97.84%</b></td>
|
235 |
+
</tr>
|
236 |
+
<tr>
|
237 |
+
<td rowspan="3"><b>Vision Evals</b></td>
|
238 |
+
<td>MMMU (val)</td>
|
239 |
+
<td>50.89%</td>
|
240 |
+
<td>50.11%</td>
|
241 |
+
<td>98.47%</td>
|
242 |
+
</tr>
|
243 |
+
<tr>
|
244 |
+
<td>ChartQA</td>
|
245 |
+
<td>72.16%</td>
|
246 |
+
<td>71.72%</td>
|
247 |
+
<td>99.39%</td>
|
248 |
+
</tr>
|
249 |
+
<tr>
|
250 |
+
<td><b>Average Score</b></td>
|
251 |
+
<td><b>61.53%</b></td>
|
252 |
+
<td><b>60.92%</b></td>
|
253 |
+
<td><b>98.93%</b></td>
|
254 |
+
</tr>
|
255 |
+
</tbody>
|
256 |
+
</table>
|
text_model/chat_template.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"chat_template": "{{ bos_token }}\n{%- if messages[0]['role'] == 'system' -%}\n {%- if messages[0]['content'] is string -%}\n {%- set first_user_prefix = messages[0]['content'] + '\n\n' -%}\n {%- else -%}\n {%- set first_user_prefix = messages[0]['content'][0]['text'] + '\n\n' -%}\n {%- endif -%}\n {%- set loop_messages = messages[1:] -%}\n{%- else -%}\n {%- set first_user_prefix = \"\" -%}\n {%- set loop_messages = messages -%}\n{%- endif -%}\n{%- for message in loop_messages -%}\n {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}\n {{ raise_exception(\"Conversation roles must alternate user/assistant/user/assistant/...\") }}\n {%- endif -%}\n {%- if (message['role'] == 'assistant') -%}\n {%- set role = \"model\" -%}\n {%- else -%}\n {%- set role = message['role'] -%}\n {%- endif -%}\n {{ '<start_of_turn>' + role + '\n' + (first_user_prefix if loop.first else \"\") }}\n {%- if message['content'] is string -%}\n {{ message['content'] | trim }}\n {%- elif message['content'] is iterable -%}\n {%- for item in message['content'] -%}\n {%- if item['type'] == 'image' -%}\n {{ '<start_of_image>' }}\n {%- elif item['type'] == 'text' -%}\n {{ item['text'] | trim }}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {{ raise_exception(\"Invalid content type\") }}\n {%- endif -%}\n {{ '<end_of_turn>\n' }}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{'<start_of_turn>model\n'}}\n{%- endif -%}\n"
|
3 |
+
}
|
text_model/config.json
ADDED
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Gemma3ForConditionalGeneration"
|
4 |
+
],
|
5 |
+
"boi_token_index": 255999,
|
6 |
+
"eoi_token_index": 256000,
|
7 |
+
"eos_token_id": [
|
8 |
+
1,
|
9 |
+
106
|
10 |
+
],
|
11 |
+
"image_token_index": 262144,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"mm_tokens_per_image": 256,
|
14 |
+
"model_type": "gemma3",
|
15 |
+
"quantization_config": {
|
16 |
+
"config_groups": {
|
17 |
+
"group_0": {
|
18 |
+
"input_activations": {
|
19 |
+
"actorder": null,
|
20 |
+
"block_structure": null,
|
21 |
+
"dynamic": true,
|
22 |
+
"group_size": null,
|
23 |
+
"num_bits": 8,
|
24 |
+
"observer": null,
|
25 |
+
"observer_kwargs": {},
|
26 |
+
"strategy": "token",
|
27 |
+
"symmetric": true,
|
28 |
+
"type": "int"
|
29 |
+
},
|
30 |
+
"output_activations": null,
|
31 |
+
"targets": [
|
32 |
+
"Linear"
|
33 |
+
],
|
34 |
+
"weights": {
|
35 |
+
"actorder": null,
|
36 |
+
"block_structure": null,
|
37 |
+
"dynamic": false,
|
38 |
+
"group_size": null,
|
39 |
+
"num_bits": 8,
|
40 |
+
"observer": "mse",
|
41 |
+
"observer_kwargs": {},
|
42 |
+
"strategy": "channel",
|
43 |
+
"symmetric": true,
|
44 |
+
"type": "int"
|
45 |
+
}
|
46 |
+
}
|
47 |
+
},
|
48 |
+
"format": "int-quantized",
|
49 |
+
"global_compression_ratio": null,
|
50 |
+
"ignore": [
|
51 |
+
"vision_tower.vision_model.encoder.layers.0.self_attn.k_proj",
|
52 |
+
"vision_tower.vision_model.encoder.layers.0.self_attn.v_proj",
|
53 |
+
"vision_tower.vision_model.encoder.layers.0.self_attn.q_proj",
|
54 |
+
"vision_tower.vision_model.encoder.layers.0.self_attn.out_proj",
|
55 |
+
"vision_tower.vision_model.encoder.layers.0.mlp.fc1",
|
56 |
+
"vision_tower.vision_model.encoder.layers.0.mlp.fc2",
|
57 |
+
"vision_tower.vision_model.encoder.layers.1.self_attn.k_proj",
|
58 |
+
"vision_tower.vision_model.encoder.layers.1.self_attn.v_proj",
|
59 |
+
"vision_tower.vision_model.encoder.layers.1.self_attn.q_proj",
|
60 |
+
"vision_tower.vision_model.encoder.layers.1.self_attn.out_proj",
|
61 |
+
"vision_tower.vision_model.encoder.layers.1.mlp.fc1",
|
62 |
+
"vision_tower.vision_model.encoder.layers.1.mlp.fc2",
|
63 |
+
"vision_tower.vision_model.encoder.layers.2.self_attn.k_proj",
|
64 |
+
"vision_tower.vision_model.encoder.layers.2.self_attn.v_proj",
|
65 |
+
"vision_tower.vision_model.encoder.layers.2.self_attn.q_proj",
|
66 |
+
"vision_tower.vision_model.encoder.layers.2.self_attn.out_proj",
|
67 |
+
"vision_tower.vision_model.encoder.layers.2.mlp.fc1",
|
68 |
+
"vision_tower.vision_model.encoder.layers.2.mlp.fc2",
|
69 |
+
"vision_tower.vision_model.encoder.layers.3.self_attn.k_proj",
|
70 |
+
"vision_tower.vision_model.encoder.layers.3.self_attn.v_proj",
|
71 |
+
"vision_tower.vision_model.encoder.layers.3.self_attn.q_proj",
|
72 |
+
"vision_tower.vision_model.encoder.layers.3.self_attn.out_proj",
|
73 |
+
"vision_tower.vision_model.encoder.layers.3.mlp.fc1",
|
74 |
+
"vision_tower.vision_model.encoder.layers.3.mlp.fc2",
|
75 |
+
"vision_tower.vision_model.encoder.layers.4.self_attn.k_proj",
|
76 |
+
"vision_tower.vision_model.encoder.layers.4.self_attn.v_proj",
|
77 |
+
"vision_tower.vision_model.encoder.layers.4.self_attn.q_proj",
|
78 |
+
"vision_tower.vision_model.encoder.layers.4.self_attn.out_proj",
|
79 |
+
"vision_tower.vision_model.encoder.layers.4.mlp.fc1",
|
80 |
+
"vision_tower.vision_model.encoder.layers.4.mlp.fc2",
|
81 |
+
"vision_tower.vision_model.encoder.layers.5.self_attn.k_proj",
|
82 |
+
"vision_tower.vision_model.encoder.layers.5.self_attn.v_proj",
|
83 |
+
"vision_tower.vision_model.encoder.layers.5.self_attn.q_proj",
|
84 |
+
"vision_tower.vision_model.encoder.layers.5.self_attn.out_proj",
|
85 |
+
"vision_tower.vision_model.encoder.layers.5.mlp.fc1",
|
86 |
+
"vision_tower.vision_model.encoder.layers.5.mlp.fc2",
|
87 |
+
"vision_tower.vision_model.encoder.layers.6.self_attn.k_proj",
|
88 |
+
"vision_tower.vision_model.encoder.layers.6.self_attn.v_proj",
|
89 |
+
"vision_tower.vision_model.encoder.layers.6.self_attn.q_proj",
|
90 |
+
"vision_tower.vision_model.encoder.layers.6.self_attn.out_proj",
|
91 |
+
"vision_tower.vision_model.encoder.layers.6.mlp.fc1",
|
92 |
+
"vision_tower.vision_model.encoder.layers.6.mlp.fc2",
|
93 |
+
"vision_tower.vision_model.encoder.layers.7.self_attn.k_proj",
|
94 |
+
"vision_tower.vision_model.encoder.layers.7.self_attn.v_proj",
|
95 |
+
"vision_tower.vision_model.encoder.layers.7.self_attn.q_proj",
|
96 |
+
"vision_tower.vision_model.encoder.layers.7.self_attn.out_proj",
|
97 |
+
"vision_tower.vision_model.encoder.layers.7.mlp.fc1",
|
98 |
+
"vision_tower.vision_model.encoder.layers.7.mlp.fc2",
|
99 |
+
"vision_tower.vision_model.encoder.layers.8.self_attn.k_proj",
|
100 |
+
"vision_tower.vision_model.encoder.layers.8.self_attn.v_proj",
|
101 |
+
"vision_tower.vision_model.encoder.layers.8.self_attn.q_proj",
|
102 |
+
"vision_tower.vision_model.encoder.layers.8.self_attn.out_proj",
|
103 |
+
"vision_tower.vision_model.encoder.layers.8.mlp.fc1",
|
104 |
+
"vision_tower.vision_model.encoder.layers.8.mlp.fc2",
|
105 |
+
"vision_tower.vision_model.encoder.layers.9.self_attn.k_proj",
|
106 |
+
"vision_tower.vision_model.encoder.layers.9.self_attn.v_proj",
|
107 |
+
"vision_tower.vision_model.encoder.layers.9.self_attn.q_proj",
|
108 |
+
"vision_tower.vision_model.encoder.layers.9.self_attn.out_proj",
|
109 |
+
"vision_tower.vision_model.encoder.layers.9.mlp.fc1",
|
110 |
+
"vision_tower.vision_model.encoder.layers.9.mlp.fc2",
|
111 |
+
"vision_tower.vision_model.encoder.layers.10.self_attn.k_proj",
|
112 |
+
"vision_tower.vision_model.encoder.layers.10.self_attn.v_proj",
|
113 |
+
"vision_tower.vision_model.encoder.layers.10.self_attn.q_proj",
|
114 |
+
"vision_tower.vision_model.encoder.layers.10.self_attn.out_proj",
|
115 |
+
"vision_tower.vision_model.encoder.layers.10.mlp.fc1",
|
116 |
+
"vision_tower.vision_model.encoder.layers.10.mlp.fc2",
|
117 |
+
"vision_tower.vision_model.encoder.layers.11.self_attn.k_proj",
|
118 |
+
"vision_tower.vision_model.encoder.layers.11.self_attn.v_proj",
|
119 |
+
"vision_tower.vision_model.encoder.layers.11.self_attn.q_proj",
|
120 |
+
"vision_tower.vision_model.encoder.layers.11.self_attn.out_proj",
|
121 |
+
"vision_tower.vision_model.encoder.layers.11.mlp.fc1",
|
122 |
+
"vision_tower.vision_model.encoder.layers.11.mlp.fc2",
|
123 |
+
"vision_tower.vision_model.encoder.layers.12.self_attn.k_proj",
|
124 |
+
"vision_tower.vision_model.encoder.layers.12.self_attn.v_proj",
|
125 |
+
"vision_tower.vision_model.encoder.layers.12.self_attn.q_proj",
|
126 |
+
"vision_tower.vision_model.encoder.layers.12.self_attn.out_proj",
|
127 |
+
"vision_tower.vision_model.encoder.layers.12.mlp.fc1",
|
128 |
+
"vision_tower.vision_model.encoder.layers.12.mlp.fc2",
|
129 |
+
"vision_tower.vision_model.encoder.layers.13.self_attn.k_proj",
|
130 |
+
"vision_tower.vision_model.encoder.layers.13.self_attn.v_proj",
|
131 |
+
"vision_tower.vision_model.encoder.layers.13.self_attn.q_proj",
|
132 |
+
"vision_tower.vision_model.encoder.layers.13.self_attn.out_proj",
|
133 |
+
"vision_tower.vision_model.encoder.layers.13.mlp.fc1",
|
134 |
+
"vision_tower.vision_model.encoder.layers.13.mlp.fc2",
|
135 |
+
"vision_tower.vision_model.encoder.layers.14.self_attn.k_proj",
|
136 |
+
"vision_tower.vision_model.encoder.layers.14.self_attn.v_proj",
|
137 |
+
"vision_tower.vision_model.encoder.layers.14.self_attn.q_proj",
|
138 |
+
"vision_tower.vision_model.encoder.layers.14.self_attn.out_proj",
|
139 |
+
"vision_tower.vision_model.encoder.layers.14.mlp.fc1",
|
140 |
+
"vision_tower.vision_model.encoder.layers.14.mlp.fc2",
|
141 |
+
"vision_tower.vision_model.encoder.layers.15.self_attn.k_proj",
|
142 |
+
"vision_tower.vision_model.encoder.layers.15.self_attn.v_proj",
|
143 |
+
"vision_tower.vision_model.encoder.layers.15.self_attn.q_proj",
|
144 |
+
"vision_tower.vision_model.encoder.layers.15.self_attn.out_proj",
|
145 |
+
"vision_tower.vision_model.encoder.layers.15.mlp.fc1",
|
146 |
+
"vision_tower.vision_model.encoder.layers.15.mlp.fc2",
|
147 |
+
"vision_tower.vision_model.encoder.layers.16.self_attn.k_proj",
|
148 |
+
"vision_tower.vision_model.encoder.layers.16.self_attn.v_proj",
|
149 |
+
"vision_tower.vision_model.encoder.layers.16.self_attn.q_proj",
|
150 |
+
"vision_tower.vision_model.encoder.layers.16.self_attn.out_proj",
|
151 |
+
"vision_tower.vision_model.encoder.layers.16.mlp.fc1",
|
152 |
+
"vision_tower.vision_model.encoder.layers.16.mlp.fc2",
|
153 |
+
"vision_tower.vision_model.encoder.layers.17.self_attn.k_proj",
|
154 |
+
"vision_tower.vision_model.encoder.layers.17.self_attn.v_proj",
|
155 |
+
"vision_tower.vision_model.encoder.layers.17.self_attn.q_proj",
|
156 |
+
"vision_tower.vision_model.encoder.layers.17.self_attn.out_proj",
|
157 |
+
"vision_tower.vision_model.encoder.layers.17.mlp.fc1",
|
158 |
+
"vision_tower.vision_model.encoder.layers.17.mlp.fc2",
|
159 |
+
"vision_tower.vision_model.encoder.layers.18.self_attn.k_proj",
|
160 |
+
"vision_tower.vision_model.encoder.layers.18.self_attn.v_proj",
|
161 |
+
"vision_tower.vision_model.encoder.layers.18.self_attn.q_proj",
|
162 |
+
"vision_tower.vision_model.encoder.layers.18.self_attn.out_proj",
|
163 |
+
"vision_tower.vision_model.encoder.layers.18.mlp.fc1",
|
164 |
+
"vision_tower.vision_model.encoder.layers.18.mlp.fc2",
|
165 |
+
"vision_tower.vision_model.encoder.layers.19.self_attn.k_proj",
|
166 |
+
"vision_tower.vision_model.encoder.layers.19.self_attn.v_proj",
|
167 |
+
"vision_tower.vision_model.encoder.layers.19.self_attn.q_proj",
|
168 |
+
"vision_tower.vision_model.encoder.layers.19.self_attn.out_proj",
|
169 |
+
"vision_tower.vision_model.encoder.layers.19.mlp.fc1",
|
170 |
+
"vision_tower.vision_model.encoder.layers.19.mlp.fc2",
|
171 |
+
"vision_tower.vision_model.encoder.layers.20.self_attn.k_proj",
|
172 |
+
"vision_tower.vision_model.encoder.layers.20.self_attn.v_proj",
|
173 |
+
"vision_tower.vision_model.encoder.layers.20.self_attn.q_proj",
|
174 |
+
"vision_tower.vision_model.encoder.layers.20.self_attn.out_proj",
|
175 |
+
"vision_tower.vision_model.encoder.layers.20.mlp.fc1",
|
176 |
+
"vision_tower.vision_model.encoder.layers.20.mlp.fc2",
|
177 |
+
"vision_tower.vision_model.encoder.layers.21.self_attn.k_proj",
|
178 |
+
"vision_tower.vision_model.encoder.layers.21.self_attn.v_proj",
|
179 |
+
"vision_tower.vision_model.encoder.layers.21.self_attn.q_proj",
|
180 |
+
"vision_tower.vision_model.encoder.layers.21.self_attn.out_proj",
|
181 |
+
"vision_tower.vision_model.encoder.layers.21.mlp.fc1",
|
182 |
+
"vision_tower.vision_model.encoder.layers.21.mlp.fc2",
|
183 |
+
"vision_tower.vision_model.encoder.layers.22.self_attn.k_proj",
|
184 |
+
"vision_tower.vision_model.encoder.layers.22.self_attn.v_proj",
|
185 |
+
"vision_tower.vision_model.encoder.layers.22.self_attn.q_proj",
|
186 |
+
"vision_tower.vision_model.encoder.layers.22.self_attn.out_proj",
|
187 |
+
"vision_tower.vision_model.encoder.layers.22.mlp.fc1",
|
188 |
+
"vision_tower.vision_model.encoder.layers.22.mlp.fc2",
|
189 |
+
"vision_tower.vision_model.encoder.layers.23.self_attn.k_proj",
|
190 |
+
"vision_tower.vision_model.encoder.layers.23.self_attn.v_proj",
|
191 |
+
"vision_tower.vision_model.encoder.layers.23.self_attn.q_proj",
|
192 |
+
"vision_tower.vision_model.encoder.layers.23.self_attn.out_proj",
|
193 |
+
"vision_tower.vision_model.encoder.layers.23.mlp.fc1",
|
194 |
+
"vision_tower.vision_model.encoder.layers.23.mlp.fc2",
|
195 |
+
"vision_tower.vision_model.encoder.layers.24.self_attn.k_proj",
|
196 |
+
"vision_tower.vision_model.encoder.layers.24.self_attn.v_proj",
|
197 |
+
"vision_tower.vision_model.encoder.layers.24.self_attn.q_proj",
|
198 |
+
"vision_tower.vision_model.encoder.layers.24.self_attn.out_proj",
|
199 |
+
"vision_tower.vision_model.encoder.layers.24.mlp.fc1",
|
200 |
+
"vision_tower.vision_model.encoder.layers.24.mlp.fc2",
|
201 |
+
"vision_tower.vision_model.encoder.layers.25.self_attn.k_proj",
|
202 |
+
"vision_tower.vision_model.encoder.layers.25.self_attn.v_proj",
|
203 |
+
"vision_tower.vision_model.encoder.layers.25.self_attn.q_proj",
|
204 |
+
"vision_tower.vision_model.encoder.layers.25.self_attn.out_proj",
|
205 |
+
"vision_tower.vision_model.encoder.layers.25.mlp.fc1",
|
206 |
+
"vision_tower.vision_model.encoder.layers.25.mlp.fc2",
|
207 |
+
"vision_tower.vision_model.encoder.layers.26.self_attn.k_proj",
|
208 |
+
"vision_tower.vision_model.encoder.layers.26.self_attn.v_proj",
|
209 |
+
"vision_tower.vision_model.encoder.layers.26.self_attn.q_proj",
|
210 |
+
"vision_tower.vision_model.encoder.layers.26.self_attn.out_proj",
|
211 |
+
"vision_tower.vision_model.encoder.layers.26.mlp.fc1",
|
212 |
+
"vision_tower.vision_model.encoder.layers.26.mlp.fc2",
|
213 |
+
"language_model.lm_head"
|
214 |
+
],
|
215 |
+
"kv_cache_scheme": null,
|
216 |
+
"quant_method": "compressed-tensors",
|
217 |
+
"quantization_status": "compressed"
|
218 |
+
},
|
219 |
+
"text_config": {
|
220 |
+
"attention_bias": false,
|
221 |
+
"attention_dropout": 0.0,
|
222 |
+
"attn_logit_softcapping": null,
|
223 |
+
"cache_implementation": "hybrid",
|
224 |
+
"final_logit_softcapping": null,
|
225 |
+
"head_dim": 128,
|
226 |
+
"hidden_activation": "gelu_pytorch_tanh",
|
227 |
+
"hidden_size": 5376,
|
228 |
+
"initializer_range": 0.02,
|
229 |
+
"intermediate_size": 21504,
|
230 |
+
"max_position_embeddings": 131072,
|
231 |
+
"model_type": "gemma3_text",
|
232 |
+
"num_attention_heads": 32,
|
233 |
+
"num_hidden_layers": 62,
|
234 |
+
"num_key_value_heads": 16,
|
235 |
+
"query_pre_attn_scalar": 168,
|
236 |
+
"rms_norm_eps": 1e-06,
|
237 |
+
"rope_local_base_freq": 10000.0,
|
238 |
+
"rope_scaling": {
|
239 |
+
"factor": 8.0,
|
240 |
+
"rope_type": "linear"
|
241 |
+
},
|
242 |
+
"rope_theta": 1000000.0,
|
243 |
+
"sliding_window": 1024,
|
244 |
+
"sliding_window_pattern": 6,
|
245 |
+
"use_cache": true,
|
246 |
+
"vocab_size": 262208
|
247 |
+
},
|
248 |
+
"torch_dtype": "bfloat16",
|
249 |
+
"transformers_version": "4.51.3",
|
250 |
+
"vision_config": {
|
251 |
+
"attention_dropout": 0.0,
|
252 |
+
"hidden_act": "gelu_pytorch_tanh",
|
253 |
+
"hidden_size": 1152,
|
254 |
+
"image_size": 896,
|
255 |
+
"intermediate_size": 4304,
|
256 |
+
"layer_norm_eps": 1e-06,
|
257 |
+
"model_type": "siglip_vision_model",
|
258 |
+
"num_attention_heads": 16,
|
259 |
+
"num_channels": 3,
|
260 |
+
"num_hidden_layers": 27,
|
261 |
+
"patch_size": 14,
|
262 |
+
"vision_use_head": false
|
263 |
+
}
|
264 |
+
}
|
text_model/generation_config.json
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 2,
|
3 |
+
"cache_implementation": "hybrid",
|
4 |
+
"do_sample": true,
|
5 |
+
"eos_token_id": [
|
6 |
+
1,
|
7 |
+
106
|
8 |
+
],
|
9 |
+
"pad_token_id": 0,
|
10 |
+
"top_k": 64,
|
11 |
+
"top_p": 0.95,
|
12 |
+
"transformers_version": "4.51.3"
|
13 |
+
}
|
text_model/model-00001-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6f604b90b7a8259b5edac4c3248772e26349f06ad4ceb10b512f5b792d0c6c17
|
3 |
+
size 4970671664
|
text_model/model-00002-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:898531a9f713b83366d380188366bd844ffcf9c1c7fc42463e1543e5a2eb6f6c
|
3 |
+
size 4956561192
|
text_model/model-00003-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:43e888205b6f1a996ce78e5fdf95ae75e1840996d6c5ace486e61be368dc8993
|
3 |
+
size 4956561336
|
text_model/model-00004-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:64656d2f094399c804d9a2d4cfa0aedca46cc608743a6f33b65a289d7942abb8
|
3 |
+
size 4956561336
|
text_model/model-00005-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a0a50cfb8f141b9fa492750eeee0b4f2ea39ba3fb556941d73f6ba741b79537d
|
3 |
+
size 4956561336
|
text_model/model-00006-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6062e9120283d4c8b11f431b3cfdcb4ba82772a890769c62bcf218bfb2e4cc34
|
3 |
+
size 4477436176
|
text_model/model-00007-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e3af9ced7321e166924a85ce941256dc26465c6279094f46a85b9bd9f7032c33
|
3 |
+
size 2819260560
|
text_model/model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
text_model/preprocessor_config.json
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"do_convert_rgb": true,
|
3 |
+
"do_normalize": true,
|
4 |
+
"do_pan_and_scan": null,
|
5 |
+
"do_rescale": true,
|
6 |
+
"do_resize": true,
|
7 |
+
"image_mean": [
|
8 |
+
0.5,
|
9 |
+
0.5,
|
10 |
+
0.5
|
11 |
+
],
|
12 |
+
"image_processor_type": "Gemma3ImageProcessor",
|
13 |
+
"image_seq_length": 256,
|
14 |
+
"image_std": [
|
15 |
+
0.5,
|
16 |
+
0.5,
|
17 |
+
0.5
|
18 |
+
],
|
19 |
+
"pan_and_scan_max_num_crops": null,
|
20 |
+
"pan_and_scan_min_crop_size": null,
|
21 |
+
"pan_and_scan_min_ratio_to_activate": null,
|
22 |
+
"processor_class": "Gemma3Processor",
|
23 |
+
"resample": 2,
|
24 |
+
"rescale_factor": 0.00392156862745098,
|
25 |
+
"size": {
|
26 |
+
"height": 896,
|
27 |
+
"width": 896
|
28 |
+
}
|
29 |
+
}
|
text_model/processor_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"image_seq_length": 256,
|
3 |
+
"processor_class": "Gemma3Processor"
|
4 |
+
}
|
text_model/recipe.yaml
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
quant_stage:
|
2 |
+
quant_modifiers:
|
3 |
+
GPTQModifier:
|
4 |
+
dampening_frac: 0.05
|
5 |
+
ignore: ['re:.*lm_head.*', 're:.*embed_tokens.*', 're:vision_tower.*', 're:multi_modal_projector.*']
|
6 |
+
sequential_update: true
|
7 |
+
config_groups:
|
8 |
+
group_0:
|
9 |
+
targets: [Linear]
|
10 |
+
weights: {num_bits: 8, type: int, symmetric: true, strategy: channel, observer: mse}
|
11 |
+
input_activations: {num_bits: 8, type: int, symmetric: true, strategy: token, dynamic: true,
|
12 |
+
observer: memoryless}
|
text_model/special_tokens_map.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"boi_token": "<start_of_image>",
|
3 |
+
"bos_token": {
|
4 |
+
"content": "<bos>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false
|
9 |
+
},
|
10 |
+
"eoi_token": "<end_of_image>",
|
11 |
+
"eos_token": {
|
12 |
+
"content": "<eos>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false
|
17 |
+
},
|
18 |
+
"image_token": "<image_soft_token>",
|
19 |
+
"pad_token": {
|
20 |
+
"content": "<pad>",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false
|
25 |
+
},
|
26 |
+
"unk_token": {
|
27 |
+
"content": "<unk>",
|
28 |
+
"lstrip": false,
|
29 |
+
"normalized": false,
|
30 |
+
"rstrip": false,
|
31 |
+
"single_word": false
|
32 |
+
}
|
33 |
+
}
|
text_model/tokenizer.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4667f2089529e8e7657cfb6d1c19910ae71ff5f28aa7ab2ff2763330affad795
|
3 |
+
size 33384568
|
text_model/tokenizer_config.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4667f2089529e8e7657cfb6d1c19910ae71ff5f28aa7ab2ff2763330affad795
|
3 |
+
size 33384568
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1299c11d7cf632ef3b4e11937501358ada021bbdf7c47638d13c0ee982f2e79c
|
3 |
+
size 4689074
|
tokenizer_config.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
ultravox_config.py
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
from enum import Enum
|
3 |
+
from typing import Any, Dict, List, Optional
|
4 |
+
|
5 |
+
import transformers
|
6 |
+
|
7 |
+
|
8 |
+
@dataclasses.dataclass
|
9 |
+
class LoraConfigSimplified:
|
10 |
+
"""
|
11 |
+
Low Rank Approximation (LoRA) configuration.
|
12 |
+
|
13 |
+
Used for language and audio models separately.
|
14 |
+
"""
|
15 |
+
|
16 |
+
# The rank of the approximation
|
17 |
+
r: int = 0
|
18 |
+
lora_alpha: float = 8
|
19 |
+
target_modules: Optional[List[str]] = dataclasses.field(
|
20 |
+
default_factory=lambda: ["k_proj", "q_proj", "linear_k", "linear_q"]
|
21 |
+
)
|
22 |
+
# A list of module names regex patterns to unfreeze. Only used if r == 0.
|
23 |
+
unfreeze_layers: Optional[List[str]] = None
|
24 |
+
|
25 |
+
|
26 |
+
class LossMaskType(str, Enum):
|
27 |
+
"""Type of loss mask to use."""
|
28 |
+
|
29 |
+
LAST_ASSISTANT = "last_assistant"
|
30 |
+
"""This applies the loss mask up until the last assistant token"""
|
31 |
+
ALL = "all" # This does not work with KL loss
|
32 |
+
"""No loss mask, all inputs are used for loss"""
|
33 |
+
AFTER_AUDIO = "after_audio"
|
34 |
+
"""Applies the loss mask up until the audio token"""
|
35 |
+
|
36 |
+
|
37 |
+
class LossFunction(str, Enum):
|
38 |
+
CrossEntropy = "ce"
|
39 |
+
KL_Divergence = "kl"
|
40 |
+
|
41 |
+
|
42 |
+
@dataclasses.dataclass
|
43 |
+
class LossConfig:
|
44 |
+
loss_function: LossFunction = LossFunction.CrossEntropy
|
45 |
+
kl_temperature: float = 2.0
|
46 |
+
# Number of tokens to ignore from the beginning of the sequence. Only used in LSM
|
47 |
+
initial_tokens_to_ignore: int = 0
|
48 |
+
# Weight for the EOT token KL loss
|
49 |
+
eot_loss_weight: float = 1.0
|
50 |
+
|
51 |
+
@property
|
52 |
+
def requires_alt_fields(self):
|
53 |
+
return self.loss_function == LossFunction.KL_Divergence
|
54 |
+
|
55 |
+
|
56 |
+
class UltravoxConfig(transformers.PretrainedConfig):
|
57 |
+
r"""
|
58 |
+
This is the configuration class to store the configuration of a [`UltravoxForConditionalGeneration`]. It is used to instantiate an
|
59 |
+
Ultravox model according to the specified arguments, defining the model architecture.
|
60 |
+
|
61 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
62 |
+
documentation from [`PretrainedConfig`] for more information.
|
63 |
+
|
64 |
+
Args:
|
65 |
+
audio_config (`WhisperConfig`, *optional*):
|
66 |
+
Custom audio config or dict
|
67 |
+
text_config (`Union[AutoConfig, dict]`, *optional*):
|
68 |
+
The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`.
|
69 |
+
ignore_index (`int`, *optional*, defaults to -100):
|
70 |
+
The ignore index for the loss function.
|
71 |
+
audio_token_index (`int`, *optional*, defaults to 32000):
|
72 |
+
The audio token index to encode the audio prompt.
|
73 |
+
stack_factor (`int`, *optional*, defaults to 8):
|
74 |
+
Audio downsampling factor for the multimodal projector.
|
75 |
+
norm_init (`float`, *optional*, defaults to 0.4):
|
76 |
+
The initialization value for the layer normalization.
|
77 |
+
projector_act (`str`, *optional*, defaults to `"swiglu"`):
|
78 |
+
The activation function used by the multimodal projector.
|
79 |
+
text_model_lora_config (`LoraConfigSimplified`, *optional*):
|
80 |
+
The LoRA configuration for finetuning the text model.
|
81 |
+
audio_model_lora_config (`LoraConfigSimplified`, *optional*):
|
82 |
+
The LoRA configuration for finetuning the audio model.
|
83 |
+
audio_latency_block_size (`int`, *optional*, defaults to `None`):
|
84 |
+
The latency block size for simulating audio streaming.
|
85 |
+
|
86 |
+
|
87 |
+
Example:
|
88 |
+
|
89 |
+
```python
|
90 |
+
>>> from transformers import UltravoxModel, WhisperConfig, UltravoxConfig, LlamaConfig
|
91 |
+
|
92 |
+
>>> # Initializing an audio encoder config
|
93 |
+
>>> audio_config = WhisperConfig()
|
94 |
+
|
95 |
+
>>> # Initializing a Llama config
|
96 |
+
>>> text_config = LlamaConfig()
|
97 |
+
|
98 |
+
>>> # Initializing a default configuration
|
99 |
+
>>> configuration = UltravoxConfig(audio_config, text_config)
|
100 |
+
|
101 |
+
>>> # Initializing a completely untrained model from the configuration
|
102 |
+
>>> model = UltravoxModel(configuration)
|
103 |
+
|
104 |
+
>>> # Accessing the model configuration
|
105 |
+
>>> configuration = model.config
|
106 |
+
|
107 |
+
>>> # Initialize a model from pretrained checkpoints and random projector weights
|
108 |
+
>>> config = UltravoxConfig(audio_model_id="openai/whisper-tiny", text_model_id="meta-llama/Llama-2-7b-chat-hf")
|
109 |
+
```"""
|
110 |
+
|
111 |
+
model_type = "ultravox"
|
112 |
+
is_composition = False
|
113 |
+
|
114 |
+
def __init__(
|
115 |
+
self,
|
116 |
+
audio_config: dict[str, Any] | transformers.PretrainedConfig | None = None,
|
117 |
+
text_config: dict[str, Any] | transformers.PretrainedConfig | None = None,
|
118 |
+
audio_model_id: str | None = None,
|
119 |
+
text_model_id: str | None = None,
|
120 |
+
ignore_index: int = -100,
|
121 |
+
audio_token_index: int | None = None,
|
122 |
+
hidden_size: int = 4096,
|
123 |
+
stack_factor: int = 8,
|
124 |
+
norm_init: float = 0.4,
|
125 |
+
projector_act: str = "swiglu",
|
126 |
+
projector_ln_mid: bool = False, # defaults to False for compatibility with v0.4.1 and below
|
127 |
+
text_model_lora_config: LoraConfigSimplified | None = None,
|
128 |
+
audio_model_lora_config: LoraConfigSimplified | None = None,
|
129 |
+
audio_latency_block_size: int | None = None,
|
130 |
+
**kwargs,
|
131 |
+
):
|
132 |
+
self.ignore_index = ignore_index
|
133 |
+
|
134 |
+
self.audio_model_id = audio_model_id
|
135 |
+
self.text_model_id = text_model_id
|
136 |
+
|
137 |
+
self.audio_token_index = audio_token_index
|
138 |
+
|
139 |
+
self.hidden_size = hidden_size
|
140 |
+
self.stack_factor = stack_factor
|
141 |
+
self.norm_init = norm_init
|
142 |
+
self.projector_act = projector_act
|
143 |
+
self.projector_ln_mid = projector_ln_mid
|
144 |
+
if text_model_id is not None:
|
145 |
+
text_config = transformers.AutoConfig.from_pretrained(text_model_id)
|
146 |
+
else:
|
147 |
+
text_config = text_config or {}
|
148 |
+
if isinstance(text_config, dict):
|
149 |
+
text_config = transformers.CONFIG_MAPPING[
|
150 |
+
text_config.get("model_type", "llama")
|
151 |
+
](**text_config)
|
152 |
+
|
153 |
+
if audio_model_id is not None:
|
154 |
+
audio_config = transformers.AutoConfig.from_pretrained(audio_model_id)
|
155 |
+
else:
|
156 |
+
audio_config = audio_config or {}
|
157 |
+
if isinstance(audio_config, dict):
|
158 |
+
audio_config = transformers.CONFIG_MAPPING[
|
159 |
+
audio_config.get("model_type", "whisper")
|
160 |
+
](**audio_config)
|
161 |
+
|
162 |
+
self.text_config = text_config
|
163 |
+
self.audio_config = audio_config
|
164 |
+
|
165 |
+
self.text_model_lora_config = (
|
166 |
+
text_model_lora_config
|
167 |
+
if isinstance(text_model_lora_config, dict)
|
168 |
+
else dataclasses.asdict(text_model_lora_config or LoraConfigSimplified())
|
169 |
+
)
|
170 |
+
self.audio_model_lora_config = (
|
171 |
+
audio_model_lora_config
|
172 |
+
if isinstance(audio_model_lora_config, dict)
|
173 |
+
else dataclasses.asdict(audio_model_lora_config or LoraConfigSimplified())
|
174 |
+
)
|
175 |
+
self.audio_latency_block_size = audio_latency_block_size
|
176 |
+
|
177 |
+
if hasattr(text_config, "text_config"):
|
178 |
+
text_config.vocab_size = text_config.text_config.vocab_size
|
179 |
+
text_config.hidden_size = text_config.text_config.hidden_size
|
180 |
+
|
181 |
+
self.vocab_size = text_config.vocab_size
|
182 |
+
|
183 |
+
self.initializer_range = text_config.initializer_range
|
184 |
+
|
185 |
+
super().__init__(**kwargs)
|
186 |
+
|
187 |
+
def to_diff_dict(self) -> Dict[str, Any]:
|
188 |
+
diff_dict = super().to_diff_dict()
|
189 |
+
|
190 |
+
# remove text_config and audio_config if text_model_id and audio_model_id are present
|
191 |
+
if self.text_model_id is not None:
|
192 |
+
diff_dict.pop("text_config", None)
|
193 |
+
elif "text_config" in diff_dict:
|
194 |
+
diff_dict["text_config"].pop("_attn_implementation_autoset", None)
|
195 |
+
|
196 |
+
if self.audio_model_id is not None:
|
197 |
+
diff_dict.pop("audio_config", None)
|
198 |
+
elif "audio_config" in diff_dict:
|
199 |
+
diff_dict["audio_config"].pop("_attn_implementation_autoset", None)
|
200 |
+
|
201 |
+
return diff_dict
|
ultravox_model.py
ADDED
@@ -0,0 +1,976 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import re
|
3 |
+
from typing import Any, Dict, Generator, Optional, Set, Tuple, TypeVar, Union
|
4 |
+
|
5 |
+
import accelerate
|
6 |
+
import peft
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
import torch.nn.functional as F
|
10 |
+
import transformers
|
11 |
+
import transformers.activations
|
12 |
+
import transformers.modeling_outputs
|
13 |
+
import transformers.models
|
14 |
+
from transformers.generation.utils import GenerationMixin
|
15 |
+
from transformers.models.whisper import modeling_whisper as whisper
|
16 |
+
|
17 |
+
# We must use relative import in this directory to allow uploading to HF Hub
|
18 |
+
# Even "from . import X" pattern doesn't work (undocumented and unclear why)
|
19 |
+
from .ultravox_config import LossConfig
|
20 |
+
from .ultravox_config import LossFunction
|
21 |
+
from .ultravox_config import UltravoxConfig
|
22 |
+
|
23 |
+
FROM_PRETRAINED_KWARGS = {}
|
24 |
+
SHARED_PRETRAINED_KWARGS = [
|
25 |
+
"tp_plan",
|
26 |
+
"device_map",
|
27 |
+
"torch_dtype",
|
28 |
+
"attn_implementation",
|
29 |
+
"use_flash_attention_2",
|
30 |
+
]
|
31 |
+
|
32 |
+
class UltravoxModel(transformers.LlamaPreTrainedModel, GenerationMixin):
|
33 |
+
"""
|
34 |
+
The Ultravox model which consists of an audio encoder and a language model.
|
35 |
+
|
36 |
+
Audio input is processed by the audio encoder, then every `stack_factor` frames are stacked together and
|
37 |
+
projected to the language model's embedding space using a few linear layers.
|
38 |
+
The text is embedded by the language model as usual and then the audio and text embeddings are merged together.
|
39 |
+
|
40 |
+
A special token `<|audio|>` is used to indicate the start of the audio embeddings in the merged embeddings.
|
41 |
+
|
42 |
+
Parameters:
|
43 |
+
config: Model configuration class with all the parameters of the model.
|
44 |
+
"""
|
45 |
+
|
46 |
+
config_class = UltravoxConfig
|
47 |
+
config: UltravoxConfig # for type hinting
|
48 |
+
# Usually we load encoder and LLM weights from a pretrained model separately, so they are allowed to be missing
|
49 |
+
_keys_to_ignore_on_load_missing = ["audio_tower.*", "language_model.*"]
|
50 |
+
# Since we have kwargs in forward, we need to set this to False, otherwise grad_accum_steps will cause incorrect train loss to be reported
|
51 |
+
# see https://github.com/huggingface/transformers/issues/35856 and https://github.com/huggingface/trl/pull/2615/files
|
52 |
+
accepts_loss_kwargs = False
|
53 |
+
|
54 |
+
def __init__(self, config: UltravoxConfig):
|
55 |
+
super().__init__(config)
|
56 |
+
self._register_load_state_dict_pre_hook(self._pre_load_state_dict_hook)
|
57 |
+
|
58 |
+
self.keep_params: Set[str] = set()
|
59 |
+
self.vocab_size = config.vocab_size
|
60 |
+
|
61 |
+
self.audio_tower = self._create_audio_tower(config)
|
62 |
+
self.audio_tower_context_length: Optional[int] = None
|
63 |
+
self.audio_tower_context_length = self.audio_tower.max_context_length
|
64 |
+
|
65 |
+
self.multi_modal_projector = self._create_multi_modal_projector(config)
|
66 |
+
self.language_model = self._create_language_model(config)
|
67 |
+
|
68 |
+
if self.language_model._tied_weights_keys is not None:
|
69 |
+
self._tied_weights_keys = [
|
70 |
+
f"language_model.{k}" for k in self.language_model._tied_weights_keys
|
71 |
+
]
|
72 |
+
|
73 |
+
# Determine no_split_modules dynamically to use with FSDP auto_wrap policy.
|
74 |
+
# FSDP throws an error if some of the layer types are not found in the model.
|
75 |
+
# This would be something like ["LlamaDecoderLayer"] as we don't split audio encoder layers.
|
76 |
+
# Filter out modules that don't exist in this model to avoid FSDP errors.
|
77 |
+
language_model_modules = self.language_model._no_split_modules or []
|
78 |
+
existing_modules = []
|
79 |
+
for module_name in language_model_modules:
|
80 |
+
# Check if any module in the model has this class name
|
81 |
+
module_exists = any(
|
82 |
+
module.__class__.__name__ == module_name
|
83 |
+
for module in self.modules()
|
84 |
+
)
|
85 |
+
if module_exists:
|
86 |
+
existing_modules.append(module_name)
|
87 |
+
self._no_split_modules = existing_modules
|
88 |
+
|
89 |
+
self.loss_config = LossConfig()
|
90 |
+
self.post_init()
|
91 |
+
|
92 |
+
def _init_weights(self, module):
|
93 |
+
if module is self:
|
94 |
+
if self.config.text_model_id is not None:
|
95 |
+
self.language_model = self._create_language_model(self.config)
|
96 |
+
if self.config.audio_model_id is not None:
|
97 |
+
self.audio_tower = self._create_audio_tower(self.config)
|
98 |
+
elif module in self.language_model.modules():
|
99 |
+
pass
|
100 |
+
elif module in self.audio_tower.modules():
|
101 |
+
pass
|
102 |
+
else:
|
103 |
+
super()._init_weights(module)
|
104 |
+
|
105 |
+
@classmethod
|
106 |
+
def from_pretrained(cls, *args, **kwargs):
|
107 |
+
global FROM_PRETRAINED_KWARGS
|
108 |
+
FROM_PRETRAINED_KWARGS = {
|
109 |
+
k: v for k, v in kwargs.items() if k in SHARED_PRETRAINED_KWARGS
|
110 |
+
}
|
111 |
+
model = super().from_pretrained(*args, **kwargs)
|
112 |
+
FROM_PRETRAINED_KWARGS = {}
|
113 |
+
return model
|
114 |
+
|
115 |
+
def get_input_embeddings(self):
|
116 |
+
return self.language_model.get_input_embeddings()
|
117 |
+
|
118 |
+
def set_input_embeddings(self, value):
|
119 |
+
self.language_model.set_input_embeddings(value)
|
120 |
+
|
121 |
+
def get_output_embeddings(self):
|
122 |
+
return self.language_model.get_output_embeddings()
|
123 |
+
|
124 |
+
def set_output_embeddings(self, new_embeddings):
|
125 |
+
self.language_model.set_output_embeddings(new_embeddings)
|
126 |
+
|
127 |
+
def set_decoder(self, decoder):
|
128 |
+
self.language_model.set_decoder(decoder)
|
129 |
+
|
130 |
+
def get_decoder(self):
|
131 |
+
return self.language_model.get_decoder()
|
132 |
+
|
133 |
+
def tie_weights(self):
|
134 |
+
return self.language_model.tie_weights()
|
135 |
+
|
136 |
+
def set_loss_config(self, loss_config: LossConfig):
|
137 |
+
self.loss_config = loss_config
|
138 |
+
|
139 |
+
def _setup_cache(
|
140 |
+
self, cache_cls, max_batch_size: int, max_cache_len: Optional[int] = None
|
141 |
+
):
|
142 |
+
self.language_model._setup_cache(cache_cls, max_batch_size, max_cache_len)
|
143 |
+
|
144 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
145 |
+
return self.language_model._reorder_cache(past_key_values, beam_idx)
|
146 |
+
|
147 |
+
def resize_token_embeddings(
|
148 |
+
self,
|
149 |
+
new_num_tokens: Optional[int] = None,
|
150 |
+
pad_to_multiple_of: Optional[int] = None,
|
151 |
+
) -> nn.Embedding:
|
152 |
+
model_embeds = self.language_model.resize_token_embeddings(
|
153 |
+
new_num_tokens, pad_to_multiple_of
|
154 |
+
)
|
155 |
+
# update vocab size
|
156 |
+
self.config.text_config.vocab_size = model_embeds.num_embeddings
|
157 |
+
self.config.vocab_size = model_embeds.num_embeddings
|
158 |
+
self.vocab_size = model_embeds.num_embeddings
|
159 |
+
return model_embeds
|
160 |
+
|
161 |
+
def _get_prediction_mask(
|
162 |
+
self, labels: Optional[torch.Tensor]
|
163 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
164 |
+
"""Get boolean masks for positions where we want to compute KL divergence.
|
165 |
+
|
166 |
+
For each label position, we want the position before it since that's where
|
167 |
+
the model makes the prediction for that label.
|
168 |
+
|
169 |
+
Additionally, we want to identify the position right before the EOT token
|
170 |
+
(the last token with label != -100).
|
171 |
+
|
172 |
+
Args:
|
173 |
+
labels: Tensor of shape (B, T) where B is batch size and T is sequence length,
|
174 |
+
with -100 for masked positions and token ids for label positions
|
175 |
+
|
176 |
+
Returns:
|
177 |
+
Tuple containing:
|
178 |
+
- pred_mask: Boolean tensor of shape (B, T) that's True for positions where we want to compute KL divergence
|
179 |
+
- eot_mask: Boolean tensor of shape (B, T) that's True only for the last prediction position in each sequence
|
180 |
+
"""
|
181 |
+
if labels is None:
|
182 |
+
raise ValueError("labels must be provided")
|
183 |
+
|
184 |
+
# Shift the label mask right by 1 along the sequence dimension
|
185 |
+
# This gives us positions where we make predictions for the next token
|
186 |
+
label_mask = labels != -100
|
187 |
+
pred_mask = torch.zeros_like(label_mask)
|
188 |
+
pred_mask[:, :-1] = label_mask[
|
189 |
+
:, 1:
|
190 |
+
] # shift right by 1 along sequence dimension
|
191 |
+
|
192 |
+
# Create EOT mask - identify only the last prediction position in each sequence
|
193 |
+
eot_mask = torch.zeros_like(pred_mask)
|
194 |
+
batch_size = labels.shape[0]
|
195 |
+
|
196 |
+
for i in range(batch_size):
|
197 |
+
# Find positions where we make predictions
|
198 |
+
pred_positions = torch.where(pred_mask[i])[0]
|
199 |
+
if len(pred_positions) > 0:
|
200 |
+
# Only mark the last prediction position
|
201 |
+
eot_mask[i, pred_positions[-1]] = True
|
202 |
+
|
203 |
+
return pred_mask, eot_mask
|
204 |
+
|
205 |
+
def _compute_kl_loss(
|
206 |
+
self,
|
207 |
+
lm_output: transformers.modeling_outputs.CausalLMOutputWithPast,
|
208 |
+
labels: Optional[torch.Tensor] = None,
|
209 |
+
past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
|
210 |
+
alt_input_ids: Optional[torch.Tensor] = None,
|
211 |
+
alt_attention_mask: Optional[torch.Tensor] = None,
|
212 |
+
alt_labels: Optional[torch.Tensor] = None,
|
213 |
+
**kwargs,
|
214 |
+
):
|
215 |
+
# disable gradient computation for the teacher model
|
216 |
+
with torch.no_grad():
|
217 |
+
# compute the teacher (text-only) model's distribution
|
218 |
+
alt_inputs_embeds = self.get_input_embeddings().forward(alt_input_ids)
|
219 |
+
alt_lm_output = self.language_model.forward(
|
220 |
+
inputs_embeds=alt_inputs_embeds,
|
221 |
+
labels=alt_labels,
|
222 |
+
attention_mask=alt_attention_mask,
|
223 |
+
past_key_values=past_key_values,
|
224 |
+
**kwargs,
|
225 |
+
)
|
226 |
+
|
227 |
+
# Get prediction masks for regular tokens and EOT tokens
|
228 |
+
pred_mask, eot_mask = self._get_prediction_mask(labels)
|
229 |
+
alt_pred_mask, alt_eot_mask = self._get_prediction_mask(alt_labels)
|
230 |
+
|
231 |
+
# compute the KL divergence loss between the two models for regular tokens
|
232 |
+
kl_loss = F.kl_div(
|
233 |
+
F.log_softmax(
|
234 |
+
lm_output.logits[pred_mask] / self.loss_config.kl_temperature,
|
235 |
+
dim=-1,
|
236 |
+
),
|
237 |
+
F.softmax(
|
238 |
+
alt_lm_output.logits[alt_pred_mask] / self.loss_config.kl_temperature,
|
239 |
+
dim=-1,
|
240 |
+
),
|
241 |
+
reduction="batchmean",
|
242 |
+
)
|
243 |
+
|
244 |
+
# Compute the KL divergence loss for EOT token positions if any exist
|
245 |
+
if self.loss_config.eot_loss_weight > 0:
|
246 |
+
eot_loss = F.kl_div(
|
247 |
+
F.log_softmax(
|
248 |
+
lm_output.logits[eot_mask] / self.loss_config.kl_temperature,
|
249 |
+
dim=-1,
|
250 |
+
),
|
251 |
+
F.softmax(
|
252 |
+
alt_lm_output.logits[alt_eot_mask]
|
253 |
+
/ self.loss_config.kl_temperature,
|
254 |
+
dim=-1,
|
255 |
+
),
|
256 |
+
reduction="batchmean",
|
257 |
+
)
|
258 |
+
kl_loss += self.loss_config.eot_loss_weight * eot_loss
|
259 |
+
|
260 |
+
return kl_loss
|
261 |
+
|
262 |
+
def _audio_iter(
|
263 |
+
self, audio_batch_size: torch.Tensor
|
264 |
+
) -> Generator[Tuple[int, int], None, None]:
|
265 |
+
"""
|
266 |
+
Iterate over the audio batch size and yield the batch index and audio index of each audio item.
|
267 |
+
|
268 |
+
Args:
|
269 |
+
audio_batch_size: A tensor of shape (B,) where B is the batch size.
|
270 |
+
|
271 |
+
Returns:
|
272 |
+
A generator that yields a tuple of (start index, length) for each audio item.
|
273 |
+
"""
|
274 |
+
audio_index = 0
|
275 |
+
for i_b, batch_count in enumerate(audio_batch_size):
|
276 |
+
for _ in range(batch_count):
|
277 |
+
yield i_b, audio_index
|
278 |
+
audio_index += 1
|
279 |
+
|
280 |
+
def forward(
|
281 |
+
self,
|
282 |
+
input_ids: torch.Tensor,
|
283 |
+
audio_values: Optional[torch.FloatTensor] = None,
|
284 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
285 |
+
labels: Optional[torch.Tensor] = None,
|
286 |
+
attention_mask: Optional[torch.Tensor] = None,
|
287 |
+
audio_token_start_idx: Optional[torch.Tensor] = None,
|
288 |
+
audio_lens: Optional[torch.Tensor] = None,
|
289 |
+
audio_token_len: Optional[torch.Tensor] = None,
|
290 |
+
audio_batch_size: Optional[torch.Tensor] = None,
|
291 |
+
past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
|
292 |
+
# the alt_* fields are needed for KL divergence loss
|
293 |
+
alt_input_ids: Optional[torch.Tensor] = None,
|
294 |
+
alt_attention_mask: Optional[torch.Tensor] = None,
|
295 |
+
alt_labels: Optional[torch.Tensor] = None,
|
296 |
+
**kwargs,
|
297 |
+
) -> transformers.modeling_outputs.CausalLMOutputWithPast:
|
298 |
+
"""
|
299 |
+
Forward pass for the Ultravox model.
|
300 |
+
|
301 |
+
`input_ids` are the tokenized text input. They are embedded by the language model as usual.
|
302 |
+
`audio_values` are processed by the audio encoder and then every `stack_factor` frames are stacked together and
|
303 |
+
projected to the language model's embedding space using a few linear layers.
|
304 |
+
The audio and text embeddings are merged together. A special token `<|audio|>` is used to indicate the start
|
305 |
+
of the audio embeddings in the merged embeddings.
|
306 |
+
|
307 |
+
Args:
|
308 |
+
input_ids: The tokenized text input.
|
309 |
+
audio_values: The processed audio values.
|
310 |
+
inputs_embeds: The embeddings for the input tokens.
|
311 |
+
labels: The tokenized text labels.
|
312 |
+
attention_mask: The attention mask for the input.
|
313 |
+
position_ids: The position ids for the input.
|
314 |
+
past_key_values: The past key value cache for the language model attention layers.
|
315 |
+
**kwargs: Additional keyword arguments. Passed directly to the language model.
|
316 |
+
"""
|
317 |
+
if inputs_embeds is None:
|
318 |
+
# B x T -> B x T x D
|
319 |
+
inputs_embeds = self.get_input_embeddings().forward(input_ids)
|
320 |
+
|
321 |
+
if audio_values is not None and len(audio_values) > 0:
|
322 |
+
assert (
|
323 |
+
audio_token_start_idx is not None
|
324 |
+
and audio_token_len is not None
|
325 |
+
and audio_lens is not None
|
326 |
+
and audio_batch_size is not None
|
327 |
+
), "audio_token_start_idx/audio_token_len/audio_lens must be provided if audio_values are provided."
|
328 |
+
assert (
|
329 |
+
len(audio_token_start_idx)
|
330 |
+
== len(audio_token_len)
|
331 |
+
== len(audio_lens)
|
332 |
+
== len(audio_values)
|
333 |
+
), "audio_token_start_idx/audio_token_len/audio_lens/audio_values must have the same batch size."
|
334 |
+
assert len(audio_batch_size) == len(
|
335 |
+
inputs_embeds
|
336 |
+
), "audio_batch_size and inputs_embeds must have the same batch size."
|
337 |
+
|
338 |
+
# B x A/3200 x (D=max-audio-length-in-batch)
|
339 |
+
audio_tower_output = self.audio_tower.forward(
|
340 |
+
audio_values.to(self.audio_tower.dtype),
|
341 |
+
audio_len=audio_lens,
|
342 |
+
).last_hidden_state
|
343 |
+
audio_tower_output = audio_tower_output.to(inputs_embeds.dtype)
|
344 |
+
audio_embeds = self.multi_modal_projector.forward(audio_tower_output)
|
345 |
+
|
346 |
+
# combine audio and text embeddings
|
347 |
+
for i_b, i_a in self._audio_iter(audio_batch_size):
|
348 |
+
start_idx = audio_token_start_idx[i_a]
|
349 |
+
token_len = audio_token_len[i_a]
|
350 |
+
item_embedding = audio_embeds[i_a][:token_len]
|
351 |
+
inputs_embeds[i_b][start_idx : start_idx + token_len] = item_embedding
|
352 |
+
|
353 |
+
lm_output = self.language_model.forward(
|
354 |
+
inputs_embeds=inputs_embeds,
|
355 |
+
labels=labels,
|
356 |
+
attention_mask=attention_mask,
|
357 |
+
past_key_values=past_key_values,
|
358 |
+
**kwargs,
|
359 |
+
)
|
360 |
+
if self.loss_config.loss_function == LossFunction.CrossEntropy:
|
361 |
+
pass
|
362 |
+
elif self.loss_config.loss_function == LossFunction.KL_Divergence:
|
363 |
+
lm_output.loss = self._compute_kl_loss(
|
364 |
+
lm_output=lm_output,
|
365 |
+
labels=labels,
|
366 |
+
past_key_values=past_key_values,
|
367 |
+
alt_input_ids=alt_input_ids,
|
368 |
+
alt_attention_mask=alt_attention_mask,
|
369 |
+
alt_labels=alt_labels,
|
370 |
+
**kwargs,
|
371 |
+
)
|
372 |
+
else:
|
373 |
+
raise ValueError(
|
374 |
+
f"Unsupported loss function: {self.loss_config.loss_function}"
|
375 |
+
)
|
376 |
+
return lm_output
|
377 |
+
|
378 |
+
def prepare_inputs_for_generation(
|
379 |
+
self,
|
380 |
+
input_ids: torch.Tensor,
|
381 |
+
audio_values: Optional[torch.FloatTensor] = None,
|
382 |
+
audio_token_start_idx: Optional[torch.Tensor] = None,
|
383 |
+
audio_token_len: Optional[torch.Tensor] = None,
|
384 |
+
audio_lens: Optional[torch.Tensor] = None,
|
385 |
+
audio_batch_size: Optional[torch.Tensor] = None,
|
386 |
+
past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
|
387 |
+
attention_mask: Optional[torch.Tensor] = None,
|
388 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
389 |
+
cache_position: Optional[torch.Tensor] = None,
|
390 |
+
**kwargs,
|
391 |
+
) -> Dict[str, Any]:
|
392 |
+
model_input = self.language_model.prepare_inputs_for_generation(
|
393 |
+
input_ids=input_ids,
|
394 |
+
past_key_values=past_key_values,
|
395 |
+
attention_mask=attention_mask,
|
396 |
+
inputs_embeds=inputs_embeds,
|
397 |
+
cache_position=cache_position,
|
398 |
+
**kwargs,
|
399 |
+
)
|
400 |
+
|
401 |
+
# include audio information in model_input only when it is needed during prefilling
|
402 |
+
# audio_token_start_idx should always be relative to the current cache position
|
403 |
+
prefill_start_idx: int | torch.Tensor = (
|
404 |
+
0 if cache_position is None else cache_position[0]
|
405 |
+
)
|
406 |
+
if (
|
407 |
+
audio_values is not None
|
408 |
+
and audio_token_start_idx is not None
|
409 |
+
and prefill_start_idx <= torch.max(audio_token_start_idx)
|
410 |
+
):
|
411 |
+
model_input["audio_values"] = audio_values
|
412 |
+
model_input["audio_token_start_idx"] = (
|
413 |
+
audio_token_start_idx - prefill_start_idx
|
414 |
+
)
|
415 |
+
model_input["audio_token_len"] = audio_token_len
|
416 |
+
model_input["audio_batch_size"] = audio_batch_size
|
417 |
+
model_input["audio_lens"] = audio_lens
|
418 |
+
|
419 |
+
return model_input
|
420 |
+
|
421 |
+
@classmethod
|
422 |
+
def _create_multi_modal_projector(
|
423 |
+
cls, config: UltravoxConfig
|
424 |
+
) -> "UltravoxProjector":
|
425 |
+
projector = UltravoxProjector(config)
|
426 |
+
dtype = config.torch_dtype
|
427 |
+
if isinstance(dtype, str):
|
428 |
+
dtype = getattr(torch, dtype)
|
429 |
+
projector.to(dtype)
|
430 |
+
return projector
|
431 |
+
|
432 |
+
@classmethod
|
433 |
+
def _create_audio_tower(
|
434 |
+
cls, config: UltravoxConfig
|
435 |
+
) -> Union[transformers.Wav2Vec2Model, "ModifiedWhisperEncoder"]:
|
436 |
+
# We probably don't want to pass tp_plan or device_map to the audio tower
|
437 |
+
# But potentially other kwargs can be passed in. TODO
|
438 |
+
kwargs = {"torch_dtype": config.torch_dtype}
|
439 |
+
if (
|
440 |
+
transformers.modeling_utils._init_weights
|
441 |
+
and config.audio_model_id is not None
|
442 |
+
):
|
443 |
+
if "whisper" in config.audio_model_id.lower():
|
444 |
+
audio_tower = ModifiedWhisperEncoder.from_pretrained(
|
445 |
+
config.audio_model_id, **kwargs
|
446 |
+
)
|
447 |
+
audio_tower.init_latency_mask(
|
448 |
+
config.audio_latency_block_size, dtype=config.torch_dtype
|
449 |
+
)
|
450 |
+
else:
|
451 |
+
assert config.audio_latency_block_size in (
|
452 |
+
None,
|
453 |
+
0,
|
454 |
+
), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
|
455 |
+
audio_tower = transformers.AutoModel.from_pretrained(
|
456 |
+
config.audio_model_id, **kwargs
|
457 |
+
)
|
458 |
+
else:
|
459 |
+
with accelerate.init_empty_weights():
|
460 |
+
if "whisper" in config.audio_config._name_or_path.lower():
|
461 |
+
audio_tower = ModifiedWhisperEncoder(config.audio_config)
|
462 |
+
audio_tower.init_latency_mask(
|
463 |
+
config.audio_latency_block_size,
|
464 |
+
dtype=config.torch_dtype,
|
465 |
+
)
|
466 |
+
else:
|
467 |
+
assert config.audio_latency_block_size in (
|
468 |
+
None,
|
469 |
+
0,
|
470 |
+
), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
|
471 |
+
# we only ever use from_config if the weights are retrained, hence initializing is not
|
472 |
+
# required. This makes the model quite creation faster since init on CPU is quite slow.
|
473 |
+
audio_tower = transformers.AutoModel.from_config(
|
474 |
+
config.audio_config, **kwargs
|
475 |
+
)
|
476 |
+
|
477 |
+
if isinstance(
|
478 |
+
audio_tower,
|
479 |
+
(transformers.Wav2Vec2BertModel, transformers.WhisperModel),
|
480 |
+
):
|
481 |
+
# For these models we only need the encoder part
|
482 |
+
# Wav2Vec2BertModel -> Wav2Vec2BertEncoder
|
483 |
+
# WhisperModel -> WhisperEncoder
|
484 |
+
audio_tower = audio_tower.encoder
|
485 |
+
|
486 |
+
audio_tower = apply_lora(audio_tower, config.audio_model_lora_config)
|
487 |
+
return audio_tower
|
488 |
+
|
489 |
+
@classmethod
|
490 |
+
def _create_language_model(
|
491 |
+
cls, config: UltravoxConfig
|
492 |
+
) -> transformers.LlamaForCausalLM:
|
493 |
+
if (
|
494 |
+
transformers.modeling_utils._init_weights
|
495 |
+
and config.text_model_id is not None
|
496 |
+
):
|
497 |
+
language_model = transformers.AutoModelForCausalLM.from_pretrained(
|
498 |
+
config.text_model_id,
|
499 |
+
**{
|
500 |
+
"attn_implementation": config.text_config._attn_implementation,
|
501 |
+
"torch_dtype": config.torch_dtype,
|
502 |
+
**FROM_PRETRAINED_KWARGS,
|
503 |
+
},
|
504 |
+
)
|
505 |
+
else:
|
506 |
+
with accelerate.init_empty_weights():
|
507 |
+
# we only ever use from_config if the weights are retrained, hence initializing is not
|
508 |
+
# required. This makes the model quite creation faster since init on CPU is quite slow.
|
509 |
+
language_model = transformers.AutoModelForCausalLM.from_config(
|
510 |
+
config.text_config,
|
511 |
+
attn_implementation=config.text_config._attn_implementation,
|
512 |
+
torch_dtype=config.torch_dtype,
|
513 |
+
)
|
514 |
+
|
515 |
+
language_model = apply_lora(language_model, config.text_model_lora_config)
|
516 |
+
return language_model
|
517 |
+
|
518 |
+
def merge_and_unload(self):
|
519 |
+
if isinstance(self.language_model, peft.PeftModel):
|
520 |
+
self.language_model = self.language_model.merge_and_unload()
|
521 |
+
# no need to download base language model weights anymore, so we can remove the id
|
522 |
+
self.config.text_model_id = None
|
523 |
+
self.keep_params.update(
|
524 |
+
set(
|
525 |
+
[
|
526 |
+
f"language_model.{name}"
|
527 |
+
for name, _ in self.language_model.named_parameters()
|
528 |
+
]
|
529 |
+
)
|
530 |
+
)
|
531 |
+
|
532 |
+
if isinstance(self.audio_tower, peft.PeftModel):
|
533 |
+
self.audio_tower = self.audio_tower.merge_and_unload()
|
534 |
+
# no need to download base audio model weights anymore, so we can remove the id
|
535 |
+
self.config.audio_model_id = None
|
536 |
+
self.keep_params.update(
|
537 |
+
set(
|
538 |
+
[
|
539 |
+
f"audio_tower.{name}"
|
540 |
+
for name, _ in self.audio_tower.named_parameters()
|
541 |
+
]
|
542 |
+
)
|
543 |
+
)
|
544 |
+
|
545 |
+
for param in ["text_model_lora_config", "audio_model_lora_config"]:
|
546 |
+
if hasattr(self.config, param):
|
547 |
+
delattr(self.config, param)
|
548 |
+
|
549 |
+
def push_to_hub(self, *args, **kwargs):
|
550 |
+
self.merge_and_unload()
|
551 |
+
return super().push_to_hub(*args, **kwargs)
|
552 |
+
|
553 |
+
def diff_state_dict(
|
554 |
+
self, state_dict: Optional[Dict[str, Any]] = None
|
555 |
+
) -> Dict[str, Any]:
|
556 |
+
if state_dict is None:
|
557 |
+
state_dict = super().state_dict()
|
558 |
+
|
559 |
+
trainable_params = {k for k, v in self.named_parameters() if v.requires_grad}
|
560 |
+
# normalize the keys to match the original model
|
561 |
+
# Example: audio_tower.base_model.model.layers.0._fsdp_wrapped_module.self_attn.k_proj.lora_B.default.weight
|
562 |
+
trainable_params = {
|
563 |
+
k.replace("_fsdp_wrapped_module.", "") for k in trainable_params
|
564 |
+
}
|
565 |
+
|
566 |
+
state_dict = {
|
567 |
+
k: v
|
568 |
+
for k, v in state_dict.items()
|
569 |
+
if k in self.keep_params or k in trainable_params
|
570 |
+
}
|
571 |
+
|
572 |
+
return state_dict
|
573 |
+
|
574 |
+
def save_pretrained(
|
575 |
+
self, *args, state_dict: Optional[Dict[str, Any]] = None, **kwargs
|
576 |
+
):
|
577 |
+
state_dict = self.diff_state_dict(state_dict)
|
578 |
+
|
579 |
+
super().save_pretrained(*args, state_dict=state_dict, **kwargs)
|
580 |
+
|
581 |
+
def _pre_load_state_dict_hook(self, state_dict: Dict[str, Any], *args, **kwargs):
|
582 |
+
self.keep_params.update(set(state_dict.keys()))
|
583 |
+
|
584 |
+
def print_trainable_parameters(self):
|
585 |
+
"""
|
586 |
+
Prints the number of trainable parameters in the model (reuses Peft model's method)
|
587 |
+
"""
|
588 |
+
count_params = peft.peft_model.PeftModel.get_nb_trainable_parameters
|
589 |
+
|
590 |
+
trainable_params, all_param = count_params(self)
|
591 |
+
|
592 |
+
logging.info(
|
593 |
+
f"trainable params: {trainable_params:,d} || all params: {all_param:,d}"
|
594 |
+
f" || trainable%: {100 * trainable_params / all_param:.1f}%"
|
595 |
+
)
|
596 |
+
|
597 |
+
lm_trainable_params, lm_all_params = count_params(self.language_model)
|
598 |
+
audio_trainable_params, audio_all_params = count_params(self.audio_tower)
|
599 |
+
|
600 |
+
projector_trainable_params = (
|
601 |
+
trainable_params - lm_trainable_params - audio_trainable_params
|
602 |
+
)
|
603 |
+
projector_all_params = all_param - lm_all_params - audio_all_params
|
604 |
+
|
605 |
+
logging.info(
|
606 |
+
f"Trainable%: "
|
607 |
+
f" LLM: {100 * lm_trainable_params / lm_all_params:.1f}%"
|
608 |
+
f" || Audio Encoder: {100 * audio_trainable_params / audio_all_params:.1f}%"
|
609 |
+
f" || Projector: {100 * projector_trainable_params / projector_all_params:.1f}%"
|
610 |
+
)
|
611 |
+
|
612 |
+
|
613 |
+
def get_checkpoint_files(
|
614 |
+
model_id: str,
|
615 |
+
) -> tuple[list[str], dict | None, list[str]]:
|
616 |
+
resolved_archive_file = transformers.utils.cached_file(
|
617 |
+
model_id,
|
618 |
+
transformers.utils.SAFE_WEIGHTS_NAME,
|
619 |
+
_raise_exceptions_for_missing_entries=False,
|
620 |
+
)
|
621 |
+
|
622 |
+
if resolved_archive_file is not None:
|
623 |
+
# not sharded
|
624 |
+
sharded_metadata = None
|
625 |
+
state_dict = transformers.modeling_utils.load_state_dict(resolved_archive_file)
|
626 |
+
loaded_state_dict_keys = list(state_dict.keys())
|
627 |
+
else:
|
628 |
+
# sharded
|
629 |
+
resolved_archive_file = transformers.utils.cached_file(
|
630 |
+
model_id, transformers.utils.SAFE_WEIGHTS_INDEX_NAME
|
631 |
+
)
|
632 |
+
resolved_archive_file, sharded_metadata = (
|
633 |
+
transformers.modeling_utils.get_checkpoint_shard_files(
|
634 |
+
model_id,
|
635 |
+
resolved_archive_file,
|
636 |
+
)
|
637 |
+
)
|
638 |
+
loaded_state_dict_keys = sharded_metadata["all_checkpoint_keys"]
|
639 |
+
|
640 |
+
if isinstance(resolved_archive_file, str):
|
641 |
+
resolved_archive_file = [resolved_archive_file]
|
642 |
+
|
643 |
+
return resolved_archive_file, sharded_metadata, loaded_state_dict_keys
|
644 |
+
|
645 |
+
|
646 |
+
# TODO: refactor common parts to a shared module
|
647 |
+
def is_cache_empty(
|
648 |
+
past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]],
|
649 |
+
) -> bool:
|
650 |
+
"""
|
651 |
+
Check if the cache is empty.
|
652 |
+
"""
|
653 |
+
if past_key_values is None:
|
654 |
+
return True
|
655 |
+
if isinstance(past_key_values, tuple):
|
656 |
+
return all(len(c) == 0 for c in past_key_values)
|
657 |
+
return past_key_values.get_seq_length() == 0
|
658 |
+
|
659 |
+
|
660 |
+
T = TypeVar("T", bound=torch.nn.Module)
|
661 |
+
|
662 |
+
|
663 |
+
def apply_lora(model: T, lora_config: dict) -> T:
|
664 |
+
"""
|
665 |
+
Applies LoRA finetuning to the model. If the `r` parameter is set to 0, the model is frozen instead.
|
666 |
+
"""
|
667 |
+
unfreeze_layers = lora_config.pop("unfreeze_layers", None)
|
668 |
+
lora_config = peft.LoraConfig(**lora_config or {})
|
669 |
+
|
670 |
+
if lora_config.r == 0:
|
671 |
+
# freeze the model entirely, except for the specified layers
|
672 |
+
for name, param in model.named_parameters():
|
673 |
+
if not unfreeze_layers or not any(
|
674 |
+
re.match(layer, name) for layer in unfreeze_layers
|
675 |
+
):
|
676 |
+
param.requires_grad = False
|
677 |
+
else:
|
678 |
+
logging.info(f"Unfreezing layer: {name} with #{param.numel()} params")
|
679 |
+
else:
|
680 |
+
model = peft.get_peft_model(model, lora_config)
|
681 |
+
|
682 |
+
return model
|
683 |
+
|
684 |
+
|
685 |
+
class StackAudioFrames(nn.Module):
|
686 |
+
"""
|
687 |
+
Stack the audio embedding frames to reduce the sequence length by a factor
|
688 |
+
of `stack_factor`.
|
689 |
+
"""
|
690 |
+
|
691 |
+
def __init__(self, stack_factor: int = 8):
|
692 |
+
super().__init__()
|
693 |
+
self.stack_factor = stack_factor
|
694 |
+
|
695 |
+
def forward(self, audio_embeds: torch.Tensor) -> torch.Tensor:
|
696 |
+
B, T, C = audio_embeds.shape
|
697 |
+
T_pad = (T + self.stack_factor - 1) // self.stack_factor * self.stack_factor
|
698 |
+
audio_embeds = F.pad(audio_embeds, (0, 0, 0, T_pad - T))
|
699 |
+
B, T, C = audio_embeds.shape
|
700 |
+
audio_embeds = audio_embeds.view(
|
701 |
+
B, T // self.stack_factor, C * self.stack_factor
|
702 |
+
)
|
703 |
+
return audio_embeds
|
704 |
+
|
705 |
+
|
706 |
+
class RMSNorm(transformers.models.llama.modeling_llama.LlamaRMSNorm):
|
707 |
+
def __init__(self, hidden_size: int, init: float = 1, eps: float = 1e-6):
|
708 |
+
super().__init__(hidden_size=hidden_size, eps=eps)
|
709 |
+
self.weight.data.fill_(init)
|
710 |
+
|
711 |
+
|
712 |
+
class SwiGLU(nn.Module):
|
713 |
+
def forward(self, x):
|
714 |
+
x, gate = x.chunk(2, dim=-1)
|
715 |
+
return F.silu(gate) * x
|
716 |
+
|
717 |
+
|
718 |
+
class UltravoxProjector(nn.Module):
|
719 |
+
def __init__(self, config: UltravoxConfig):
|
720 |
+
super().__init__()
|
721 |
+
self.hidden_dim = config.hidden_size
|
722 |
+
self._pad_and_stack = StackAudioFrames(config.stack_factor)
|
723 |
+
dim_in = config.audio_config.hidden_size * config.stack_factor
|
724 |
+
self.ln_pre = RMSNorm(dim_in, init=config.norm_init)
|
725 |
+
self.linear_1 = nn.Linear(dim_in, self.hidden_dim, bias=False)
|
726 |
+
dim_mid = self.hidden_dim
|
727 |
+
self.act = transformers.activations.get_activation(config.projector_act)
|
728 |
+
dim_mid = dim_mid // 2 if config.projector_act == "swiglu" else dim_mid
|
729 |
+
dim_out = config.text_config.hidden_size
|
730 |
+
self.linear_2 = nn.Linear(dim_mid, dim_out, bias=False)
|
731 |
+
|
732 |
+
# Ultravox v0.4.1 and below uses layer_norm after the second linear layer,
|
733 |
+
# while v0.5.0 and above uses layer_norm after the first linear layer.
|
734 |
+
if config.projector_ln_mid:
|
735 |
+
self.ln_mid: nn.Module = RMSNorm(dim_mid, init=config.norm_init)
|
736 |
+
self.ln_post: nn.Module = nn.Identity()
|
737 |
+
else:
|
738 |
+
self.ln_mid = nn.Identity()
|
739 |
+
self.ln_post = RMSNorm(dim_out, init=config.norm_init)
|
740 |
+
|
741 |
+
def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
|
742 |
+
"""
|
743 |
+
Takes in audio features from the audio tower and projects them to the text model's embedding space.
|
744 |
+
It reduces the number of frames by a factor of `stack_factor` and increases the number of channels by the same factor.
|
745 |
+
If the number of audio frames are not a multiple of the stack factor, the last few frames will be padded with zeros.
|
746 |
+
|
747 |
+
Input shape:
|
748 |
+
audio_features: B, T*S, C
|
749 |
+
Output shape:
|
750 |
+
hidden_states: B, T, D
|
751 |
+
Where:
|
752 |
+
B: batch size
|
753 |
+
F: number of frames in the audio tower
|
754 |
+
T: number of output embeddings
|
755 |
+
T = ceil(F / S)
|
756 |
+
S: stack factor
|
757 |
+
C: number of channels out of the encoder (aka audio tower)
|
758 |
+
H: hidden size of the projector (config.hidden_size)
|
759 |
+
D: dimension of the text model (config.text_config.hidden_size)
|
760 |
+
|
761 |
+
"""
|
762 |
+
# B, F, C -> B, T, C*S
|
763 |
+
audio_features = self._pad_and_stack(audio_features)
|
764 |
+
audio_features = self.ln_pre(audio_features)
|
765 |
+
# B, T, C*S -> B, T, H
|
766 |
+
hidden_states = self.linear_1(audio_features)
|
767 |
+
# B, T, H -> B, T, H/2 (assuming swiglu)
|
768 |
+
hidden_states = self.act(hidden_states)
|
769 |
+
hidden_states = self.ln_mid(hidden_states)
|
770 |
+
# B, T, H/2 -> B, T, D
|
771 |
+
hidden_states = self.linear_2(hidden_states)
|
772 |
+
hidden_states = self.ln_post(hidden_states)
|
773 |
+
return hidden_states
|
774 |
+
|
775 |
+
|
776 |
+
class ModifiedWhisperEncoder(
|
777 |
+
whisper.WhisperEncoder, transformers.modeling_utils.ModuleUtilsMixin
|
778 |
+
):
|
779 |
+
"""
|
780 |
+
Encoder portion of OpenAI's Whisper model.
|
781 |
+
|
782 |
+
This implementation is a slightly modified version of HF Transformers' Whisper Encoder, with only a few fixes:
|
783 |
+
1. base_model_prefix updated to allow for doing `.from_pretrained` directly on the encoder
|
784 |
+
2. allow less than 30 second of audio padding to be passed in:
|
785 |
+
- relaxed ValueError check for `input_features` length to be less than or equal to `expected_seq_length` instead of strictly equal
|
786 |
+
- embed_pos is now sliced to match the length of `inputs_embeds`
|
787 |
+
|
788 |
+
Original: https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py
|
789 |
+
"""
|
790 |
+
|
791 |
+
base_model_prefix = "model.encoder"
|
792 |
+
_no_split_modules = ["WhisperEncoderLayer"]
|
793 |
+
_keys_to_ignore_on_load_unexpected = ["model.decoder.*"]
|
794 |
+
|
795 |
+
def __init__(self, config: transformers.WhisperConfig):
|
796 |
+
super().__init__(config)
|
797 |
+
self.config.is_decoder = False
|
798 |
+
|
799 |
+
@property
|
800 |
+
def max_context_length(self):
|
801 |
+
return (
|
802 |
+
self.config.max_source_positions
|
803 |
+
* self.conv1.stride[0]
|
804 |
+
* self.conv2.stride[0]
|
805 |
+
)
|
806 |
+
|
807 |
+
def init_latency_mask(
|
808 |
+
self, audio_latency_block_size: int | None, dtype: torch.dtype
|
809 |
+
):
|
810 |
+
if audio_latency_block_size is None:
|
811 |
+
self.audio_streaming_mask = None
|
812 |
+
return
|
813 |
+
|
814 |
+
# Use max_context_length directly in the calculation
|
815 |
+
max_seqlen = self.max_context_length
|
816 |
+
assert (
|
817 |
+
max_seqlen > 0
|
818 |
+
), f"maximum sequence length must be positive, got {max_seqlen}"
|
819 |
+
assert (
|
820 |
+
max_seqlen % audio_latency_block_size == 0
|
821 |
+
), f"audio_latency_block_size {audio_latency_block_size} must divide {max_seqlen} evenly."
|
822 |
+
# Given the block size, we calculate number of blocks.
|
823 |
+
audio_latency_nblocks = max_seqlen // audio_latency_block_size
|
824 |
+
audio_streaming_mask = (
|
825 |
+
torch.tril(
|
826 |
+
torch.ones(audio_latency_nblocks, audio_latency_nblocks),
|
827 |
+
diagonal=0,
|
828 |
+
)
|
829 |
+
.repeat_interleave(audio_latency_block_size, dim=0)
|
830 |
+
.repeat_interleave(audio_latency_block_size, dim=1)
|
831 |
+
)
|
832 |
+
audio_streaming_mask = (1.0 - audio_streaming_mask) * torch.finfo(dtype).min
|
833 |
+
audio_streaming_mask = audio_streaming_mask[None, None, :, :]
|
834 |
+
self.register_buffer(
|
835 |
+
"audio_streaming_mask", audio_streaming_mask, persistent=False
|
836 |
+
)
|
837 |
+
|
838 |
+
def forward(
|
839 |
+
self,
|
840 |
+
input_features,
|
841 |
+
audio_len=None,
|
842 |
+
head_mask=None,
|
843 |
+
output_attentions=None,
|
844 |
+
output_hidden_states=None,
|
845 |
+
return_dict=None,
|
846 |
+
):
|
847 |
+
expected_seq_length = self.max_context_length
|
848 |
+
if input_features.shape[-1] > expected_seq_length:
|
849 |
+
raise ValueError(
|
850 |
+
f"Whisper expects the mel input features to be of length {expected_seq_length} or less, but found {input_features.shape[-1]}. Make sure to pad the input mel features to {expected_seq_length}."
|
851 |
+
)
|
852 |
+
|
853 |
+
output_attentions = (
|
854 |
+
output_attentions
|
855 |
+
if output_attentions is not None
|
856 |
+
else self.config.output_attentions
|
857 |
+
)
|
858 |
+
output_hidden_states = (
|
859 |
+
output_hidden_states
|
860 |
+
if output_hidden_states is not None
|
861 |
+
else self.config.output_hidden_states
|
862 |
+
)
|
863 |
+
return_dict = (
|
864 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
865 |
+
)
|
866 |
+
inputs_embeds = nn.functional.gelu(self.conv1(input_features))
|
867 |
+
inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
|
868 |
+
|
869 |
+
inputs_embeds = inputs_embeds.permute(0, 2, 1)
|
870 |
+
embed_pos = self.embed_positions.weight[: inputs_embeds.size(-2)]
|
871 |
+
|
872 |
+
hidden_states = inputs_embeds + embed_pos
|
873 |
+
hidden_states = nn.functional.dropout(
|
874 |
+
hidden_states, p=self.dropout, training=self.training
|
875 |
+
)
|
876 |
+
|
877 |
+
encoder_states = () if output_hidden_states else None
|
878 |
+
all_attentions = () if output_attentions else None
|
879 |
+
|
880 |
+
# Create attention mask based on audio lengths to mask out padding tokens
|
881 |
+
# For each sample in batch:
|
882 |
+
# - Convert raw audio length to feature length after convolutions
|
883 |
+
# - Create boolean mask that is True for valid positions and False for padding
|
884 |
+
# - Convert to extended attention mask format expected by transformer layers
|
885 |
+
# (1.0 for positions to attend to, large negative for positions to ignore)
|
886 |
+
# This masking ensures consistent behavior between training and inference
|
887 |
+
# by preventing the model from attending to padding tokens in both cases
|
888 |
+
attention_mask = None
|
889 |
+
if audio_len is not None:
|
890 |
+
audio_feature_len = self._get_feat_extract_output_lengths(audio_len)
|
891 |
+
max_seq_len = hidden_states.shape[1]
|
892 |
+
attention_mask = torch.arange(max_seq_len, device=hidden_states.device)[
|
893 |
+
None, :
|
894 |
+
].lt(audio_feature_len.view(-1, 1))
|
895 |
+
attention_mask = self.get_extended_attention_mask(
|
896 |
+
attention_mask,
|
897 |
+
None,
|
898 |
+
dtype=hidden_states.dtype,
|
899 |
+
)
|
900 |
+
|
901 |
+
if self.audio_streaming_mask is not None:
|
902 |
+
seqlen = hidden_states.size(-2)
|
903 |
+
if attention_mask is not None:
|
904 |
+
attention_mask = torch.minimum(
|
905 |
+
self.audio_streaming_mask[:, :, :seqlen, :seqlen], attention_mask
|
906 |
+
) # merge
|
907 |
+
else:
|
908 |
+
attention_mask = self.audio_streaming_mask[:, :, :seqlen, :seqlen]
|
909 |
+
attention_mask = attention_mask.to(hidden_states.dtype)
|
910 |
+
|
911 |
+
# check if head_mask has a correct number of layers specified if desired
|
912 |
+
if head_mask is not None:
|
913 |
+
assert head_mask.size()[0] == (
|
914 |
+
len(self.layers)
|
915 |
+
), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
|
916 |
+
|
917 |
+
for idx, encoder_layer in enumerate(self.layers):
|
918 |
+
if output_hidden_states:
|
919 |
+
encoder_states = encoder_states + (hidden_states,)
|
920 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
921 |
+
to_drop = False
|
922 |
+
if self.training:
|
923 |
+
dropout_probability = torch.rand([])
|
924 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
925 |
+
to_drop = True
|
926 |
+
|
927 |
+
if to_drop:
|
928 |
+
layer_outputs = (None, None)
|
929 |
+
else:
|
930 |
+
if self.gradient_checkpointing and self.training:
|
931 |
+
layer_outputs = self._gradient_checkpointing_func(
|
932 |
+
encoder_layer.__call__,
|
933 |
+
hidden_states,
|
934 |
+
attention_mask,
|
935 |
+
(head_mask[idx] if head_mask is not None else None),
|
936 |
+
output_attentions,
|
937 |
+
)
|
938 |
+
else:
|
939 |
+
layer_outputs = encoder_layer(
|
940 |
+
hidden_states,
|
941 |
+
attention_mask,
|
942 |
+
layer_head_mask=(
|
943 |
+
head_mask[idx] if head_mask is not None else None
|
944 |
+
),
|
945 |
+
output_attentions=output_attentions,
|
946 |
+
)
|
947 |
+
|
948 |
+
hidden_states = layer_outputs[0]
|
949 |
+
|
950 |
+
if output_attentions:
|
951 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
952 |
+
|
953 |
+
hidden_states = self.layer_norm(hidden_states)
|
954 |
+
if output_hidden_states:
|
955 |
+
encoder_states = encoder_states + (hidden_states,)
|
956 |
+
|
957 |
+
if not return_dict:
|
958 |
+
return tuple(
|
959 |
+
v
|
960 |
+
for v in [hidden_states, encoder_states, all_attentions]
|
961 |
+
if v is not None
|
962 |
+
)
|
963 |
+
return transformers.modeling_outputs.BaseModelOutput(
|
964 |
+
last_hidden_state=hidden_states,
|
965 |
+
hidden_states=encoder_states,
|
966 |
+
attentions=all_attentions,
|
967 |
+
)
|
968 |
+
|
969 |
+
|
970 |
+
UltravoxConfig.register_for_auto_class()
|
971 |
+
UltravoxModel.register_for_auto_class()
|
972 |
+
|
973 |
+
transformers.AutoConfig.register("ultravox", UltravoxConfig)
|
974 |
+
transformers.AutoModel.register(UltravoxConfig, UltravoxModel)
|
975 |
+
|
976 |
+
transformers.activations.ACT2FN["swiglu"] = SwiGLU
|
ultravox_pipeline.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from typing import Any, Dict, List, Optional
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import transformers
|
6 |
+
|
7 |
+
# We must use relative import in this directory to allow uploading to HF Hub
|
8 |
+
# Even "from . import X" pattern doesn't work (undocumented and unclear why)
|
9 |
+
from .ultravox_model import UltravoxModel
|
10 |
+
from .ultravox_processing import UltravoxProcessor
|
11 |
+
from .ultravox_tokenizer import from_pretrained_text_tokenizer
|
12 |
+
from .ultravox_tokenizer import get_audio_token_id
|
13 |
+
|
14 |
+
|
15 |
+
class UltravoxPipeline(transformers.Pipeline):
|
16 |
+
def __init__(
|
17 |
+
self,
|
18 |
+
model: UltravoxModel,
|
19 |
+
tokenizer: Optional[transformers.PreTrainedTokenizerBase] = None,
|
20 |
+
audio_processor: Optional[transformers.ProcessorMixin] = None,
|
21 |
+
**kwargs
|
22 |
+
):
|
23 |
+
if tokenizer is None:
|
24 |
+
try:
|
25 |
+
tokenizer = from_pretrained_text_tokenizer(model.config._name_or_path)
|
26 |
+
except: # noqa: E722
|
27 |
+
tokenizer = from_pretrained_text_tokenizer(
|
28 |
+
model.config.text_model_id or model.config.text_config._name_or_path
|
29 |
+
)
|
30 |
+
|
31 |
+
model.config.audio_token_index = get_audio_token_id(tokenizer)
|
32 |
+
|
33 |
+
if audio_processor is None:
|
34 |
+
audio_processor = transformers.AutoProcessor.from_pretrained(
|
35 |
+
model.config.audio_model_id or model.config.audio_config._name_or_path
|
36 |
+
)
|
37 |
+
|
38 |
+
super().__init__(model=model, tokenizer=tokenizer, **kwargs)
|
39 |
+
|
40 |
+
self.processor = UltravoxProcessor(
|
41 |
+
audio_processor=audio_processor,
|
42 |
+
tokenizer=tokenizer,
|
43 |
+
stack_factor=model.config.stack_factor,
|
44 |
+
audio_context_size=model.audio_tower_context_length,
|
45 |
+
)
|
46 |
+
|
47 |
+
def _sanitize_parameters(self, **kwargs):
|
48 |
+
generation_keys = ["temperature", "max_new_tokens", "repetition_penalty"]
|
49 |
+
generation_kwargs = {k: kwargs[k] for k in kwargs if k in generation_keys}
|
50 |
+
return {}, generation_kwargs, {}
|
51 |
+
|
52 |
+
def preprocess(self, inputs: Dict[str, Any]):
|
53 |
+
turns: list = inputs.get("turns", [])
|
54 |
+
|
55 |
+
audio = inputs.get("audio", None)
|
56 |
+
# Convert to float32 if needed.
|
57 |
+
if isinstance(audio, np.ndarray):
|
58 |
+
if audio.dtype == np.float64:
|
59 |
+
audio = audio.astype(np.float32)
|
60 |
+
elif audio.dtype == np.int16:
|
61 |
+
audio = audio.astype(np.float32) / np.float32(32768.0)
|
62 |
+
elif audio.dtype == np.int32:
|
63 |
+
audio = audio.astype(np.float32) / np.float32(2147483648.0)
|
64 |
+
|
65 |
+
if audio is not None and (len(turns) == 0 or turns[-1]["role"] != "user"):
|
66 |
+
prompt = inputs.get("prompt", "<|audio|>")
|
67 |
+
if "<|audio|>" not in prompt:
|
68 |
+
logging.warning(
|
69 |
+
"Prompt does not contain '<|audio|>', appending '<|audio|>' to the end of the prompt."
|
70 |
+
)
|
71 |
+
|
72 |
+
prompt += " <|audio|>"
|
73 |
+
turns.append({"role": "user", "content": prompt})
|
74 |
+
|
75 |
+
text = self.processor.tokenizer.apply_chat_template(
|
76 |
+
turns, add_generation_prompt=True, tokenize=False
|
77 |
+
)
|
78 |
+
|
79 |
+
if "sampling_rate" not in inputs and audio is not None:
|
80 |
+
logging.warning(
|
81 |
+
"No sampling rate provided, using default of 16kHz. We highly recommend providing the correct sampling rate."
|
82 |
+
)
|
83 |
+
|
84 |
+
output = self.processor(
|
85 |
+
text=text,
|
86 |
+
audio=audio,
|
87 |
+
sampling_rate=inputs.get("sampling_rate", 16000),
|
88 |
+
)
|
89 |
+
if "audio_values" in output:
|
90 |
+
output["audio_values"] = output["audio_values"].to(self.model.dtype)
|
91 |
+
|
92 |
+
return output
|
93 |
+
|
94 |
+
def _forward(
|
95 |
+
self,
|
96 |
+
model_inputs: Dict[str, Any],
|
97 |
+
temperature: Optional[float] = None,
|
98 |
+
max_new_tokens: Optional[int] = None,
|
99 |
+
repetition_penalty: float = 1.1,
|
100 |
+
) -> List[int]:
|
101 |
+
temperature = temperature or None
|
102 |
+
do_sample = temperature is not None
|
103 |
+
|
104 |
+
terminators = [self.tokenizer.eos_token_id]
|
105 |
+
if "<|eot_id|>" in self.tokenizer.added_tokens_encoder:
|
106 |
+
terminators.append(self.tokenizer.convert_tokens_to_ids("<|eot_id|>"))
|
107 |
+
|
108 |
+
input_len = model_inputs["input_ids"].shape[1]
|
109 |
+
|
110 |
+
outputs = self.model.generate(
|
111 |
+
**model_inputs,
|
112 |
+
do_sample=do_sample,
|
113 |
+
temperature=temperature,
|
114 |
+
max_new_tokens=max_new_tokens,
|
115 |
+
repetition_penalty=repetition_penalty,
|
116 |
+
eos_token_id=terminators
|
117 |
+
)
|
118 |
+
return outputs[0][input_len:]
|
119 |
+
|
120 |
+
def postprocess(self, model_outputs) -> str:
|
121 |
+
output_text = self.tokenizer.decode(model_outputs, skip_special_tokens=True)
|
122 |
+
return output_text
|
123 |
+
|
124 |
+
|
125 |
+
transformers.pipelines.PIPELINE_REGISTRY.register_pipeline(
|
126 |
+
"ultravox-pipeline",
|
127 |
+
pipeline_class=UltravoxPipeline,
|
128 |
+
pt_model=transformers.AutoModel,
|
129 |
+
type="multimodal",
|
130 |
+
)
|
ultravox_processing.py
ADDED
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
from typing import Any, Dict, List, Optional, Union
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
import torch.nn.functional as F
|
7 |
+
import transformers
|
8 |
+
|
9 |
+
from .ultravox_config import UltravoxConfig
|
10 |
+
|
11 |
+
|
12 |
+
@dataclasses.dataclass
|
13 |
+
class DataCollatorForSeq2SeqWithAudio(transformers.DataCollatorForSeq2Seq):
|
14 |
+
# when enabled, the alt_input_ids, alt_attention_mask, and alt_labels fields are used for computing the KL loss in UltravoxModel
|
15 |
+
include_alt_fields: bool = False
|
16 |
+
|
17 |
+
def __call__(self, features, *args, **kwargs):
|
18 |
+
audio_values = [x for f in features for x in f.pop("audio_values", [])]
|
19 |
+
audio_lens = [x for f in features for x in f.pop("audio_lens", [])]
|
20 |
+
audio_token_len = [x for f in features for x in f.pop("audio_token_len", [])]
|
21 |
+
audio_token_start_idx = [
|
22 |
+
x for f in features for x in f.pop("audio_token_start_idx", [])
|
23 |
+
]
|
24 |
+
|
25 |
+
if self.include_alt_fields:
|
26 |
+
# these fields are hard-coded in the transformer data collator, so they need special handling before calling the super method
|
27 |
+
alt_features = [
|
28 |
+
{
|
29 |
+
"input_ids": f.pop("alt_input_ids"),
|
30 |
+
"attention_mask": f.pop("alt_attention_mask"),
|
31 |
+
"labels": f.pop("alt_labels"),
|
32 |
+
}
|
33 |
+
for f in features
|
34 |
+
]
|
35 |
+
|
36 |
+
batch = super().__call__(features, *args, **kwargs)
|
37 |
+
if self.include_alt_fields:
|
38 |
+
alt_batch = super().__call__(alt_features, *args, **kwargs)
|
39 |
+
batch["alt_input_ids"] = alt_batch["input_ids"]
|
40 |
+
batch["alt_attention_mask"] = alt_batch["attention_mask"]
|
41 |
+
batch["alt_labels"] = alt_batch["labels"]
|
42 |
+
|
43 |
+
if audio_values and len(audio_values[0]) > 0:
|
44 |
+
batch["audio_token_start_idx"] = torch.stack(audio_token_start_idx)
|
45 |
+
batch["audio_lens"] = torch.stack(audio_lens)
|
46 |
+
batch["audio_token_len"] = torch.stack(audio_token_len)
|
47 |
+
# Pad the last dimension of all audio_values to the same length, with 0s on the right.
|
48 |
+
max_len = max([x.shape[-1] for x in audio_values])
|
49 |
+
batch["audio_values"] = torch.stack(
|
50 |
+
[F.pad(x, (0, max_len - x.shape[-1])) for x in audio_values]
|
51 |
+
)
|
52 |
+
if self.tokenizer.padding_side == "left":
|
53 |
+
input_ids_lens = torch.LongTensor(
|
54 |
+
[f["input_ids"].shape[-1] for f in features]
|
55 |
+
)
|
56 |
+
displacement = batch["input_ids"].shape[-1] - input_ids_lens
|
57 |
+
displacement = displacement.repeat_interleave(
|
58 |
+
batch["audio_batch_size"].squeeze(-1)
|
59 |
+
)
|
60 |
+
batch["audio_token_start_idx"] += displacement.to(
|
61 |
+
batch["audio_token_start_idx"].device
|
62 |
+
)
|
63 |
+
return batch
|
64 |
+
|
65 |
+
|
66 |
+
class UltravoxProcessor(transformers.ProcessorMixin):
|
67 |
+
"""
|
68 |
+
Constructs an Ultravox processor which wraps an audio processor and a tokenizer into a single processor.
|
69 |
+
|
70 |
+
Args:
|
71 |
+
audio_processor: The audio processor for the audio encoder.
|
72 |
+
tokenizer: The tokenizer for the language model.
|
73 |
+
"""
|
74 |
+
|
75 |
+
attributes = ["audio_processor", "tokenizer"]
|
76 |
+
audio_processor_class = ("WhisperProcessor",)
|
77 |
+
tokenizer_class = (
|
78 |
+
"PreTrainedTokenizer",
|
79 |
+
"PreTrainedTokenizerFast",
|
80 |
+
)
|
81 |
+
|
82 |
+
tokenizer: transformers.PreTrainedTokenizerBase
|
83 |
+
audio_processor: transformers.ProcessorMixin
|
84 |
+
|
85 |
+
def __init__(
|
86 |
+
self,
|
87 |
+
audio_processor=None,
|
88 |
+
tokenizer=None,
|
89 |
+
audio_padding: str = "longest",
|
90 |
+
encoder_ds_factor: int = 2,
|
91 |
+
stack_factor: int = 8,
|
92 |
+
audio_placeholder: str = "<|audio|>",
|
93 |
+
# Defaults to whisper encoder context size
|
94 |
+
audio_context_size: Optional[int] = 3000,
|
95 |
+
):
|
96 |
+
"""
|
97 |
+
Args:
|
98 |
+
audio_processor: The audio processor for the audio encoder.
|
99 |
+
tokenizer: The tokenizer for the language model.
|
100 |
+
audio_padding: The padding strategy for the audio encoder.
|
101 |
+
stack_factor: The factor by which the audio encoder output is stacked in the multimodal projector.
|
102 |
+
encoder_ds_factor: The downsampling factor of the audio encoder.
|
103 |
+
audio_placeholder: The placeholder for the audio in the text.
|
104 |
+
audio_context_size: The maximum number of frames that the audio encoder can handle.
|
105 |
+
"""
|
106 |
+
self.audio_padding = audio_padding
|
107 |
+
self.encoder_ds_factor = encoder_ds_factor
|
108 |
+
self.stack_factor = stack_factor
|
109 |
+
self.audio_placeholder = audio_placeholder
|
110 |
+
self.audio_context_size = audio_context_size
|
111 |
+
assert (
|
112 |
+
tokenizer.eos_token is not None
|
113 |
+
), "The tokenizer has no EOS token. Cannot recover."
|
114 |
+
self.vocab = tokenizer.get_vocab()
|
115 |
+
# VLLM currently relies on updating audio_token_replacement, hence to be safe
|
116 |
+
# we should not update it. This dependency should be removed in the future.
|
117 |
+
self.audio_token_replacement = tokenizer.eos_token
|
118 |
+
if tokenizer.pad_token_id is None:
|
119 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
120 |
+
|
121 |
+
super().__init__(audio_processor=audio_processor, tokenizer=tokenizer)
|
122 |
+
|
123 |
+
@classmethod
|
124 |
+
def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
|
125 |
+
config: UltravoxConfig = transformers.AutoConfig.from_pretrained(
|
126 |
+
pretrained_model_name_or_path, **kwargs
|
127 |
+
)
|
128 |
+
audio_processor = transformers.AutoProcessor.from_pretrained(
|
129 |
+
config.audio_model_id
|
130 |
+
or config.audio_config._name_or_path
|
131 |
+
or "openai/whisper-tiny"
|
132 |
+
)
|
133 |
+
|
134 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
135 |
+
pretrained_model_name_or_path, **kwargs
|
136 |
+
)
|
137 |
+
tokenizer.padding_side = "left"
|
138 |
+
tokenizer.pad_token = tokenizer.eos_token
|
139 |
+
|
140 |
+
return cls(
|
141 |
+
audio_processor=audio_processor,
|
142 |
+
tokenizer=tokenizer,
|
143 |
+
stack_factor=config.stack_factor,
|
144 |
+
)
|
145 |
+
|
146 |
+
def _chunk_and_pad_audio(
|
147 |
+
self,
|
148 |
+
audio_values: torch.Tensor,
|
149 |
+
audio_lens: torch.Tensor,
|
150 |
+
include_audio_num_chunks: bool = False,
|
151 |
+
) -> Dict[str, Any]:
|
152 |
+
"""
|
153 |
+
Processes the audio batch by chunking any items in the batch according to the audio_context_size,
|
154 |
+
padding the last chunk if needed, and returns a dictionary with updated audio data.
|
155 |
+
|
156 |
+
Args:
|
157 |
+
audio_values (torch.Tensor): A tensor of audio values (e.g., in B, D, T format).
|
158 |
+
audio_lens (torch.Tensor): A tensor of audio lengths.
|
159 |
+
|
160 |
+
Returns:
|
161 |
+
Dict[str, Any]: Dictionary with the following keys:
|
162 |
+
- "audio_values": The concatenated audio tensor after chunking and padding.
|
163 |
+
- "audio_lens": Tensor of lengths for each chunk.
|
164 |
+
- "audio_is_continuation": Tensor of booleans indicating if the chunk is a continuation of the previous chunk.
|
165 |
+
- "audio_batch_size": A Tensor with one integer representing the number of chunks.
|
166 |
+
|
167 |
+
"""
|
168 |
+
chunked_audio_values: List[torch.Tensor] = []
|
169 |
+
chunked_audio_lens: List[int] = []
|
170 |
+
is_continuation_list: List[bool] = []
|
171 |
+
num_chunks: List[int] = []
|
172 |
+
context_size = self.audio_context_size or audio_values.shape[-1]
|
173 |
+
|
174 |
+
for i in range(audio_values.shape[0]): # iterate over the batch
|
175 |
+
num_chunks.append(int(np.ceil(audio_lens[i] / context_size)))
|
176 |
+
for offset in range(0, audio_lens[i], context_size):
|
177 |
+
is_continuation = offset > 0
|
178 |
+
chunk = audio_values[i, :, offset : offset + context_size]
|
179 |
+
if is_continuation and chunk.shape[-1] < context_size:
|
180 |
+
# N.B. We only need to pad continuation chunks. If none of the samples require chunking, the
|
181 |
+
# batch might not (need to) be padded all the way to the audio_context_size, in which case
|
182 |
+
# we've already included the padding above. On the other hand, if we have any continuation
|
183 |
+
# chunks we know that the batch needs to be padded to audio_context_size because that's what
|
184 |
+
# we're slicing to.
|
185 |
+
chunk = F.pad(chunk, (0, context_size - chunk.shape[-1]))
|
186 |
+
chunked_audio_values.append(chunk)
|
187 |
+
chunked_audio_lens.append(
|
188 |
+
min(int(audio_lens[i].item()) - offset, context_size)
|
189 |
+
)
|
190 |
+
is_continuation_list.append(is_continuation)
|
191 |
+
|
192 |
+
data = {
|
193 |
+
"audio_values": torch.stack(chunked_audio_values, dim=0),
|
194 |
+
"audio_lens": torch.tensor(
|
195 |
+
chunked_audio_lens, dtype=torch.int64, device=audio_values.device
|
196 |
+
),
|
197 |
+
"audio_is_continuation": torch.tensor(
|
198 |
+
is_continuation_list, dtype=torch.bool, device=audio_values.device
|
199 |
+
),
|
200 |
+
"audio_batch_size": torch.tensor(
|
201 |
+
[len(chunked_audio_values)], device=audio_values.device
|
202 |
+
),
|
203 |
+
}
|
204 |
+
if include_audio_num_chunks:
|
205 |
+
data["audio_num_chunks"] = torch.tensor(
|
206 |
+
num_chunks, dtype=torch.int64, device=audio_values.device
|
207 |
+
)
|
208 |
+
return data
|
209 |
+
|
210 |
+
def __call__(
|
211 |
+
self,
|
212 |
+
text: Optional[str] = None,
|
213 |
+
audio: Optional[Union[np.ndarray, torch.Tensor]] = None,
|
214 |
+
audios: Optional[
|
215 |
+
Union[
|
216 |
+
List[Union[np.ndarray, torch.Tensor]], Union[np.ndarray, torch.Tensor]
|
217 |
+
]
|
218 |
+
] = None,
|
219 |
+
sampling_rate: Optional[int] = None,
|
220 |
+
return_tensors: Optional[
|
221 |
+
Union[str, transformers.TensorType]
|
222 |
+
] = transformers.TensorType.PYTORCH,
|
223 |
+
include_audio_num_chunks: bool = False,
|
224 |
+
**kwargs,
|
225 |
+
) -> transformers.BatchFeature:
|
226 |
+
"""
|
227 |
+
Main method to prepare for the model one text sequence and audio. This method forwards the `text`
|
228 |
+
and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
|
229 |
+
the text. To prepare the audio(s), this method forwards the `audio`, `sampling_rate` and `kwargs` arguments to
|
230 |
+
audio processor's [`~WhisperProcessor.__call__`] if `audio` is not `None`. Please refer to the docstring
|
231 |
+
of the above two methods for more information.
|
232 |
+
|
233 |
+
Args:
|
234 |
+
text (`str`, `List[str]`):
|
235 |
+
The sequence to be encoded. Sequence can be a string or (pretokenized string).
|
236 |
+
audio (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
237 |
+
The audio to be prepared. Audio can be a single-channel (1-dimensional) NumPy array or PyTorch tensor.
|
238 |
+
audios (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
239 |
+
A list or two dimensional array of audio to be prepared.
|
240 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
241 |
+
Sampling rate of the input audio. We expect 16kHz audio. Don't change this value unless you know what
|
242 |
+
you are doing.
|
243 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
244 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
245 |
+
|
246 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
247 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
248 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
249 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
250 |
+
|
251 |
+
Returns:
|
252 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
253 |
+
|
254 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
255 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
256 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
257 |
+
`None`).
|
258 |
+
- **audio_values** -- Processed audio values to be fed to a model. Returned when `audio` is not `None`.
|
259 |
+
- **audio_token_len** -- Predicted number of audio frames: this value is guaranteed to be a close upper bound.
|
260 |
+
Returned when `audio` is not `None`.
|
261 |
+
- **audio_token_start_idx** -- The index in the tokenized text where the audio starts. Returned when `audio` is not `None`.
|
262 |
+
"""
|
263 |
+
# TODO: Add support for multiple text inputs.
|
264 |
+
if audio is not None and audios is not None:
|
265 |
+
raise ValueError("Only one of `audio` or `audios` should be provided.")
|
266 |
+
elif audio is not None:
|
267 |
+
audios = audio if isinstance(audio, list) or audio.ndim == 2 else [audio]
|
268 |
+
elif audios is None:
|
269 |
+
audios = []
|
270 |
+
|
271 |
+
data = {}
|
272 |
+
audio_is_continuation = []
|
273 |
+
if len(audios) > 0:
|
274 |
+
audios = [x.numpy() if isinstance(x, torch.Tensor) else x for x in audios]
|
275 |
+
|
276 |
+
# Pad out each audio to at least 2 hops (the minimum required by the processor).
|
277 |
+
hop_length = self.audio_processor.feature_extractor.hop_length
|
278 |
+
audios = [
|
279 |
+
(
|
280 |
+
np.pad(x, (0, 2 * hop_length - len(x)), mode="constant")
|
281 |
+
if len(x) < 2 * hop_length
|
282 |
+
else x
|
283 |
+
)
|
284 |
+
for x in audios
|
285 |
+
]
|
286 |
+
|
287 |
+
# Main audio processing. The processor is model-specific.
|
288 |
+
x: transformers.BatchFeature = self.audio_processor(
|
289 |
+
audios,
|
290 |
+
sampling_rate=sampling_rate,
|
291 |
+
padding="longest",
|
292 |
+
pad_to_multiple_of=hop_length, # The attention mask effectively gets padded to the hop length, so pad the audio to be consistent.
|
293 |
+
truncation=False,
|
294 |
+
return_attention_mask=True,
|
295 |
+
**kwargs,
|
296 |
+
)
|
297 |
+
|
298 |
+
data.update(
|
299 |
+
self._chunk_and_pad_audio(
|
300 |
+
audio_values=torch.as_tensor(
|
301 |
+
x.input_features if "input_features" in x else x.input_values
|
302 |
+
),
|
303 |
+
audio_lens=torch.as_tensor(x.attention_mask).sum(-1),
|
304 |
+
include_audio_num_chunks=include_audio_num_chunks,
|
305 |
+
)
|
306 |
+
)
|
307 |
+
|
308 |
+
audio_is_continuation = data.pop("audio_is_continuation")
|
309 |
+
data["audio_token_len"] = torch.ceil(
|
310 |
+
data["audio_lens"] / (self.encoder_ds_factor * self.stack_factor)
|
311 |
+
).to(dtype=torch.int)
|
312 |
+
|
313 |
+
if text is not None:
|
314 |
+
if not isinstance(text, str):
|
315 |
+
raise ValueError("Text must be a string. Batch mode not supported yet.")
|
316 |
+
|
317 |
+
# Special tokens like BOS should already have been added by the caller.
|
318 |
+
tokenized_parts = self.tokenizer(
|
319 |
+
text.split(
|
320 |
+
"<|audio|>" # The placeholder isn't part of the vocabulary, so split the text around it.
|
321 |
+
),
|
322 |
+
add_special_tokens=False,
|
323 |
+
**kwargs,
|
324 |
+
)
|
325 |
+
|
326 |
+
audio_token_start_idx = []
|
327 |
+
placeholder_index = -1
|
328 |
+
split_input_ids = tokenized_parts["input_ids"]
|
329 |
+
input_ids: List[int] = []
|
330 |
+
|
331 |
+
audio_replacement_token_id = getattr(self, "audio_replacement_token_id", self.tokenizer.convert_tokens_to_ids(self.audio_token_replacement))
|
332 |
+
|
333 |
+
# We don't want to fine-tune on the audio token, as we want to learn to replace
|
334 |
+
# it with the audio features. So we set the label to -100.
|
335 |
+
for i, token_len in enumerate(data.get("audio_token_len", [])):
|
336 |
+
if not audio_is_continuation[i]:
|
337 |
+
placeholder_index += 1
|
338 |
+
if placeholder_index >= len(split_input_ids):
|
339 |
+
raise ValueError(
|
340 |
+
f"Text contains too few audio placeholders. (Expected {len(audios)} placeholders)"
|
341 |
+
)
|
342 |
+
|
343 |
+
input_ids.extend(split_input_ids[placeholder_index])
|
344 |
+
|
345 |
+
audio_token_start_idx.append(len(input_ids))
|
346 |
+
|
347 |
+
input_ids.extend([audio_replacement_token_id] * token_len)
|
348 |
+
|
349 |
+
# Include any tokens after the last audio.
|
350 |
+
placeholder_index += 1
|
351 |
+
if placeholder_index != len(split_input_ids) - 1:
|
352 |
+
raise ValueError(
|
353 |
+
f"Text contains too many audio placeholders. (Expected {len(audios)} placeholders)"
|
354 |
+
)
|
355 |
+
input_ids.extend(split_input_ids[placeholder_index])
|
356 |
+
|
357 |
+
if "audio_token_len" in data:
|
358 |
+
data["audio_token_start_idx"] = torch.as_tensor(audio_token_start_idx)
|
359 |
+
|
360 |
+
data["input_ids"] = [input_ids]
|
361 |
+
data["attention_mask"] = [[1] * len(input_ids)]
|
362 |
+
|
363 |
+
# Ensure that there are no audio placeholders after the last audio.
|
364 |
+
|
365 |
+
return transformers.BatchFeature(data=data, tensor_type=return_tensors)
|
366 |
+
|
367 |
+
def batch_decode(self, *args, **kwargs):
|
368 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
369 |
+
|
370 |
+
def decode(self, *args, **kwargs):
|
371 |
+
return self.tokenizer.decode(*args, **kwargs)
|
372 |
+
|
373 |
+
@property
|
374 |
+
def model_input_names(self):
|
375 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
376 |
+
audio_processor_input_names = self.audio_processor.model_input_names
|
377 |
+
return list(set(tokenizer_input_names + audio_processor_input_names))
|
378 |
+
|
379 |
+
|
380 |
+
UltravoxProcessor.register_for_auto_class()
|
381 |
+
|
382 |
+
transformers.AutoProcessor.register(UltravoxConfig, UltravoxProcessor)
|
ultravox_tokenizer.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
|
3 |
+
import transformers
|
4 |
+
|
5 |
+
AUDIO_TOKEN = "<|audio|>"
|
6 |
+
|
7 |
+
|
8 |
+
def from_pretrained_text_tokenizer(
|
9 |
+
*args, **kwargs
|
10 |
+
) -> transformers.PreTrainedTokenizerBase:
|
11 |
+
"""
|
12 |
+
Create a tokenizer with the additional special token for audio.
|
13 |
+
This is mainly used for VLLM to work properly. This repo does not currently require it.
|
14 |
+
"""
|
15 |
+
|
16 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(*args, **kwargs)
|
17 |
+
tokenizer.add_special_tokens({"additional_special_tokens": [AUDIO_TOKEN]})
|
18 |
+
logging.info(f"Audio token id: {get_audio_token_id(tokenizer)}")
|
19 |
+
return tokenizer
|
20 |
+
|
21 |
+
|
22 |
+
def get_audio_token_id(tokenizer: transformers.PreTrainedTokenizerBase) -> int:
|
23 |
+
audio_token_id = tokenizer.encode(AUDIO_TOKEN, add_special_tokens=False)
|
24 |
+
assert len(audio_token_id) == 1, "Audio token should be a single token"
|
25 |
+
return audio_token_id[0]
|