zqhuang commited on
Commit
ad41a2f
·
verified ·
1 Parent(s): 5bf77b4

Upload UltravoxPipeline

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
added_tokens.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|audio|>": 151669,
9
+ "<|box_end|>": 151649,
10
+ "<|box_start|>": 151648,
11
+ "<|endoftext|>": 151643,
12
+ "<|file_sep|>": 151664,
13
+ "<|fim_middle|>": 151660,
14
+ "<|fim_pad|>": 151662,
15
+ "<|fim_prefix|>": 151659,
16
+ "<|fim_suffix|>": 151661,
17
+ "<|im_end|>": 151645,
18
+ "<|im_start|>": 151644,
19
+ "<|image_pad|>": 151655,
20
+ "<|object_ref_end|>": 151647,
21
+ "<|object_ref_start|>": 151646,
22
+ "<|quad_end|>": 151651,
23
+ "<|quad_start|>": 151650,
24
+ "<|repo_name|>": 151663,
25
+ "<|video_pad|>": 151656,
26
+ "<|vision_end|>": 151653,
27
+ "<|vision_pad|>": 151654,
28
+ "<|vision_start|>": 151652
29
+ }
config.json ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 151669,
51
+ "auto_map": {
52
+ "AutoConfig": "ultravox_config.UltravoxConfig",
53
+ "AutoModel": "ultravox_model.UltravoxModel"
54
+ },
55
+ "custom_pipelines": {
56
+ "ultravox-pipeline": {
57
+ "impl": "ultravox_pipeline.UltravoxPipeline",
58
+ "pt": [
59
+ "AutoModel"
60
+ ],
61
+ "tf": [],
62
+ "type": "multimodal"
63
+ }
64
+ },
65
+ "hidden_size": 4096,
66
+ "ignore_index": -100,
67
+ "initializer_range": 0.02,
68
+ "model_type": "ultravox",
69
+ "norm_init": 0.4,
70
+ "pad_token_id": 151645,
71
+ "projector_act": "swiglu",
72
+ "projector_ln_mid": true,
73
+ "stack_factor": 8,
74
+ "text_model_id": "Qwen/Qwen3-32B",
75
+ "torch_dtype": "bfloat16",
76
+ "transformers_version": "4.51.3",
77
+ "vocab_size": 151936
78
+ }
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "pad_token_id": 151645,
6
+ "transformers_version": "4.51.3"
7
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c893760e51695bb68738541636adb68c0c5df3dd8edd2894aebe40c04d51950
3
+ size 1378876648
special_tokens_map.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "eos_token": {
12
+ "content": "<|im_end|>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ },
18
+ "pad_token": {
19
+ "content": "<|im_end|>",
20
+ "lstrip": false,
21
+ "normalized": false,
22
+ "rstrip": false,
23
+ "single_word": false
24
+ }
25
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0422f49acb9b2b8861f8a8c9fc5883758d7be3e805fdc014ade10478ea8fb1c9
3
+ size 11422840
tokenizer_config.json ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ },
213
+ "151669": {
214
+ "content": "<|audio|>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": true
220
+ }
221
+ },
222
+ "additional_special_tokens": [
223
+ "<|audio|>"
224
+ ],
225
+ "auto_map": {
226
+ "AutoProcessor": "ultravox_processing.UltravoxProcessor"
227
+ },
228
+ "bos_token": null,
229
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
230
+ "clean_up_tokenization_spaces": false,
231
+ "eos_token": "<|im_end|>",
232
+ "errors": "replace",
233
+ "extra_special_tokens": {},
234
+ "model_max_length": 131072,
235
+ "pad_token": "<|im_end|>",
236
+ "processor_class": "UltravoxProcessor",
237
+ "split_special_tokens": false,
238
+ "tokenizer_class": "Qwen2Tokenizer",
239
+ "unk_token": null
240
+ }
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,983 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
24
+ FROM_PRETRAINED_KWARGS = {}
25
+ SHARED_PRETRAINED_KWARGS = [
26
+ "tp_plan",
27
+ "device_map",
28
+ "torch_dtype",
29
+ "attn_implementation",
30
+ "use_flash_attention_2",
31
+ ]
32
+
33
+ class UltravoxModel(transformers.LlamaPreTrainedModel, GenerationMixin):
34
+ """
35
+ The Ultravox model which consists of an audio encoder and a language model.
36
+
37
+ Audio input is processed by the audio encoder, then every `stack_factor` frames are stacked together and
38
+ projected to the language model's embedding space using a few linear layers.
39
+ The text is embedded by the language model as usual and then the audio and text embeddings are merged together.
40
+
41
+ A special token `<|audio|>` is used to indicate the start of the audio embeddings in the merged embeddings.
42
+
43
+ Parameters:
44
+ config: Model configuration class with all the parameters of the model.
45
+ """
46
+
47
+ config_class = UltravoxConfig
48
+ config: UltravoxConfig # for type hinting
49
+ # Usually we load encoder and LLM weights from a pretrained model separately, so they are allowed to be missing
50
+ _keys_to_ignore_on_load_missing = ["audio_tower.*", "language_model.*"]
51
+ # 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
52
+ # see https://github.com/huggingface/transformers/issues/35856 and https://github.com/huggingface/trl/pull/2615/files
53
+ accepts_loss_kwargs = False
54
+
55
+ def __init__(self, config: UltravoxConfig):
56
+ super().__init__(config)
57
+ self._register_load_state_dict_pre_hook(self._pre_load_state_dict_hook)
58
+
59
+ self.keep_params: Set[str] = set()
60
+ self.vocab_size = config.vocab_size
61
+
62
+ self.audio_tower = self._create_audio_tower(config)
63
+ self.audio_tower_context_length: Optional[int] = None
64
+ self.audio_tower_context_length = self.audio_tower.max_context_length
65
+
66
+ self.multi_modal_projector = self._create_multi_modal_projector(config)
67
+ self.language_model = self._create_language_model(config)
68
+
69
+ if self.language_model._tied_weights_keys is not None:
70
+ self._tied_weights_keys = [
71
+ f"language_model.{k}" for k in self.language_model._tied_weights_keys
72
+ ]
73
+
74
+ # Determine no_split_modules dynamically to use with FSDP auto_wrap policy.
75
+ # FSDP throws an error if some of the layer types are not found in the model.
76
+ # This would be something like ["LlamaDecoderLayer"] as we don't split audio encoder layers.
77
+ # Filter out modules that don't exist in this model to avoid FSDP errors.
78
+ language_model_modules = self.language_model._no_split_modules or []
79
+ existing_modules = []
80
+ for module_name in language_model_modules:
81
+ # Check if any module in the model has this class name
82
+ module_exists = any(
83
+ module.__class__.__name__ == module_name
84
+ for module in self.modules()
85
+ )
86
+ if module_exists:
87
+ existing_modules.append(module_name)
88
+ self._no_split_modules = existing_modules
89
+
90
+ self.loss_config = LossConfig()
91
+ self.post_init()
92
+
93
+ def _init_weights(self, module):
94
+ if module is self:
95
+ if self.config.text_model_id is not None:
96
+ self.language_model = self._create_language_model(self.config)
97
+ if self.config.audio_model_id is not None:
98
+ self.audio_tower = self._create_audio_tower(self.config)
99
+ elif module in self.language_model.modules():
100
+ pass
101
+ elif module in self.audio_tower.modules():
102
+ pass
103
+ else:
104
+ super()._init_weights(module)
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, *args, **kwargs):
108
+ global FROM_PRETRAINED_KWARGS
109
+ FROM_PRETRAINED_KWARGS = {
110
+ k: v for k, v in kwargs.items() if k in SHARED_PRETRAINED_KWARGS
111
+ }
112
+ model = super().from_pretrained(*args, **kwargs)
113
+ FROM_PRETRAINED_KWARGS = {}
114
+ return model
115
+
116
+ def get_input_embeddings(self):
117
+ return self.language_model.get_input_embeddings()
118
+
119
+ def set_input_embeddings(self, value):
120
+ self.language_model.set_input_embeddings(value)
121
+
122
+ def get_output_embeddings(self):
123
+ return self.language_model.get_output_embeddings()
124
+
125
+ def set_output_embeddings(self, new_embeddings):
126
+ self.language_model.set_output_embeddings(new_embeddings)
127
+
128
+ def set_decoder(self, decoder):
129
+ self.language_model.set_decoder(decoder)
130
+
131
+ def get_decoder(self):
132
+ return self.language_model.get_decoder()
133
+
134
+ def tie_weights(self):
135
+ return self.language_model.tie_weights()
136
+
137
+ def set_loss_config(self, loss_config: LossConfig):
138
+ self.loss_config = loss_config
139
+
140
+ def _setup_cache(
141
+ self, cache_cls, max_batch_size: int, max_cache_len: Optional[int] = None
142
+ ):
143
+ self.language_model._setup_cache(cache_cls, max_batch_size, max_cache_len)
144
+
145
+ def _reorder_cache(self, past_key_values, beam_idx):
146
+ return self.language_model._reorder_cache(past_key_values, beam_idx)
147
+
148
+ def resize_token_embeddings(
149
+ self,
150
+ new_num_tokens: Optional[int] = None,
151
+ pad_to_multiple_of: Optional[int] = None,
152
+ ) -> nn.Embedding:
153
+ model_embeds = self.language_model.resize_token_embeddings(
154
+ new_num_tokens, pad_to_multiple_of
155
+ )
156
+ # update vocab size
157
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
158
+ self.config.vocab_size = model_embeds.num_embeddings
159
+ self.vocab_size = model_embeds.num_embeddings
160
+ return model_embeds
161
+
162
+ def _get_prediction_mask(
163
+ self, labels: Optional[torch.Tensor]
164
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
165
+ """Get boolean masks for positions where we want to compute KL divergence.
166
+
167
+ For each label position, we want the position before it since that's where
168
+ the model makes the prediction for that label.
169
+
170
+ Additionally, we want to identify the position right before the EOT token
171
+ (the last token with label != -100).
172
+
173
+ Args:
174
+ labels: Tensor of shape (B, T) where B is batch size and T is sequence length,
175
+ with -100 for masked positions and token ids for label positions
176
+
177
+ Returns:
178
+ Tuple containing:
179
+ - pred_mask: Boolean tensor of shape (B, T) that's True for positions where we want to compute KL divergence
180
+ - eot_mask: Boolean tensor of shape (B, T) that's True only for the last prediction position in each sequence
181
+ """
182
+ if labels is None:
183
+ raise ValueError("labels must be provided")
184
+
185
+ # Shift the label mask right by 1 along the sequence dimension
186
+ # This gives us positions where we make predictions for the next token
187
+ label_mask = labels != -100
188
+ pred_mask = torch.zeros_like(label_mask)
189
+ pred_mask[:, :-1] = label_mask[
190
+ :, 1:
191
+ ] # shift right by 1 along sequence dimension
192
+
193
+ # Create EOT mask - identify only the last prediction position in each sequence
194
+ eot_mask = torch.zeros_like(pred_mask)
195
+ batch_size = labels.shape[0]
196
+
197
+ for i in range(batch_size):
198
+ # Find positions where we make predictions
199
+ pred_positions = torch.where(pred_mask[i])[0]
200
+ if len(pred_positions) > 0:
201
+ # Only mark the last prediction position
202
+ eot_mask[i, pred_positions[-1]] = True
203
+
204
+ return pred_mask, eot_mask
205
+
206
+ def _compute_kl_loss(
207
+ self,
208
+ lm_output: transformers.modeling_outputs.CausalLMOutputWithPast,
209
+ labels: Optional[torch.Tensor] = None,
210
+ past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
211
+ alt_input_ids: Optional[torch.Tensor] = None,
212
+ alt_attention_mask: Optional[torch.Tensor] = None,
213
+ alt_labels: Optional[torch.Tensor] = None,
214
+ **kwargs,
215
+ ):
216
+ # disable gradient computation for the teacher model
217
+ with torch.no_grad():
218
+ # compute the teacher (text-only) model's distribution
219
+ alt_inputs_embeds = self.get_input_embeddings().forward(alt_input_ids)
220
+ alt_lm_output = self.language_model.forward(
221
+ inputs_embeds=alt_inputs_embeds,
222
+ labels=alt_labels,
223
+ attention_mask=alt_attention_mask,
224
+ past_key_values=past_key_values,
225
+ **kwargs,
226
+ )
227
+
228
+ # Get prediction masks for regular tokens and EOT tokens
229
+ pred_mask, eot_mask = self._get_prediction_mask(labels)
230
+ alt_pred_mask, alt_eot_mask = self._get_prediction_mask(alt_labels)
231
+
232
+ # compute the KL divergence loss between the two models for regular tokens
233
+ kl_loss = F.kl_div(
234
+ F.log_softmax(
235
+ lm_output.logits[pred_mask] / self.loss_config.kl_temperature,
236
+ dim=-1,
237
+ ),
238
+ F.softmax(
239
+ alt_lm_output.logits[alt_pred_mask] / self.loss_config.kl_temperature,
240
+ dim=-1,
241
+ ),
242
+ reduction="batchmean",
243
+ )
244
+
245
+ # Compute the KL divergence loss for EOT token positions if any exist
246
+ if self.loss_config.eot_loss_weight > 0:
247
+ eot_loss = F.kl_div(
248
+ F.log_softmax(
249
+ lm_output.logits[eot_mask] / self.loss_config.kl_temperature,
250
+ dim=-1,
251
+ ),
252
+ F.softmax(
253
+ alt_lm_output.logits[alt_eot_mask]
254
+ / self.loss_config.kl_temperature,
255
+ dim=-1,
256
+ ),
257
+ reduction="batchmean",
258
+ )
259
+ kl_loss += self.loss_config.eot_loss_weight * eot_loss
260
+
261
+ return kl_loss
262
+
263
+ def _audio_iter(
264
+ self, audio_batch_size: torch.Tensor
265
+ ) -> Generator[Tuple[int, int], None, None]:
266
+ """
267
+ Iterate over the audio batch size and yield the batch index and audio index of each audio item.
268
+
269
+ Args:
270
+ audio_batch_size: A tensor of shape (B,) where B is the batch size.
271
+
272
+ Returns:
273
+ A generator that yields a tuple of (start index, length) for each audio item.
274
+ """
275
+ audio_index = 0
276
+ for i_b, batch_count in enumerate(audio_batch_size):
277
+ for _ in range(batch_count):
278
+ yield i_b, audio_index
279
+ audio_index += 1
280
+
281
+ def forward(
282
+ self,
283
+ input_ids: torch.Tensor,
284
+ audio_values: Optional[torch.FloatTensor] = None,
285
+ inputs_embeds: Optional[torch.FloatTensor] = None,
286
+ labels: Optional[torch.Tensor] = None,
287
+ attention_mask: Optional[torch.Tensor] = None,
288
+ audio_token_start_idx: Optional[torch.Tensor] = None,
289
+ audio_lens: Optional[torch.Tensor] = None,
290
+ audio_token_len: Optional[torch.Tensor] = None,
291
+ audio_batch_size: Optional[torch.Tensor] = None,
292
+ past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
293
+ # the alt_* fields are needed for KL divergence loss
294
+ alt_input_ids: Optional[torch.Tensor] = None,
295
+ alt_attention_mask: Optional[torch.Tensor] = None,
296
+ alt_labels: Optional[torch.Tensor] = None,
297
+ **kwargs,
298
+ ) -> transformers.modeling_outputs.CausalLMOutputWithPast:
299
+ """
300
+ Forward pass for the Ultravox model.
301
+
302
+ `input_ids` are the tokenized text input. They are embedded by the language model as usual.
303
+ `audio_values` are processed by the audio encoder and then every `stack_factor` frames are stacked together and
304
+ projected to the language model's embedding space using a few linear layers.
305
+ The audio and text embeddings are merged together. A special token `<|audio|>` is used to indicate the start
306
+ of the audio embeddings in the merged embeddings.
307
+
308
+ Args:
309
+ input_ids: The tokenized text input.
310
+ audio_values: The processed audio values.
311
+ inputs_embeds: The embeddings for the input tokens.
312
+ labels: The tokenized text labels.
313
+ attention_mask: The attention mask for the input.
314
+ position_ids: The position ids for the input.
315
+ past_key_values: The past key value cache for the language model attention layers.
316
+ **kwargs: Additional keyword arguments. Passed directly to the language model.
317
+ """
318
+ if inputs_embeds is None:
319
+ # B x T -> B x T x D
320
+ inputs_embeds = self.get_input_embeddings().forward(input_ids)
321
+
322
+ if audio_values is not None and len(audio_values) > 0:
323
+ inputs_embeds = self._prepare_audio_embeds(
324
+ inputs_embeds=inputs_embeds,
325
+ audio_values=audio_values,
326
+ audio_token_start_idx=audio_token_start_idx,
327
+ audio_lens=audio_lens,
328
+ audio_token_len=audio_token_len,
329
+ audio_batch_size=audio_batch_size,
330
+ )
331
+
332
+ lm_output = self.language_model.forward(
333
+ inputs_embeds=inputs_embeds,
334
+ labels=labels,
335
+ attention_mask=attention_mask,
336
+ past_key_values=past_key_values,
337
+ **kwargs,
338
+ )
339
+ if self.training:
340
+ if self.loss_config.loss_function == LossFunction.CrossEntropy:
341
+ pass
342
+ elif self.loss_config.loss_function == LossFunction.KL_Divergence:
343
+ lm_output.loss = self._compute_kl_loss(
344
+ lm_output=lm_output,
345
+ labels=labels,
346
+ past_key_values=past_key_values,
347
+ alt_input_ids=alt_input_ids,
348
+ alt_attention_mask=alt_attention_mask,
349
+ alt_labels=alt_labels,
350
+ **kwargs,
351
+ )
352
+ else:
353
+ raise ValueError(
354
+ f"Unsupported loss function: {self.loss_config.loss_function}"
355
+ )
356
+ return lm_output
357
+
358
+ def _prepare_audio_embeds(self,
359
+ inputs_embeds: torch.FloatTensor,
360
+ audio_values: torch.FloatTensor,
361
+ audio_token_start_idx: Optional[torch.Tensor] = None,
362
+ audio_lens: Optional[torch.Tensor] = None,
363
+ audio_token_len: Optional[torch.Tensor] = None,
364
+ audio_batch_size: Optional[torch.Tensor] = None,
365
+ ) -> torch.Tensor:
366
+ assert (
367
+ audio_token_start_idx is not None
368
+ and audio_token_len is not None
369
+ and audio_lens is not None
370
+ and audio_batch_size is not None
371
+ ), "audio_token_start_idx/audio_token_len/audio_lens must be provided if audio_values are provided."
372
+ assert (
373
+ len(audio_token_start_idx)
374
+ == len(audio_token_len)
375
+ == len(audio_lens)
376
+ == len(audio_values)
377
+ ), "audio_token_start_idx/audio_token_len/audio_lens/audio_values must have the same batch size."
378
+ assert len(audio_batch_size) == len(
379
+ inputs_embeds
380
+ ), "audio_batch_size and inputs_embeds must have the same batch size."
381
+
382
+ # B x A/3200 x (D=max-audio-length-in-batch)
383
+ audio_tower_output = self.audio_tower.forward(
384
+ audio_values.to(self.audio_tower.dtype),
385
+ audio_len=audio_lens,
386
+ ).last_hidden_state
387
+ audio_tower_output = audio_tower_output.to(inputs_embeds.dtype)
388
+ audio_embeds = self.multi_modal_projector.forward(audio_tower_output)
389
+
390
+ # combine audio and text embeddings
391
+ for i_b, i_a in self._audio_iter(audio_batch_size):
392
+ start_idx = audio_token_start_idx[i_a]
393
+ token_len = audio_token_len[i_a]
394
+ item_embedding = audio_embeds[i_a][:token_len]
395
+ inputs_embeds[i_b][start_idx : start_idx + token_len] = item_embedding
396
+
397
+ return inputs_embeds
398
+
399
+ def generate(self,
400
+ input_ids: torch.Tensor,
401
+ audio_values: Optional[torch.FloatTensor] = None,
402
+ inputs_embeds: Optional[torch.FloatTensor] = None,
403
+ audio_token_start_idx: Optional[torch.Tensor] = None,
404
+ audio_lens: Optional[torch.Tensor] = None,
405
+ audio_token_len: Optional[torch.Tensor] = None,
406
+ audio_batch_size: Optional[torch.Tensor] = None,
407
+ **kwargs,
408
+ ) -> torch.Tensor:
409
+ if inputs_embeds is None:
410
+ inputs_embeds = self.get_input_embeddings().forward(input_ids)
411
+
412
+ if audio_values is not None and len(audio_values) > 0:
413
+ inputs_embeds = self._prepare_audio_embeds(
414
+ inputs_embeds=inputs_embeds,
415
+ audio_values=audio_values,
416
+ audio_token_start_idx=audio_token_start_idx,
417
+ audio_lens=audio_lens,
418
+ audio_token_len=audio_token_len,
419
+ audio_batch_size=audio_batch_size,
420
+ )
421
+
422
+ return self.language_model.generate(
423
+ input_ids=input_ids,
424
+ inputs_embeds=inputs_embeds,
425
+ **kwargs,
426
+ )
427
+
428
+ @classmethod
429
+ def _create_multi_modal_projector(
430
+ cls, config: UltravoxConfig
431
+ ) -> "UltravoxProjector":
432
+ projector = UltravoxProjector(config)
433
+ dtype = config.torch_dtype
434
+ if isinstance(dtype, str):
435
+ dtype = getattr(torch, dtype)
436
+ projector.to(dtype)
437
+ return projector
438
+
439
+ @classmethod
440
+ def _create_audio_tower(
441
+ cls, config: UltravoxConfig
442
+ ) -> Union[transformers.Wav2Vec2Model, "ModifiedWhisperEncoder"]:
443
+ # We probably don't want to pass tp_plan or device_map to the audio tower
444
+ # But potentially other kwargs can be passed in. TODO
445
+ kwargs = {"torch_dtype": config.torch_dtype}
446
+ if (
447
+ transformers.modeling_utils._init_weights
448
+ and config.audio_model_id is not None
449
+ ):
450
+ if "whisper" in config.audio_model_id.lower():
451
+ audio_tower = ModifiedWhisperEncoder.from_pretrained(
452
+ config.audio_model_id, **kwargs
453
+ )
454
+ audio_tower.init_latency_mask(
455
+ config.audio_latency_block_size, dtype=config.torch_dtype
456
+ )
457
+ else:
458
+ assert config.audio_latency_block_size in (
459
+ None,
460
+ 0,
461
+ ), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
462
+ audio_tower = transformers.AutoModel.from_pretrained(
463
+ config.audio_model_id, **kwargs
464
+ )
465
+ else:
466
+ with accelerate.init_empty_weights():
467
+ if "whisper" in config.audio_config._name_or_path.lower():
468
+ audio_tower = ModifiedWhisperEncoder(config.audio_config)
469
+ audio_tower.init_latency_mask(
470
+ config.audio_latency_block_size,
471
+ dtype=config.torch_dtype,
472
+ )
473
+ else:
474
+ assert config.audio_latency_block_size in (
475
+ None,
476
+ 0,
477
+ ), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
478
+ # we only ever use from_config if the weights are retrained, hence initializing is not
479
+ # required. This makes the model quite creation faster since init on CPU is quite slow.
480
+ audio_tower = transformers.AutoModel.from_config(
481
+ config.audio_config, **kwargs
482
+ )
483
+
484
+ if isinstance(
485
+ audio_tower,
486
+ (transformers.Wav2Vec2BertModel, transformers.WhisperModel),
487
+ ):
488
+ # For these models we only need the encoder part
489
+ # Wav2Vec2BertModel -> Wav2Vec2BertEncoder
490
+ # WhisperModel -> WhisperEncoder
491
+ audio_tower = audio_tower.encoder
492
+
493
+ audio_tower = apply_lora(audio_tower, config.audio_model_lora_config)
494
+ return audio_tower
495
+
496
+ @classmethod
497
+ def _create_language_model(
498
+ cls, config: UltravoxConfig
499
+ ) -> transformers.LlamaForCausalLM:
500
+ if (
501
+ transformers.modeling_utils._init_weights
502
+ and config.text_model_id is not None
503
+ ):
504
+ language_model = transformers.AutoModelForCausalLM.from_pretrained(
505
+ config.text_model_id,
506
+ **{
507
+ "attn_implementation": config.text_config._attn_implementation,
508
+ "torch_dtype": config.torch_dtype,
509
+ **FROM_PRETRAINED_KWARGS,
510
+ },
511
+ )
512
+ else:
513
+ with accelerate.init_empty_weights():
514
+ # we only ever use from_config if the weights are retrained, hence initializing is not
515
+ # required. This makes the model quite creation faster since init on CPU is quite slow.
516
+ language_model = transformers.AutoModelForCausalLM.from_config(
517
+ config.text_config,
518
+ attn_implementation=config.text_config._attn_implementation,
519
+ torch_dtype=config.torch_dtype,
520
+ )
521
+
522
+ language_model = apply_lora(language_model, config.text_model_lora_config)
523
+ return language_model
524
+
525
+ def merge_and_unload(self):
526
+ if isinstance(self.language_model, peft.PeftModel):
527
+ self.language_model = self.language_model.merge_and_unload()
528
+ # no need to download base language model weights anymore, so we can remove the id
529
+ self.config.text_model_id = None
530
+ self.keep_params.update(
531
+ set(
532
+ [
533
+ f"language_model.{name}"
534
+ for name, _ in self.language_model.named_parameters()
535
+ ]
536
+ )
537
+ )
538
+
539
+ if isinstance(self.audio_tower, peft.PeftModel):
540
+ self.audio_tower = self.audio_tower.merge_and_unload()
541
+ # no need to download base audio model weights anymore, so we can remove the id
542
+ self.config.audio_model_id = None
543
+ self.keep_params.update(
544
+ set(
545
+ [
546
+ f"audio_tower.{name}"
547
+ for name, _ in self.audio_tower.named_parameters()
548
+ ]
549
+ )
550
+ )
551
+
552
+ for param in ["text_model_lora_config", "audio_model_lora_config"]:
553
+ if hasattr(self.config, param):
554
+ delattr(self.config, param)
555
+
556
+ def push_to_hub(self, *args, **kwargs):
557
+ self.merge_and_unload()
558
+ return super().push_to_hub(*args, **kwargs)
559
+
560
+ def diff_state_dict(
561
+ self, state_dict: Optional[Dict[str, Any]] = None
562
+ ) -> Dict[str, Any]:
563
+ if state_dict is None:
564
+ state_dict = super().state_dict()
565
+
566
+ trainable_params = {k for k, v in self.named_parameters() if v.requires_grad}
567
+ # normalize the keys to match the original model
568
+ # Example: audio_tower.base_model.model.layers.0._fsdp_wrapped_module.self_attn.k_proj.lora_B.default.weight
569
+ trainable_params = {
570
+ k.replace("_fsdp_wrapped_module.", "") for k in trainable_params
571
+ }
572
+
573
+ state_dict = {
574
+ k: v
575
+ for k, v in state_dict.items()
576
+ if k in self.keep_params or k in trainable_params
577
+ }
578
+
579
+ return state_dict
580
+
581
+ def save_pretrained(
582
+ self, *args, state_dict: Optional[Dict[str, Any]] = None, **kwargs
583
+ ):
584
+ state_dict = self.diff_state_dict(state_dict)
585
+
586
+ super().save_pretrained(*args, state_dict=state_dict, **kwargs)
587
+
588
+ def _pre_load_state_dict_hook(self, state_dict: Dict[str, Any], *args, **kwargs):
589
+ self.keep_params.update(set(state_dict.keys()))
590
+
591
+ def print_trainable_parameters(self):
592
+ """
593
+ Prints the number of trainable parameters in the model (reuses Peft model's method)
594
+ """
595
+ count_params = peft.peft_model.PeftModel.get_nb_trainable_parameters
596
+
597
+ trainable_params, all_param = count_params(self)
598
+
599
+ logging.info(
600
+ f"trainable params: {trainable_params:,d} || all params: {all_param:,d}"
601
+ f" || trainable%: {100 * trainable_params / all_param:.1f}%"
602
+ )
603
+
604
+ lm_trainable_params, lm_all_params = count_params(self.language_model)
605
+ audio_trainable_params, audio_all_params = count_params(self.audio_tower)
606
+
607
+ projector_trainable_params = (
608
+ trainable_params - lm_trainable_params - audio_trainable_params
609
+ )
610
+ projector_all_params = all_param - lm_all_params - audio_all_params
611
+
612
+ logging.info(
613
+ f"Trainable%: "
614
+ f" LLM: {100 * lm_trainable_params / lm_all_params:.1f}%"
615
+ f" || Audio Encoder: {100 * audio_trainable_params / audio_all_params:.1f}%"
616
+ f" || Projector: {100 * projector_trainable_params / projector_all_params:.1f}%"
617
+ )
618
+
619
+
620
+ def get_checkpoint_files(
621
+ model_id: str,
622
+ ) -> tuple[list[str], dict | None, list[str]]:
623
+ resolved_archive_file = transformers.utils.cached_file(
624
+ model_id,
625
+ transformers.utils.SAFE_WEIGHTS_NAME,
626
+ _raise_exceptions_for_missing_entries=False,
627
+ )
628
+
629
+ if resolved_archive_file is not None:
630
+ # not sharded
631
+ sharded_metadata = None
632
+ state_dict = transformers.modeling_utils.load_state_dict(resolved_archive_file)
633
+ loaded_state_dict_keys = list(state_dict.keys())
634
+ else:
635
+ # sharded
636
+ resolved_archive_file = transformers.utils.cached_file(
637
+ model_id, transformers.utils.SAFE_WEIGHTS_INDEX_NAME
638
+ )
639
+ resolved_archive_file, sharded_metadata = (
640
+ transformers.modeling_utils.get_checkpoint_shard_files(
641
+ model_id,
642
+ resolved_archive_file,
643
+ )
644
+ )
645
+ loaded_state_dict_keys = sharded_metadata["all_checkpoint_keys"]
646
+
647
+ if isinstance(resolved_archive_file, str):
648
+ resolved_archive_file = [resolved_archive_file]
649
+
650
+ return resolved_archive_file, sharded_metadata, loaded_state_dict_keys
651
+
652
+
653
+ # TODO: refactor common parts to a shared module
654
+ def is_cache_empty(
655
+ past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]],
656
+ ) -> bool:
657
+ """
658
+ Check if the cache is empty.
659
+ """
660
+ if past_key_values is None:
661
+ return True
662
+ if isinstance(past_key_values, tuple):
663
+ return all(len(c) == 0 for c in past_key_values)
664
+ return past_key_values.get_seq_length() == 0
665
+
666
+
667
+ T = TypeVar("T", bound=torch.nn.Module)
668
+
669
+
670
+ def apply_lora(model: T, lora_config: dict) -> T:
671
+ """
672
+ Applies LoRA finetuning to the model. If the `r` parameter is set to 0, the model is frozen instead.
673
+ """
674
+ unfreeze_layers = lora_config.pop("unfreeze_layers", None)
675
+ lora_config = peft.LoraConfig(**lora_config or {})
676
+
677
+ if lora_config.r == 0:
678
+ # freeze the model entirely, except for the specified layers
679
+ for name, param in model.named_parameters():
680
+ if not unfreeze_layers or not any(
681
+ re.match(layer, name) for layer in unfreeze_layers
682
+ ):
683
+ param.requires_grad = False
684
+ else:
685
+ logging.info(f"Unfreezing layer: {name} with #{param.numel()} params")
686
+ else:
687
+ model = peft.get_peft_model(model, lora_config)
688
+
689
+ return model
690
+
691
+
692
+ class StackAudioFrames(nn.Module):
693
+ """
694
+ Stack the audio embedding frames to reduce the sequence length by a factor
695
+ of `stack_factor`.
696
+ """
697
+
698
+ def __init__(self, stack_factor: int = 8):
699
+ super().__init__()
700
+ self.stack_factor = stack_factor
701
+
702
+ def forward(self, audio_embeds: torch.Tensor) -> torch.Tensor:
703
+ B, T, C = audio_embeds.shape
704
+ T_pad = (T + self.stack_factor - 1) // self.stack_factor * self.stack_factor
705
+ audio_embeds = F.pad(audio_embeds, (0, 0, 0, T_pad - T))
706
+ B, T, C = audio_embeds.shape
707
+ audio_embeds = audio_embeds.view(
708
+ B, T // self.stack_factor, C * self.stack_factor
709
+ )
710
+ return audio_embeds
711
+
712
+
713
+ class RMSNorm(transformers.models.llama.modeling_llama.LlamaRMSNorm):
714
+ def __init__(self, hidden_size: int, init: float = 1, eps: float = 1e-6):
715
+ super().__init__(hidden_size=hidden_size, eps=eps)
716
+ self.weight.data.fill_(init)
717
+
718
+
719
+ class SwiGLU(nn.Module):
720
+ def forward(self, x):
721
+ x, gate = x.chunk(2, dim=-1)
722
+ return F.silu(gate) * x
723
+
724
+
725
+ class UltravoxProjector(nn.Module):
726
+ def __init__(self, config: UltravoxConfig):
727
+ super().__init__()
728
+ self.hidden_dim = config.hidden_size
729
+ self._pad_and_stack = StackAudioFrames(config.stack_factor)
730
+ dim_in = config.audio_config.hidden_size * config.stack_factor
731
+ self.ln_pre = RMSNorm(dim_in, init=config.norm_init)
732
+ self.linear_1 = nn.Linear(dim_in, self.hidden_dim, bias=False)
733
+ dim_mid = self.hidden_dim
734
+ self.act = transformers.activations.get_activation(config.projector_act)
735
+ dim_mid = dim_mid // 2 if config.projector_act == "swiglu" else dim_mid
736
+ dim_out = config.text_config.hidden_size
737
+ self.linear_2 = nn.Linear(dim_mid, dim_out, bias=False)
738
+
739
+ # Ultravox v0.4.1 and below uses layer_norm after the second linear layer,
740
+ # while v0.5.0 and above uses layer_norm after the first linear layer.
741
+ if config.projector_ln_mid:
742
+ self.ln_mid: nn.Module = RMSNorm(dim_mid, init=config.norm_init)
743
+ self.ln_post: nn.Module = nn.Identity()
744
+ else:
745
+ self.ln_mid = nn.Identity()
746
+ self.ln_post = RMSNorm(dim_out, init=config.norm_init)
747
+
748
+ def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
749
+ """
750
+ Takes in audio features from the audio tower and projects them to the text model's embedding space.
751
+ It reduces the number of frames by a factor of `stack_factor` and increases the number of channels by the same factor.
752
+ If the number of audio frames are not a multiple of the stack factor, the last few frames will be padded with zeros.
753
+
754
+ Input shape:
755
+ audio_features: B, T*S, C
756
+ Output shape:
757
+ hidden_states: B, T, D
758
+ Where:
759
+ B: batch size
760
+ F: number of frames in the audio tower
761
+ T: number of output embeddings
762
+ T = ceil(F / S)
763
+ S: stack factor
764
+ C: number of channels out of the encoder (aka audio tower)
765
+ H: hidden size of the projector (config.hidden_size)
766
+ D: dimension of the text model (config.text_config.hidden_size)
767
+
768
+ """
769
+ # B, F, C -> B, T, C*S
770
+ audio_features = self._pad_and_stack(audio_features)
771
+ audio_features = self.ln_pre(audio_features)
772
+ # B, T, C*S -> B, T, H
773
+ hidden_states = self.linear_1(audio_features)
774
+ # B, T, H -> B, T, H/2 (assuming swiglu)
775
+ hidden_states = self.act(hidden_states)
776
+ hidden_states = self.ln_mid(hidden_states)
777
+ # B, T, H/2 -> B, T, D
778
+ hidden_states = self.linear_2(hidden_states)
779
+ hidden_states = self.ln_post(hidden_states)
780
+ return hidden_states
781
+
782
+
783
+ class ModifiedWhisperEncoder(
784
+ whisper.WhisperEncoder, transformers.modeling_utils.ModuleUtilsMixin
785
+ ):
786
+ """
787
+ Encoder portion of OpenAI's Whisper model.
788
+
789
+ This implementation is a slightly modified version of HF Transformers' Whisper Encoder, with only a few fixes:
790
+ 1. base_model_prefix updated to allow for doing `.from_pretrained` directly on the encoder
791
+ 2. allow less than 30 second of audio padding to be passed in:
792
+ - relaxed ValueError check for `input_features` length to be less than or equal to `expected_seq_length` instead of strictly equal
793
+ - embed_pos is now sliced to match the length of `inputs_embeds`
794
+
795
+ Original: https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py
796
+ """
797
+
798
+ base_model_prefix = "model.encoder"
799
+ _no_split_modules = ["WhisperEncoderLayer"]
800
+ _keys_to_ignore_on_load_unexpected = ["model.decoder.*"]
801
+
802
+ def __init__(self, config: transformers.WhisperConfig):
803
+ super().__init__(config)
804
+ self.config.is_decoder = False
805
+
806
+ @property
807
+ def max_context_length(self):
808
+ return (
809
+ self.config.max_source_positions
810
+ * self.conv1.stride[0]
811
+ * self.conv2.stride[0]
812
+ )
813
+
814
+ def init_latency_mask(
815
+ self, audio_latency_block_size: int | None, dtype: torch.dtype
816
+ ):
817
+ if audio_latency_block_size is None:
818
+ self.audio_streaming_mask = None
819
+ return
820
+
821
+ # Use max_context_length directly in the calculation
822
+ max_seqlen = self.max_context_length
823
+ assert (
824
+ max_seqlen > 0
825
+ ), f"maximum sequence length must be positive, got {max_seqlen}"
826
+ assert (
827
+ max_seqlen % audio_latency_block_size == 0
828
+ ), f"audio_latency_block_size {audio_latency_block_size} must divide {max_seqlen} evenly."
829
+ # Given the block size, we calculate number of blocks.
830
+ audio_latency_nblocks = max_seqlen // audio_latency_block_size
831
+ audio_streaming_mask = (
832
+ torch.tril(
833
+ torch.ones(audio_latency_nblocks, audio_latency_nblocks),
834
+ diagonal=0,
835
+ )
836
+ .repeat_interleave(audio_latency_block_size, dim=0)
837
+ .repeat_interleave(audio_latency_block_size, dim=1)
838
+ )
839
+ audio_streaming_mask = (1.0 - audio_streaming_mask) * torch.finfo(dtype).min
840
+ audio_streaming_mask = audio_streaming_mask[None, None, :, :]
841
+ self.register_buffer(
842
+ "audio_streaming_mask", audio_streaming_mask, persistent=False
843
+ )
844
+
845
+ def forward(
846
+ self,
847
+ input_features,
848
+ audio_len=None,
849
+ head_mask=None,
850
+ output_attentions=None,
851
+ output_hidden_states=None,
852
+ return_dict=None,
853
+ ):
854
+ expected_seq_length = self.max_context_length
855
+ if input_features.shape[-1] > expected_seq_length:
856
+ raise ValueError(
857
+ 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}."
858
+ )
859
+
860
+ output_attentions = (
861
+ output_attentions
862
+ if output_attentions is not None
863
+ else self.config.output_attentions
864
+ )
865
+ output_hidden_states = (
866
+ output_hidden_states
867
+ if output_hidden_states is not None
868
+ else self.config.output_hidden_states
869
+ )
870
+ return_dict = (
871
+ return_dict if return_dict is not None else self.config.use_return_dict
872
+ )
873
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
874
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
875
+
876
+ inputs_embeds = inputs_embeds.permute(0, 2, 1)
877
+ embed_pos = self.embed_positions.weight[: inputs_embeds.size(-2)]
878
+
879
+ hidden_states = inputs_embeds + embed_pos
880
+ hidden_states = nn.functional.dropout(
881
+ hidden_states, p=self.dropout, training=self.training
882
+ )
883
+
884
+ encoder_states = () if output_hidden_states else None
885
+ all_attentions = () if output_attentions else None
886
+
887
+ # Create attention mask based on audio lengths to mask out padding tokens
888
+ # For each sample in batch:
889
+ # - Convert raw audio length to feature length after convolutions
890
+ # - Create boolean mask that is True for valid positions and False for padding
891
+ # - Convert to extended attention mask format expected by transformer layers
892
+ # (1.0 for positions to attend to, large negative for positions to ignore)
893
+ # This masking ensures consistent behavior between training and inference
894
+ # by preventing the model from attending to padding tokens in both cases
895
+ attention_mask = None
896
+ if audio_len is not None:
897
+ audio_feature_len = self._get_feat_extract_output_lengths(audio_len)
898
+ max_seq_len = hidden_states.shape[1]
899
+ attention_mask = torch.arange(max_seq_len, device=hidden_states.device)[
900
+ None, :
901
+ ].lt(audio_feature_len.view(-1, 1))
902
+ attention_mask = self.get_extended_attention_mask(
903
+ attention_mask,
904
+ None,
905
+ dtype=hidden_states.dtype,
906
+ )
907
+
908
+ if self.audio_streaming_mask is not None:
909
+ seqlen = hidden_states.size(-2)
910
+ if attention_mask is not None:
911
+ attention_mask = torch.minimum(
912
+ self.audio_streaming_mask[:, :, :seqlen, :seqlen], attention_mask
913
+ ) # merge
914
+ else:
915
+ attention_mask = self.audio_streaming_mask[:, :, :seqlen, :seqlen]
916
+ attention_mask = attention_mask.to(hidden_states.dtype)
917
+
918
+ # check if head_mask has a correct number of layers specified if desired
919
+ if head_mask is not None:
920
+ assert head_mask.size()[0] == (
921
+ len(self.layers)
922
+ ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
923
+
924
+ for idx, encoder_layer in enumerate(self.layers):
925
+ if output_hidden_states:
926
+ encoder_states = encoder_states + (hidden_states,)
927
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
928
+ to_drop = False
929
+ if self.training:
930
+ dropout_probability = torch.rand([])
931
+ if dropout_probability < self.layerdrop: # skip the layer
932
+ to_drop = True
933
+
934
+ if to_drop:
935
+ layer_outputs = (None, None)
936
+ else:
937
+ if self.gradient_checkpointing and self.training:
938
+ layer_outputs = self._gradient_checkpointing_func(
939
+ encoder_layer.__call__,
940
+ hidden_states,
941
+ attention_mask,
942
+ (head_mask[idx] if head_mask is not None else None),
943
+ output_attentions,
944
+ )
945
+ else:
946
+ layer_outputs = encoder_layer(
947
+ hidden_states,
948
+ attention_mask,
949
+ layer_head_mask=(
950
+ head_mask[idx] if head_mask is not None else None
951
+ ),
952
+ output_attentions=output_attentions,
953
+ )
954
+
955
+ hidden_states = layer_outputs[0]
956
+
957
+ if output_attentions:
958
+ all_attentions = all_attentions + (layer_outputs[1],)
959
+
960
+ hidden_states = self.layer_norm(hidden_states)
961
+ if output_hidden_states:
962
+ encoder_states = encoder_states + (hidden_states,)
963
+
964
+ if not return_dict:
965
+ return tuple(
966
+ v
967
+ for v in [hidden_states, encoder_states, all_attentions]
968
+ if v is not None
969
+ )
970
+ return transformers.modeling_outputs.BaseModelOutput(
971
+ last_hidden_state=hidden_states,
972
+ hidden_states=encoder_states,
973
+ attentions=all_attentions,
974
+ )
975
+
976
+
977
+ UltravoxConfig.register_for_auto_class()
978
+ UltravoxModel.register_for_auto_class()
979
+
980
+ transformers.AutoConfig.register("ultravox", UltravoxConfig)
981
+ transformers.AutoModel.register(UltravoxConfig, UltravoxModel)
982
+
983
+ 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,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = self.vocab[self.audio_token_replacement]
332
+
333
+ for i, token_len in enumerate(data.get("audio_token_len", [])):
334
+ if not audio_is_continuation[i]:
335
+ placeholder_index += 1
336
+ if placeholder_index >= len(split_input_ids):
337
+ raise ValueError(
338
+ f"Text contains too few audio placeholders. (Expected {len(audios)} placeholders)"
339
+ )
340
+
341
+ input_ids.extend(split_input_ids[placeholder_index])
342
+
343
+ audio_token_start_idx.append(len(input_ids))
344
+
345
+ input_ids.extend([audio_replacement_token_id] * token_len)
346
+
347
+ # Include any tokens after the last audio.
348
+ placeholder_index += 1
349
+ if placeholder_index != len(split_input_ids) - 1:
350
+ raise ValueError(
351
+ f"Text contains too many audio placeholders. (Expected {len(audios)} placeholders)"
352
+ )
353
+ input_ids.extend(split_input_ids[placeholder_index])
354
+
355
+ if "audio_token_len" in data:
356
+ data["audio_token_start_idx"] = torch.as_tensor(audio_token_start_idx)
357
+
358
+ data["input_ids"] = [input_ids]
359
+ data["attention_mask"] = [[1] * len(input_ids)]
360
+
361
+ # Ensure that there are no audio placeholders after the last audio.
362
+
363
+ return transformers.BatchFeature(data=data, tensor_type=return_tensors)
364
+
365
+ def batch_decode(self, *args, **kwargs):
366
+ return self.tokenizer.batch_decode(*args, **kwargs)
367
+
368
+ def decode(self, *args, **kwargs):
369
+ return self.tokenizer.decode(*args, **kwargs)
370
+
371
+ @property
372
+ def model_input_names(self):
373
+ tokenizer_input_names = self.tokenizer.model_input_names
374
+ audio_processor_input_names = self.audio_processor.model_input_names
375
+ return list(set(tokenizer_input_names + audio_processor_input_names))
376
+
377
+
378
+ UltravoxProcessor.register_for_auto_class()
379
+
380
+ 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]
vocab.json ADDED
The diff for this file is too large to render. See raw diff