zqhuang commited on
Commit
b110422
·
verified ·
1 Parent(s): 2f7e5ff

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]
chat_template.jinja ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gMASK]<sop>
2
+ {%- if tools -%}
3
+ <|system|>
4
+ # Tools
5
+
6
+ You may call one or more functions to assist with the user query.
7
+
8
+ You are provided with function signatures within <tools></tools> XML tags:
9
+ <tools>
10
+ {% for tool in tools %}
11
+ {{ tool | tojson(ensure_ascii=False) }}
12
+ {% endfor %}
13
+ </tools>
14
+
15
+ For each function call, output the function name and arguments within the following XML format:
16
+ <tool_call>{function-name}
17
+ <arg_key>{arg-key-1}</arg_key>
18
+ <arg_value>{arg-value-1}</arg_value>
19
+ <arg_key>{arg-key-2}</arg_key>
20
+ <arg_value>{arg-value-2}</arg_value>
21
+ ...
22
+ </tool_call>{%- endif -%}
23
+ {%- macro visible_text(content) -%}
24
+ {%- if content is string -%}
25
+ {{- content }}
26
+ {%- elif content is iterable and content is not mapping -%}
27
+ {%- for item in content -%}
28
+ {%- if item is mapping and item.type == 'text' -%}
29
+ {{- item.text }}
30
+ {%- elif item is string -%}
31
+ {{- item }}
32
+ {%- endif -%}
33
+ {%- endfor -%}
34
+ {%- else -%}
35
+ {{- content }}
36
+ {%- endif -%}
37
+ {%- endmacro -%}
38
+ {%- set ns = namespace(last_user_index=-1) %}
39
+ {%- for m in messages %}
40
+ {%- if m.role == 'user' %}
41
+ {% set ns.last_user_index = loop.index0 -%}
42
+ {%- endif %}
43
+ {%- endfor %}
44
+ {% for m in messages %}
45
+ {%- if m.role == 'user' -%}<|user|>
46
+ {{ visible_text(m.content) }}
47
+ {{- '/nothink' if (enable_thinking is defined and not enable_thinking and not visible_text(m.content).endswith("/nothink")) else '' -}}
48
+ {%- elif m.role == 'assistant' -%}
49
+ <|assistant|>
50
+ {%- set reasoning_content = '' %}
51
+ {%- set content = visible_text(m.content) %}
52
+ {%- if m.reasoning_content is string %}
53
+ {%- set reasoning_content = m.reasoning_content %}
54
+ {%- else %}
55
+ {%- if '</think>' in content %}
56
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
57
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {%- if loop.index0 > ns.last_user_index and reasoning_content -%}
61
+ {{ '\n<think>' + reasoning_content.strip() + '</think>'}}
62
+ {%- else -%}
63
+ {{ '\n<think></think>' }}
64
+ {%- endif -%}
65
+ {%- if content.strip() -%}
66
+ {{ '\n' + content.strip() }}
67
+ {%- endif -%}
68
+ {% if m.tool_calls %}
69
+ {% for tc in m.tool_calls %}
70
+ {%- if tc.function %}
71
+ {%- set tc = tc.function %}
72
+ {%- endif %}
73
+ {{ '\n<tool_call>' + tc.name }}
74
+ {% set _args = tc.arguments %}
75
+ {% for k, v in _args.items() %}
76
+ <arg_key>{{ k }}</arg_key>
77
+ <arg_value>{{ v | tojson(ensure_ascii=False) if v is not string else v }}</arg_value>
78
+ {% endfor %}
79
+ </tool_call>{% endfor %}
80
+ {% endif %}
81
+ {%- elif m.role == 'tool' -%}
82
+ {%- if m.content is string -%}
83
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
84
+ {{- '<|observation|>' }}
85
+ {%- endif %}
86
+ {{- '\n<tool_response>\n' }}
87
+ {{- m.content }}
88
+ {{- '\n</tool_response>' }}
89
+ {%- else -%}
90
+ <|observation|>{% for tr in m.content %}
91
+
92
+ <tool_response>
93
+ {{ tr.output if tr.output is defined else tr }}
94
+ </tool_response>{% endfor -%}
95
+ {% endif -%}
96
+ {%- elif m.role == 'system' -%}
97
+ <|system|>
98
+ {{ visible_text(m.content) }}
99
+ {%- endif -%}
100
+ {%- endfor -%}
101
+ {%- if add_generation_prompt -%}
102
+ <|assistant|>{{- '\n<think></think>' if (enable_thinking is defined and not enable_thinking) else '' -}}
103
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "UltravoxModel"
4
+ ],
5
+ "attn_implementation": null,
6
+ "audio_config": {
7
+ "_name_or_path": "openai/whisper-large-v3-turbo",
8
+ "activation_dropout": 0.0,
9
+ "activation_function": "gelu",
10
+ "apply_spec_augment": false,
11
+ "architectures": [
12
+ "WhisperForConditionalGeneration"
13
+ ],
14
+ "attention_dropout": 0.0,
15
+ "bos_token_id": 50257,
16
+ "classifier_proj_size": 256,
17
+ "d_model": 1280,
18
+ "decoder_attention_heads": 20,
19
+ "decoder_ffn_dim": 5120,
20
+ "decoder_layerdrop": 0.0,
21
+ "decoder_layers": 4,
22
+ "decoder_start_token_id": 50258,
23
+ "dropout": 0.0,
24
+ "dtype": "float16",
25
+ "encoder_attention_heads": 20,
26
+ "encoder_ffn_dim": 5120,
27
+ "encoder_layerdrop": 0.0,
28
+ "encoder_layers": 32,
29
+ "eos_token_id": 50257,
30
+ "init_std": 0.02,
31
+ "mask_feature_length": 10,
32
+ "mask_feature_min_masks": 0,
33
+ "mask_feature_prob": 0.0,
34
+ "mask_time_length": 10,
35
+ "mask_time_min_masks": 2,
36
+ "mask_time_prob": 0.05,
37
+ "max_source_positions": 1500,
38
+ "max_target_positions": 448,
39
+ "median_filter_width": 7,
40
+ "model_type": "whisper",
41
+ "num_hidden_layers": 32,
42
+ "num_mel_bins": 128,
43
+ "pad_token_id": 50257,
44
+ "scale_embedding": false,
45
+ "use_cache": true,
46
+ "use_weighted_layer_sum": false,
47
+ "vocab_size": 51866
48
+ },
49
+ "audio_latency_block_size": null,
50
+ "audio_model_id": null,
51
+ "audio_token_index": 151365,
52
+ "auto_map": {
53
+ "AutoConfig": "ultravox_config.UltravoxConfig",
54
+ "AutoModel": "ultravox_model.UltravoxModel"
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
+ "dtype": "bfloat16",
67
+ "hidden_logits_layers": null,
68
+ "hidden_size": 4096,
69
+ "ignore_index": -100,
70
+ "initializer_range": 0.02,
71
+ "llm_only_training": false,
72
+ "model_type": "ultravox",
73
+ "moe_capture_layers": [
74
+ 5,
75
+ 25,
76
+ 45,
77
+ 65,
78
+ 85
79
+ ],
80
+ "norm_init": 0.4,
81
+ "num_llm_layers": -1,
82
+ "num_projector_layers": 4,
83
+ "pad_token_id": 151329,
84
+ "projector_act": "swiglu",
85
+ "projector_ln_mid": true,
86
+ "stack_factor": 8,
87
+ "text_model_id": "zai-org/GLM-4.6",
88
+ "text_model_quantization": null,
89
+ "transformers_version": "4.56.2",
90
+ "use_fsdp": true,
91
+ "vocab_size": 151552
92
+ }
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": [
4
+ 151329,
5
+ 151336,
6
+ 151338
7
+ ],
8
+ "pad_token_id": 151329,
9
+ "transformers_version": "4.56.2"
10
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd9c5309e305c27c6620149fdec942a3c917afa2c6ef27409aeecda264550d79
3
+ size 1474609120
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": "<|endoftext|>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ },
18
+ "pad_token": {
19
+ "content": "<|endoftext|>",
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:96e1ca1945519d47f9b5e3d8f0eeb3c2955ccdcf1a27cc062c44e8507fa4ab59
3
+ size 19970886
tokenizer_config.json ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "151329": {
4
+ "content": "<|endoftext|>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "151330": {
12
+ "content": "[MASK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "151331": {
20
+ "content": "[gMASK]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "151332": {
28
+ "content": "[sMASK]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "151333": {
36
+ "content": "<sop>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "151334": {
44
+ "content": "<eop>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "151335": {
52
+ "content": "<|system|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "151336": {
60
+ "content": "<|user|>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "151337": {
68
+ "content": "<|assistant|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "151338": {
76
+ "content": "<|observation|>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "151339": {
84
+ "content": "<|begin_of_image|>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "151340": {
92
+ "content": "<|end_of_image|>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "151341": {
100
+ "content": "<|begin_of_video|>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "151342": {
108
+ "content": "<|end_of_video|>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "151343": {
116
+ "content": "<|begin_of_audio|>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "151344": {
124
+ "content": "<|end_of_audio|>",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "151345": {
132
+ "content": "<|begin_of_transcription|>",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "151346": {
140
+ "content": "<|end_of_transcription|>",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ },
147
+ "151347": {
148
+ "content": "<|code_prefix|>",
149
+ "lstrip": false,
150
+ "normalized": false,
151
+ "rstrip": false,
152
+ "single_word": false,
153
+ "special": true
154
+ },
155
+ "151348": {
156
+ "content": "<|code_middle|>",
157
+ "lstrip": false,
158
+ "normalized": false,
159
+ "rstrip": false,
160
+ "single_word": false,
161
+ "special": true
162
+ },
163
+ "151349": {
164
+ "content": "<|code_suffix|>",
165
+ "lstrip": false,
166
+ "normalized": false,
167
+ "rstrip": false,
168
+ "single_word": false,
169
+ "special": true
170
+ },
171
+ "151350": {
172
+ "content": "<think>",
173
+ "lstrip": false,
174
+ "normalized": false,
175
+ "rstrip": false,
176
+ "single_word": false,
177
+ "special": false
178
+ },
179
+ "151351": {
180
+ "content": "</think>",
181
+ "lstrip": false,
182
+ "normalized": false,
183
+ "rstrip": false,
184
+ "single_word": false,
185
+ "special": false
186
+ },
187
+ "151352": {
188
+ "content": "<tool_call>",
189
+ "lstrip": false,
190
+ "normalized": false,
191
+ "rstrip": false,
192
+ "single_word": false,
193
+ "special": false
194
+ },
195
+ "151353": {
196
+ "content": "</tool_call>",
197
+ "lstrip": false,
198
+ "normalized": false,
199
+ "rstrip": false,
200
+ "single_word": false,
201
+ "special": false
202
+ },
203
+ "151354": {
204
+ "content": "<tool_response>",
205
+ "lstrip": false,
206
+ "normalized": false,
207
+ "rstrip": false,
208
+ "single_word": false,
209
+ "special": false
210
+ },
211
+ "151355": {
212
+ "content": "</tool_response>",
213
+ "lstrip": false,
214
+ "normalized": false,
215
+ "rstrip": false,
216
+ "single_word": false,
217
+ "special": false
218
+ },
219
+ "151356": {
220
+ "content": "<arg_key>",
221
+ "lstrip": false,
222
+ "normalized": false,
223
+ "rstrip": false,
224
+ "single_word": false,
225
+ "special": false
226
+ },
227
+ "151357": {
228
+ "content": "</arg_key>",
229
+ "lstrip": false,
230
+ "normalized": false,
231
+ "rstrip": false,
232
+ "single_word": false,
233
+ "special": false
234
+ },
235
+ "151358": {
236
+ "content": "<arg_value>",
237
+ "lstrip": false,
238
+ "normalized": false,
239
+ "rstrip": false,
240
+ "single_word": false,
241
+ "special": false
242
+ },
243
+ "151359": {
244
+ "content": "</arg_value>",
245
+ "lstrip": false,
246
+ "normalized": false,
247
+ "rstrip": false,
248
+ "single_word": false,
249
+ "special": false
250
+ },
251
+ "151360": {
252
+ "content": "/nothink",
253
+ "lstrip": false,
254
+ "normalized": false,
255
+ "rstrip": false,
256
+ "single_word": false,
257
+ "special": true
258
+ },
259
+ "151361": {
260
+ "content": "<|begin_of_box|>",
261
+ "lstrip": false,
262
+ "normalized": false,
263
+ "rstrip": false,
264
+ "single_word": false,
265
+ "special": false
266
+ },
267
+ "151362": {
268
+ "content": "<|end_of_box|>",
269
+ "lstrip": false,
270
+ "normalized": false,
271
+ "rstrip": false,
272
+ "single_word": false,
273
+ "special": false
274
+ },
275
+ "151363": {
276
+ "content": "<|image|>",
277
+ "lstrip": false,
278
+ "normalized": false,
279
+ "rstrip": false,
280
+ "single_word": false,
281
+ "special": false
282
+ },
283
+ "151364": {
284
+ "content": "<|video|>",
285
+ "lstrip": false,
286
+ "normalized": false,
287
+ "rstrip": false,
288
+ "single_word": false,
289
+ "special": false
290
+ },
291
+ "151365": {
292
+ "content": "<|audio|>",
293
+ "lstrip": false,
294
+ "normalized": false,
295
+ "rstrip": false,
296
+ "single_word": false,
297
+ "special": true
298
+ }
299
+ },
300
+ "additional_special_tokens": [
301
+ "<|audio|>"
302
+ ],
303
+ "auto_map": {
304
+ "AutoProcessor": "ultravox_processing.UltravoxProcessor"
305
+ },
306
+ "clean_up_tokenization_spaces": false,
307
+ "do_lower_case": false,
308
+ "eos_token": "<|endoftext|>",
309
+ "extra_special_tokens": {},
310
+ "model_max_length": 128000,
311
+ "pad_token": "<|endoftext|>",
312
+ "padding_side": "right",
313
+ "processor_class": "UltravoxProcessor",
314
+ "remove_space": false,
315
+ "tokenizer_class": "PreTrainedTokenizerFast"
316
+ }
ultravox_config.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from enum import Enum
3
+ from typing import Any, Dict, List, Optional
4
+
5
+ import transformers
6
+ from transformers import BitsAndBytesConfig
7
+ from transformers import HqqConfig
8
+
9
+ @dataclasses.dataclass
10
+ class LoraConfigSimplified:
11
+ """
12
+ Low Rank Approximation (LoRA) configuration.
13
+
14
+ Used for language and audio models separately.
15
+ """
16
+
17
+ # The rank of the approximation
18
+ r: int = 0
19
+ lora_alpha: float = 8
20
+ target_modules: Optional[List[str]] = dataclasses.field(
21
+ default_factory=lambda: ["k_proj", "q_proj", "linear_k", "linear_q"]
22
+ )
23
+ # A list of module names regex patterns to unfreeze. Only used if r == 0.
24
+ unfreeze_layers: Optional[List[str]] = None
25
+
26
+
27
+ class LossMaskType(str, Enum):
28
+ """Type of loss mask to use."""
29
+
30
+ LAST_ASSISTANT = "last_assistant"
31
+ """This applies the loss mask up until the last assistant token"""
32
+ ALL = "all" # This does not work with KL loss
33
+ """No loss mask, all inputs are used for loss"""
34
+ AFTER_AUDIO = "after_audio"
35
+ """Applies the loss mask up until the audio token"""
36
+
37
+
38
+ class UltravoxConfig(transformers.PretrainedConfig):
39
+ r"""
40
+ This is the configuration class to store the configuration of a [`UltravoxForConditionalGeneration`]. It is used to instantiate an
41
+ Ultravox model according to the specified arguments, defining the model architecture.
42
+
43
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
44
+ documentation from [`PretrainedConfig`] for more information.
45
+
46
+ Args:
47
+ audio_config (`WhisperConfig`, *optional*):
48
+ Custom audio config or dict
49
+ text_config (`Union[AutoConfig, dict]`, *optional*):
50
+ The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`.
51
+ ignore_index (`int`, *optional*, defaults to -100):
52
+ The ignore index for the loss function.
53
+ audio_token_index (`int`, *optional*, defaults to 32000):
54
+ The audio token index to encode the audio prompt.
55
+ stack_factor (`int`, *optional*, defaults to 8):
56
+ Audio downsampling factor for the multimodal projector.
57
+ norm_init (`float`, *optional*, defaults to 0.4):
58
+ The initialization value for the layer normalization.
59
+ projector_act (`str`, *optional*, defaults to `"swiglu"`):
60
+ The activation function used by the multimodal projector.
61
+ text_model_lora_config (`LoraConfigSimplified`, *optional*):
62
+ The LoRA configuration for finetuning the text model.
63
+ audio_model_lora_config (`LoraConfigSimplified`, *optional*):
64
+ The LoRA configuration for finetuning the audio model.
65
+ audio_latency_block_size (`int`, *optional*, defaults to `None`):
66
+ The latency block size for simulating audio streaming.
67
+ attn_implementation (`str`, *optional*, defaults to "eager"):
68
+ The attention implementation to use. Choose from one of "eager", "flash_attention_2", or "sdpa".
69
+ use_fsdp (`bool`, *optional*, defaults to False):
70
+ If set to True, Ultravox will use FSDP for distributed training.
71
+ Configuration for kernel acceleration backends (unsloth, liger, etc).
72
+
73
+
74
+ Example:
75
+
76
+ ```python
77
+ >>> from transformers import UltravoxModel, WhisperConfig, UltravoxConfig, LlamaConfig
78
+
79
+ >>> # Initializing an audio encoder config
80
+ >>> audio_config = WhisperConfig()
81
+
82
+ >>> # Initializing a Llama config
83
+ >>> text_config = LlamaConfig()
84
+
85
+ >>> # Initializing a default configuration
86
+ >>> configuration = UltravoxConfig(audio_config, text_config)
87
+
88
+ >>> # Initializing a completely untrained model from the configuration
89
+ >>> model = UltravoxModel(configuration)
90
+
91
+ >>> # Accessing the model configuration
92
+ >>> configuration = model.config
93
+
94
+ >>> # Initialize a model from pretrained checkpoints and random projector weights
95
+ >>> config = UltravoxConfig(audio_model_id="openai/whisper-tiny", text_model_id="meta-llama/Llama-2-7b-chat-hf")
96
+ ```"""
97
+
98
+ model_type = "ultravox"
99
+ is_composition = False
100
+
101
+ def __init__(
102
+ self,
103
+ audio_config: dict[str, Any] | transformers.PretrainedConfig | None = None,
104
+ text_config: dict[str, Any] | transformers.PretrainedConfig | None = None,
105
+ audio_model_id: str | None = None,
106
+ text_model_id: str | None = None,
107
+ llm_only_training: bool = False,
108
+ ignore_index: int = -100,
109
+ audio_token_index: int | None = None,
110
+ hidden_size: int = 4096,
111
+ stack_factor: int = 8,
112
+ norm_init: float = 0.4,
113
+ projector_act: str = "swiglu",
114
+ projector_ln_mid: bool = False, # defaults to False for compatibility with v0.4.1 and below
115
+ num_projector_layers: int = 4,
116
+ text_model_lora_config: LoraConfigSimplified | None = None,
117
+ audio_model_lora_config: LoraConfigSimplified | None = None,
118
+ num_llm_layers: int = -1,
119
+ audio_latency_block_size: int | None = None,
120
+ attn_implementation: str = "eager",
121
+ use_fsdp: bool = False,
122
+ **kwargs,
123
+ ):
124
+ self.ignore_index = ignore_index
125
+
126
+ self.audio_model_id = audio_model_id
127
+ self.text_model_id = text_model_id
128
+
129
+ self.audio_token_index = audio_token_index
130
+
131
+ self.hidden_size = hidden_size
132
+ self.stack_factor = stack_factor
133
+ self.norm_init = norm_init
134
+ self.projector_act = projector_act
135
+ self.projector_ln_mid = projector_ln_mid
136
+ self.num_projector_layers = num_projector_layers
137
+ if text_model_id is not None:
138
+ text_config = transformers.AutoConfig.from_pretrained(text_model_id)
139
+ else:
140
+ text_config = text_config or {}
141
+ if isinstance(text_config, dict):
142
+ text_config = transformers.CONFIG_MAPPING[
143
+ text_config.get("model_type", "llama")
144
+ ](**text_config)
145
+
146
+ if audio_model_id is not None:
147
+ audio_config = transformers.AutoConfig.from_pretrained(audio_model_id)
148
+ else:
149
+ audio_config = audio_config or {}
150
+ if isinstance(audio_config, dict):
151
+ audio_config = transformers.CONFIG_MAPPING[
152
+ audio_config.get("model_type", "whisper")
153
+ ](**audio_config)
154
+
155
+ self.text_config = text_config
156
+ self.audio_config = audio_config
157
+
158
+ self.llm_only_training = llm_only_training
159
+ self.text_model_lora_config = (
160
+ text_model_lora_config
161
+ if isinstance(text_model_lora_config, dict)
162
+ else dataclasses.asdict(text_model_lora_config or LoraConfigSimplified())
163
+ )
164
+ self.audio_model_lora_config = (
165
+ audio_model_lora_config
166
+ if isinstance(audio_model_lora_config, dict)
167
+ else dataclasses.asdict(audio_model_lora_config or LoraConfigSimplified())
168
+ )
169
+ self.audio_latency_block_size = audio_latency_block_size
170
+
171
+ if hasattr(text_config, "text_config"):
172
+ text_config.vocab_size = text_config.text_config.vocab_size
173
+ text_config.hidden_size = text_config.text_config.hidden_size
174
+
175
+ self.vocab_size = text_config.vocab_size
176
+
177
+ self.initializer_range = text_config.initializer_range
178
+
179
+ self.attn_implementation = attn_implementation
180
+
181
+ self.use_fsdp = use_fsdp
182
+ self.num_llm_layers = num_llm_layers
183
+
184
+ super().__init__(**kwargs)
185
+
186
+ def to_diff_dict(self) -> Dict[str, Any]:
187
+ diff_dict = super().to_diff_dict()
188
+
189
+ # remove text_config and audio_config if text_model_id and audio_model_id are present
190
+ if self.text_model_id is not None:
191
+ diff_dict.pop("text_config", None)
192
+ elif "text_config" in diff_dict:
193
+ diff_dict["text_config"].pop("_attn_implementation_autoset", None)
194
+
195
+ if self.audio_model_id is not None:
196
+ diff_dict.pop("audio_config", None)
197
+ elif "audio_config" in diff_dict:
198
+ diff_dict["audio_config"].pop("_attn_implementation_autoset", None)
199
+
200
+ return diff_dict
ultravox_model.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import re
3
+ from typing import Any, Dict, Generator, Optional, Set, Tuple, TypeVar, Union
4
+
5
+ import contextlib
6
+
7
+ import copy
8
+ import accelerate
9
+ import peft
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import transformers
14
+ import transformers.activations
15
+ import transformers.modeling_outputs
16
+ import transformers.models
17
+ from transformers.generation.utils import GenerationMixin
18
+ from transformers.models.whisper import modeling_whisper as whisper
19
+
20
+ # from ultravox.model import kernel_integrations
21
+ # from ultravox.model import model_loading_utils
22
+ # from ultravox.utils import device_helpers
23
+
24
+ # We must use relative import in this directory to allow uploading to HF Hub
25
+ # Even "from . import X" pattern doesn't work (undocumented and unclear why)
26
+ from .ultravox_config import UltravoxConfig
27
+ from .ultravox_processing import UltravoxProcessor
28
+
29
+ FROM_PRETRAINED_KWARGS = {}
30
+ SHARED_PRETRAINED_KWARGS = [
31
+ "tp_plan",
32
+ "device_map",
33
+ "torch_dtype",
34
+ "attn_implementation",
35
+ "use_flash_attention_2",
36
+ ]
37
+
38
+ class UltravoxModel(transformers.LlamaPreTrainedModel, GenerationMixin):
39
+ """
40
+ The Ultravox model which consists of an audio encoder and a language model.
41
+
42
+ Audio input is processed by the audio encoder, then every `stack_factor` frames are stacked together and
43
+ projected to the language model's embedding space using a few linear layers.
44
+ The text is embedded by the language model as usual and then the audio and text embeddings are merged together.
45
+
46
+ A special token `<|audio|>` is used to indicate the start of the audio embeddings in the merged embeddings.
47
+
48
+ Parameters:
49
+ config: Model configuration class with all the parameters of the model.
50
+ """
51
+
52
+ config_class = UltravoxConfig
53
+ config: UltravoxConfig # for type hinting
54
+ # Usually we load encoder and LLM weights from a pretrained model separately, so they are allowed to be missing
55
+ _keys_to_ignore_on_load_missing = ["audio_tower.*", "language_model.*"]
56
+ # 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
57
+ # see https://github.com/huggingface/transformers/issues/35856 and https://github.com/huggingface/trl/pull/2615/files
58
+ accepts_loss_kwargs = False
59
+
60
+ def __init__(self, config: UltravoxConfig):
61
+ super().__init__(config)
62
+ self._register_load_state_dict_pre_hook(self._pre_load_state_dict_hook)
63
+
64
+ self.keep_params: Set[str] = set()
65
+ self.vocab_size = config.vocab_size
66
+
67
+ if not config.llm_only_training:
68
+ self.audio_tower = self._create_audio_tower(config)
69
+ self.multi_modal_projector = self._create_multi_modal_projector(config)
70
+ self.audio_tower_context_length = self.audio_tower.max_context_length
71
+
72
+ self.language_model = self._create_language_model(config)
73
+
74
+ if self.language_model._tied_weights_keys is not None:
75
+ self._tied_weights_keys = [
76
+ f"language_model.{k}" for k in self.language_model._tied_weights_keys
77
+ ]
78
+
79
+ # Determine no_split_modules dynamically to use with FSDP auto_wrap policy.
80
+ # This would be something like ["LlamaDecoderLayer"] as we don't split audio encoder layers.
81
+ # FSDP throws an error if some of the layer types are not found in the model, and they need to be filted out.
82
+ # 1. Get the names the language model *wants* to keep intact
83
+ candidate_names = set(
84
+ getattr(self.language_model, "_no_split_modules", []) or []
85
+ )
86
+ # 2. Names that actually exist in the current model
87
+ present_names = {m.__class__.__name__ for m in self.modules()}
88
+ # 3. Keep only those that are both requested and present
89
+ self._no_split_modules = list(candidate_names & present_names)
90
+
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 _setup_cache(
138
+ self, cache_cls, max_batch_size: int, max_cache_len: Optional[int] = None
139
+ ):
140
+ self.language_model._setup_cache(cache_cls, max_batch_size, max_cache_len)
141
+
142
+ def _reorder_cache(self, past_key_values, beam_idx):
143
+ return self.language_model._reorder_cache(past_key_values, beam_idx)
144
+
145
+ def resize_token_embeddings(
146
+ self,
147
+ new_num_tokens: Optional[int] = None,
148
+ pad_to_multiple_of: Optional[int] = None,
149
+ ) -> nn.Embedding:
150
+ model_embeds = self.language_model.resize_token_embeddings(
151
+ new_num_tokens, pad_to_multiple_of
152
+ )
153
+ # update vocab size
154
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
155
+ self.config.vocab_size = model_embeds.num_embeddings
156
+ self.vocab_size = model_embeds.num_embeddings
157
+ return model_embeds
158
+
159
+ def _audio_iter(
160
+ self, audio_batch_size: torch.Tensor
161
+ ) -> Generator[Tuple[int, int], None, None]:
162
+ """
163
+ Iterate over the audio batch size and yield the batch index and audio index of each audio item.
164
+
165
+ Args:
166
+ audio_batch_size: A tensor of shape (B,) where B is the batch size.
167
+
168
+ Returns:
169
+ A generator that yields a tuple of (start index, length) for each audio item.
170
+ """
171
+ audio_index = 0
172
+ for i_b, batch_count in enumerate(audio_batch_size):
173
+ for _ in range(batch_count):
174
+ yield i_b, audio_index
175
+ audio_index += 1
176
+
177
+ def _select_embedings(
178
+ self,
179
+ inputs_embeds: torch.Tensor,
180
+ start_idx: torch.Tensor,
181
+ lengths: torch.Tensor,
182
+ ) -> torch.Tensor:
183
+ """
184
+ Select a contiguous slice per batch starting at `start_idx[b]` with
185
+ length `lengths[b]`, returned in a compact, front-aligned tensor.
186
+ Any positions in the output that correspond to padding are zeroed out.
187
+
188
+ Supports both 3D tensors (B, T, D) and 2D tensors (B, T).
189
+ """
190
+ B = inputs_embeds.size(0)
191
+ T = inputs_embeds.size(1)
192
+ max_length = int(lengths.max().item())
193
+ if max_length == 0:
194
+ # Return an empty slice with correct rank
195
+ if inputs_embeds.dim() == 3:
196
+ return inputs_embeds.new_zeros((B, 0, inputs_embeds.size(2)))
197
+ else:
198
+ return inputs_embeds.new_zeros((B, 0), dtype=inputs_embeds.dtype)
199
+
200
+ # --- Create indices to gather ---
201
+ idx = torch.arange(
202
+ max_length, device=inputs_embeds.device, dtype=start_idx.dtype
203
+ ) # (Lmax,)
204
+ pos = start_idx.unsqueeze(1) + idx.unsqueeze(0) # (B, Lmax)
205
+ # Clamp to prevent out-of-bounds gather, we will mask the invalid values later
206
+ pos = pos.clamp_(0, T - 1)
207
+
208
+ # --- Create mask for valid output positions ---
209
+ mask = idx.unsqueeze(0) < lengths.unsqueeze(1) # (B, Lmax)
210
+
211
+ # --- Gather and mask ---
212
+ if inputs_embeds.dim() == 3:
213
+ D = inputs_embeds.size(2)
214
+ gathered = inputs_embeds.gather(
215
+ 1, pos.unsqueeze(-1).expand(B, max_length, D)
216
+ )
217
+ # Zero out the padded values
218
+ gathered = gathered * mask.unsqueeze(-1)
219
+ return gathered
220
+ elif inputs_embeds.dim() == 2:
221
+ gathered = inputs_embeds.gather(1, pos)
222
+ # Zero out the padded values
223
+ gathered = gathered * mask
224
+ return gathered
225
+ else:
226
+ raise ValueError(
227
+ f"_select_embedings expects 2D or 3D tensors, got {inputs_embeds.dim()}D"
228
+ )
229
+
230
+ def _decoder_layers(self):
231
+ """Return decoder blocks across architectures (LLaMA/GLM/etc.)."""
232
+ lm = self.language_model
233
+ candidates = [
234
+ getattr(getattr(lm, "model", None), "layers", None),
235
+ getattr(getattr(lm, "transformer", None), "layers", None),
236
+ getattr(lm, "layers", None),
237
+ ]
238
+ for c in candidates:
239
+ if c is not None and hasattr(c, "__len__") and len(c) > 0:
240
+ return c
241
+ raise AttributeError(
242
+ "Could not locate decoder layers on language_model. Tried .model.layers, .transformer.layers, and .layers"
243
+ )
244
+
245
+ def forward(
246
+ self,
247
+ input_ids: torch.Tensor,
248
+ audio_values: Optional[torch.Tensor] = None,
249
+ inputs_embeds: Optional[torch.Tensor] = None,
250
+ labels: Optional[torch.Tensor] = None,
251
+ attention_mask: Optional[torch.Tensor] = None,
252
+ audio_token_start_idx: Optional[torch.Tensor] = None,
253
+ audio_lens: Optional[torch.Tensor] = None,
254
+ audio_token_len: Optional[torch.Tensor] = None,
255
+ audio_batch_size: Optional[torch.Tensor] = None,
256
+ past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
257
+ # the alt_* fields are needed for KL divergence loss
258
+ alt_input_ids: Optional[torch.Tensor] = None,
259
+ alt_attention_mask: Optional[torch.Tensor] = None,
260
+ alt_labels: Optional[torch.Tensor] = None,
261
+ **kwargs,
262
+ ) -> transformers.modeling_outputs.CausalLMOutputWithPast:
263
+ """
264
+ Forward pass for the Ultravox model.
265
+
266
+ `input_ids` are the tokenized text input. They are embedded by the language model as usual.
267
+ `audio_values` are processed by the audio encoder and then every `stack_factor` frames are stacked together and
268
+ projected to the language model's embedding space using a few linear layers.
269
+ The audio and text embeddings are merged together. A special token `<|audio|>` is used to indicate the start
270
+ of the audio embeddings in the merged embeddings.
271
+
272
+ Args:
273
+ input_ids: The tokenized text input.
274
+ audio_values: The processed audio values.
275
+ inputs_embeds: The embeddings for the input tokens.
276
+ labels: The tokenized text labels.
277
+ attention_mask: The attention mask for the input.
278
+ position_ids: The position ids for the input.
279
+ past_key_values: The past key value cache for the language model attention layers.
280
+ **kwargs: Additional keyword arguments. Passed directly to the language model.
281
+ """
282
+ if inputs_embeds is None:
283
+ # B x T -> B x T x D
284
+ inputs_embeds = self.get_input_embeddings().forward(input_ids)
285
+
286
+ if audio_values is not None and len(audio_values) > 0:
287
+ inputs_embeds, _, _ = (
288
+ self._prepare_audio_embeds(
289
+ inputs_embeds=inputs_embeds,
290
+ audio_values=audio_values,
291
+ audio_token_start_idx=audio_token_start_idx,
292
+ audio_lens=audio_lens,
293
+ audio_token_len=audio_token_len,
294
+ audio_batch_size=audio_batch_size,
295
+ )
296
+ )
297
+
298
+ lm_output = self.language_model.forward(
299
+ inputs_embeds=inputs_embeds,
300
+ labels=labels,
301
+ attention_mask=attention_mask,
302
+ past_key_values=past_key_values,
303
+ output_hidden_states=False, # avoid keeping all layers
304
+ **kwargs,
305
+ )
306
+
307
+ return lm_output
308
+
309
+
310
+
311
+ def _prepare_audio_embeds(
312
+ self,
313
+ inputs_embeds: torch.FloatTensor,
314
+ audio_values: torch.FloatTensor,
315
+ audio_token_start_idx: Optional[torch.Tensor] = None,
316
+ audio_lens: Optional[torch.Tensor] = None,
317
+ audio_token_len: Optional[torch.Tensor] = None,
318
+ audio_batch_size: Optional[torch.Tensor] = None,
319
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
320
+ assert (
321
+ audio_token_start_idx is not None
322
+ and audio_token_len is not None
323
+ and audio_lens is not None
324
+ and audio_batch_size is not None
325
+ ), "audio_token_start_idx/audio_token_len/audio_lens must be provided if audio_values are provided."
326
+ assert (
327
+ len(audio_token_start_idx)
328
+ == len(audio_token_len)
329
+ == len(audio_lens)
330
+ == len(audio_values)
331
+ ), "audio_token_start_idx/audio_token_len/audio_lens/audio_values must have the same batch size."
332
+ assert len(audio_batch_size) == len(
333
+ inputs_embeds
334
+ ), "audio_batch_size and inputs_embeds must have the same batch size."
335
+
336
+ # B x A/3200 x (D=max-audio-length-in-batch)
337
+ audio_tower_output = self.audio_tower.forward(
338
+ audio_values.to(self.audio_tower.dtype),
339
+ audio_len=audio_lens,
340
+ ).last_hidden_state
341
+ audio_tower_output = audio_tower_output.to(inputs_embeds.dtype)
342
+ audio_embeds = self.multi_modal_projector.forward(
343
+ audio_tower_output, audio_token_len=audio_token_len
344
+ )
345
+
346
+ # combine audio and text embeddings
347
+ merged_audio_start_idx = torch.zeros(
348
+ (inputs_embeds.shape[0],), device=inputs_embeds.device, dtype=torch.long
349
+ )
350
+ merged_audio_token_len = torch.zeros(
351
+ (inputs_embeds.shape[0],), device=inputs_embeds.device, dtype=torch.long
352
+ )
353
+ for i_b, i_a in self._audio_iter(audio_batch_size):
354
+ start_idx = audio_token_start_idx[i_a]
355
+ token_len = audio_token_len[i_a]
356
+ item_embedding = audio_embeds[i_a][:token_len]
357
+ inputs_embeds[i_b][start_idx : start_idx + token_len] = item_embedding
358
+ if merged_audio_token_len[i_b] == 0:
359
+ merged_audio_start_idx[i_b] = start_idx
360
+ merged_audio_token_len[i_b] += token_len
361
+
362
+ return inputs_embeds, merged_audio_start_idx, merged_audio_token_len
363
+
364
+ def generate(
365
+ self,
366
+ input_ids: torch.Tensor,
367
+ audio_values: Optional[torch.Tensor] = None,
368
+ inputs_embeds: Optional[torch.Tensor] = None,
369
+ audio_token_start_idx: Optional[torch.Tensor] = None,
370
+ audio_lens: Optional[torch.Tensor] = None,
371
+ audio_token_len: Optional[torch.Tensor] = None,
372
+ audio_batch_size: Optional[torch.Tensor] = None,
373
+ attention_mask: Optional[torch.Tensor] = None,
374
+ **kwargs,
375
+ ) -> torch.Tensor:
376
+ if inputs_embeds is None:
377
+ inputs_embeds = self.get_input_embeddings().forward(input_ids)
378
+
379
+ if audio_values is not None:
380
+ inputs_embeds, _, _ = (
381
+ self._prepare_audio_embeds(
382
+ inputs_embeds=inputs_embeds,
383
+ audio_values=audio_values,
384
+ audio_token_start_idx=audio_token_start_idx,
385
+ audio_lens=audio_lens,
386
+ audio_token_len=audio_token_len,
387
+ audio_batch_size=audio_batch_size,
388
+ )
389
+ )
390
+
391
+ return self.language_model.generate(
392
+ input_ids=input_ids,
393
+ inputs_embeds=inputs_embeds,
394
+ attention_mask=attention_mask,
395
+ **kwargs,
396
+ )
397
+
398
+ @classmethod
399
+ def _create_multi_modal_projector(
400
+ cls, config: UltravoxConfig
401
+ ) -> "UltravoxProjector":
402
+ if (
403
+ transformers.modeling_utils._init_weights
404
+ and config.text_model_id is not None
405
+ ):
406
+ projector = UltravoxProjector(config)
407
+ dtype = config.torch_dtype
408
+ if isinstance(dtype, str):
409
+ dtype = getattr(torch, dtype)
410
+ projector.to(dtype)
411
+ return projector
412
+ else:
413
+ with accelerate.init_empty_weights():
414
+ projector = UltravoxProjector(config)
415
+ dtype = config.torch_dtype
416
+ if isinstance(dtype, str):
417
+ dtype = getattr(torch, dtype)
418
+ projector.to(dtype)
419
+ return projector
420
+
421
+ @classmethod
422
+ def _create_audio_tower(
423
+ cls, config: UltravoxConfig
424
+ ) -> Union[transformers.Wav2Vec2Model, "ModifiedWhisperEncoder"]:
425
+ # We probably don't want to pass tp_plan or device_map to the audio tower
426
+ # But potentially other kwargs can be passed in. TODO
427
+ kwargs = {"torch_dtype": config.torch_dtype}
428
+ if (
429
+ transformers.modeling_utils._init_weights
430
+ and config.audio_model_id is not None
431
+ ):
432
+ if "whisper" in config.audio_model_id.lower():
433
+ audio_tower = ModifiedWhisperEncoder.from_pretrained(
434
+ config.audio_model_id, **kwargs
435
+ )
436
+ audio_tower.init_latency_mask(
437
+ config.audio_latency_block_size, dtype=config.torch_dtype
438
+ )
439
+ else:
440
+ assert config.audio_latency_block_size in (
441
+ None,
442
+ 0,
443
+ ), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
444
+ audio_tower = transformers.AutoModel.from_pretrained(
445
+ config.audio_model_id, **kwargs
446
+ )
447
+ else:
448
+ with accelerate.init_empty_weights():
449
+ if "whisper" in config.audio_config._name_or_path.lower():
450
+ audio_tower = ModifiedWhisperEncoder(config.audio_config)
451
+ audio_tower.init_latency_mask(
452
+ config.audio_latency_block_size,
453
+ dtype=config.torch_dtype,
454
+ )
455
+ else:
456
+ assert config.audio_latency_block_size in (
457
+ None,
458
+ 0,
459
+ ), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
460
+ # we only ever use from_config if the weights are retrained, hence initializing is not
461
+ # required. This makes the model quite creation faster since init on CPU is quite slow.
462
+ audio_tower = transformers.AutoModel.from_config(
463
+ config.audio_config, **kwargs
464
+ )
465
+
466
+ if isinstance(
467
+ audio_tower,
468
+ (transformers.Wav2Vec2BertModel, transformers.WhisperModel),
469
+ ):
470
+ # For these models we only need the encoder part
471
+ # Wav2Vec2BertModel -> Wav2Vec2BertEncoder
472
+ # WhisperModel -> WhisperEncoder
473
+ audio_tower = audio_tower.encoder
474
+
475
+ audio_tower = apply_lora(audio_tower, config.audio_model_lora_config)
476
+
477
+ # Convert all parameters to target dtype
478
+ audio_tower = audio_tower.to(config.torch_dtype)
479
+
480
+ return audio_tower
481
+
482
+ @classmethod
483
+ def _create_language_model(
484
+ cls, config: UltravoxConfig
485
+ ) -> transformers.LlamaForCausalLM:
486
+ if (
487
+ transformers.modeling_utils._init_weights
488
+ and config.text_model_id is not None
489
+ ):
490
+ language_model = transformers.AutoModelForCausalLM.from_pretrained(
491
+ config.text_model_id,
492
+ **{
493
+ "attn_implementation": config.text_config._attn_implementation,
494
+ "torch_dtype": config.torch_dtype,
495
+ **FROM_PRETRAINED_KWARGS,
496
+ },
497
+ )
498
+ else:
499
+ with accelerate.init_empty_weights():
500
+ # we only ever use from_config if the weights are retrained, hence initializing is not
501
+ # required. This makes the model quite creation faster since init on CPU is quite slow.
502
+ language_model = transformers.AutoModelForCausalLM.from_config(
503
+ config.text_config,
504
+ attn_implementation=config.text_config._attn_implementation,
505
+ torch_dtype=config.torch_dtype,
506
+ )
507
+
508
+ language_model = apply_lora(language_model, config.text_model_lora_config)
509
+ return language_model
510
+
511
+ def merge_and_unload(self):
512
+ if isinstance(self.language_model, peft.PeftModel):
513
+ self.language_model = self.language_model.merge_and_unload()
514
+ # no need to download base language model weights anymore, so we can remove the id
515
+ self.config.text_model_id = None
516
+ self.keep_params.update(
517
+ set(
518
+ [
519
+ f"language_model.{name}"
520
+ for name, _ in self.language_model.named_parameters()
521
+ ]
522
+ )
523
+ )
524
+
525
+ if hasattr(self, "audio_tower") and isinstance(
526
+ self.audio_tower, peft.PeftModel
527
+ ):
528
+ self.audio_tower = self.audio_tower.merge_and_unload()
529
+ # no need to download base audio model weights anymore, so we can remove the id
530
+ self.config.audio_model_id = None
531
+
532
+ self.keep_params.update(
533
+ set(
534
+ [
535
+ f"audio_tower.{name}"
536
+ for name, _ in self.audio_tower.named_parameters()
537
+ ]
538
+ )
539
+ )
540
+
541
+ for param in ["text_model_lora_config", "audio_model_lora_config"]:
542
+ if hasattr(self.config, param):
543
+ delattr(self.config, param)
544
+
545
+ def push_to_hub(self, *args, **kwargs):
546
+ self.merge_and_unload()
547
+ return super().push_to_hub(*args, **kwargs)
548
+
549
+ def diff_state_dict(
550
+ self, state_dict: Optional[Dict[str, Any]] = None
551
+ ) -> Dict[str, Any]:
552
+ if state_dict is None:
553
+ state_dict = super().state_dict()
554
+
555
+ trainable_params = {k for k, v in self.named_parameters() if v.requires_grad}
556
+ # normalize the keys to match the original model
557
+ # Example: audio_tower.base_model.model.layers.0._fsdp_wrapped_module.self_attn.k_proj.lora_B.default.weight
558
+ trainable_params = {
559
+ k.replace("_fsdp_wrapped_module.", "") for k in trainable_params
560
+ }
561
+
562
+ state_dict = {
563
+ k: v
564
+ for k, v in state_dict.items()
565
+ if k in self.keep_params or k in trainable_params
566
+ }
567
+
568
+ return state_dict
569
+
570
+ def save_pretrained(
571
+ self, *args, state_dict: Optional[Dict[str, Any]] = None, **kwargs
572
+ ):
573
+ state_dict = self.diff_state_dict(state_dict)
574
+
575
+ super().save_pretrained(*args, state_dict=state_dict, **kwargs)
576
+
577
+ def _pre_load_state_dict_hook(self, state_dict: Dict[str, Any], *args, **kwargs):
578
+ self.keep_params.update(set(state_dict.keys()))
579
+
580
+ def print_trainable_parameters(self):
581
+ """
582
+ Prints the number of trainable parameters in the model (reuses Peft model's method)
583
+ """
584
+ count_params = peft.peft_model.PeftModel.get_nb_trainable_parameters
585
+
586
+ trainable_params, all_param = count_params(self)
587
+
588
+ logging.info(
589
+ f"trainable params: {trainable_params:,d} || all params: {all_param:,d}"
590
+ f" || trainable%: {100 * trainable_params / all_param:.1f}%"
591
+ )
592
+
593
+ lm_trainable_params, lm_all_params = count_params(self.language_model)
594
+ if hasattr(self, "audio_tower") and self.audio_tower is not None:
595
+ audio_trainable_params, audio_all_params = count_params(self.audio_tower)
596
+ else:
597
+ audio_trainable_params, audio_all_params = 0, 0
598
+
599
+ projector_trainable_params = (
600
+ trainable_params - lm_trainable_params - audio_trainable_params
601
+ )
602
+ projector_all_params = all_param - lm_all_params - audio_all_params
603
+
604
+ # Calculate percentages only if the total parameters are non-zero
605
+ audio_percent = (
606
+ 0.0
607
+ if audio_all_params == 0
608
+ else 100 * audio_trainable_params / audio_all_params
609
+ )
610
+ projector_percent = (
611
+ 0.0
612
+ if projector_all_params == 0
613
+ else 100 * projector_trainable_params / projector_all_params
614
+ )
615
+
616
+ logging.info(
617
+ f"Trainable%: "
618
+ f" LLM: {100 * lm_trainable_params / lm_all_params:.1f}%"
619
+ f" || Audio Encoder: {audio_percent:.1f}%"
620
+ f" || Projector: {projector_percent:.1f}%"
621
+ )
622
+
623
+ def get_fsdp_wrap_module_class(self) -> Optional[type]:
624
+ """
625
+ Dynamically finds and returns the FSDP wrap module class from the language model.
626
+ This is typically the main transformer block class (e.g., LlamaDecoderLayer).
627
+ It's used by the `transformer_auto_wrap_policy`.
628
+ """
629
+ if not hasattr(self.language_model, "_no_split_modules"):
630
+ return None
631
+
632
+ # _no_split_modules is a list of class names, e.g., ["LlamaDecoderLayer"]
633
+ # We take the first one as it's the main one.
634
+ module_name_to_find = self.language_model._no_split_modules[0]
635
+
636
+ # Recursively search for a module with the desired class name.
637
+ for module in self.language_model.modules():
638
+ if module.__class__.__name__ == module_name_to_find:
639
+ return module.__class__
640
+
641
+ logging.warning(
642
+ f"Could not find FSDP wrap module class '{module_name_to_find}' in the language model."
643
+ )
644
+ return None
645
+
646
+
647
+ def get_checkpoint_files(
648
+ model_id: str,
649
+ local_files_only: bool = False,
650
+ ) -> tuple[list[str], dict | None, list[str]]:
651
+ resolved_archive_file = transformers.utils.cached_file(
652
+ model_id,
653
+ transformers.utils.SAFE_WEIGHTS_NAME,
654
+ _raise_exceptions_for_missing_entries=False,
655
+ local_files_only=local_files_only,
656
+ )
657
+
658
+ if resolved_archive_file is not None:
659
+ # not sharded
660
+ sharded_metadata = None
661
+ state_dict = transformers.modeling_utils.load_state_dict(resolved_archive_file)
662
+ loaded_state_dict_keys = list(state_dict.keys())
663
+ else:
664
+ # sharded
665
+ resolved_archive_file = transformers.utils.cached_file(
666
+ model_id,
667
+ transformers.utils.SAFE_WEIGHTS_INDEX_NAME,
668
+ local_files_only=local_files_only,
669
+ )
670
+ resolved_archive_file, sharded_metadata = (
671
+ transformers.modeling_utils.get_checkpoint_shard_files(
672
+ model_id,
673
+ resolved_archive_file,
674
+ local_files_only=local_files_only,
675
+ )
676
+ )
677
+ loaded_state_dict_keys = sharded_metadata["all_checkpoint_keys"]
678
+
679
+ if isinstance(resolved_archive_file, str):
680
+ resolved_archive_file = [resolved_archive_file]
681
+
682
+ return resolved_archive_file, sharded_metadata, loaded_state_dict_keys
683
+
684
+
685
+ # TODO: refactor common parts to a shared module
686
+ def is_cache_empty(
687
+ past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]],
688
+ ) -> bool:
689
+ """
690
+ Check if the cache is empty.
691
+ """
692
+ if past_key_values is None:
693
+ return True
694
+ if isinstance(past_key_values, tuple):
695
+ return all(len(c) == 0 for c in past_key_values)
696
+ return past_key_values.get_seq_length() == 0
697
+
698
+
699
+ T = TypeVar("T", bound=torch.nn.Module)
700
+
701
+
702
+ def apply_lora(model: T, lora_config: dict) -> T:
703
+ """
704
+ Applies LoRA finetuning to the model. If the `r` parameter is set to 0, the model is frozen instead.
705
+ """
706
+ unfreeze_layers = lora_config.pop("unfreeze_layers", None)
707
+ lora_config = peft.LoraConfig(**lora_config or {})
708
+
709
+ if lora_config.r == 0:
710
+ # freeze the model entirely, except for the specified layers
711
+ for name, param in model.named_parameters():
712
+ if not unfreeze_layers or not any(
713
+ re.match(layer, name) for layer in unfreeze_layers
714
+ ):
715
+ param.requires_grad = False
716
+ else:
717
+ logging.info(f"Unfreezing layer: {name} with #{param.numel()} params")
718
+ else:
719
+ model = peft.get_peft_model(model, lora_config)
720
+
721
+ return model
722
+
723
+
724
+ class StackAudioFrames(nn.Module):
725
+ """
726
+ Stack the audio embedding frames to reduce the sequence length by a factor
727
+ of `stack_factor`.
728
+ """
729
+
730
+ def __init__(self, stack_factor: int = 8):
731
+ super().__init__()
732
+ self.stack_factor = stack_factor
733
+
734
+ def forward(self, audio_embeds: torch.Tensor) -> torch.Tensor:
735
+ B, T, C = audio_embeds.shape
736
+ T_pad = (T + self.stack_factor - 1) // self.stack_factor * self.stack_factor
737
+ audio_embeds = F.pad(audio_embeds, (0, 0, 0, T_pad - T))
738
+ B, T, C = audio_embeds.shape
739
+ audio_embeds = audio_embeds.view(
740
+ B, T // self.stack_factor, C * self.stack_factor
741
+ )
742
+ return audio_embeds
743
+
744
+
745
+ class RMSNorm(transformers.models.llama.modeling_llama.LlamaRMSNorm):
746
+ def __init__(self, hidden_size: int, init: float = 1, eps: float = 1e-6):
747
+ super().__init__(hidden_size=hidden_size, eps=eps)
748
+ self.weight.data.fill_(init)
749
+
750
+
751
+ class SwiGLU(nn.Module):
752
+ def forward(self, x):
753
+ x, gate = x.chunk(2, dim=-1)
754
+ return F.silu(gate) * x
755
+
756
+
757
+ class UltravoxProjector(nn.Module, transformers.modeling_utils.ModuleUtilsMixin):
758
+ def __init__(self, config: UltravoxConfig):
759
+ super().__init__()
760
+ from types import SimpleNamespace
761
+
762
+ self.config = SimpleNamespace(is_decoder=False)
763
+
764
+ self._pad_and_stack = StackAudioFrames(config.stack_factor)
765
+ dim_in = config.audio_config.hidden_size * config.stack_factor
766
+
767
+ # Create a copy to avoid modifying the original config object in place.
768
+ projector_audio_config = copy.deepcopy(config.audio_config)
769
+ # Ensure the projector transformer layers use the desired attention backend
770
+ # Some backends expect `attn_implementation` (HF-style), others use `_attn_implementation` (internal/Whisper-style).
771
+ # We set both for compatibility across training and inference.
772
+ try:
773
+ attn_impl_value = config.attn_implementation if config.attn_implementation else "eager"
774
+ setattr(projector_audio_config, "attn_implementation", attn_impl_value)
775
+ try:
776
+ setattr(projector_audio_config, "_attn_implementation", attn_impl_value)
777
+ except Exception:
778
+ pass
779
+ except Exception:
780
+ pass
781
+
782
+ self.ln_pre = RMSNorm(dim_in, init=config.norm_init)
783
+ self.linear_in = nn.Linear(dim_in, projector_audio_config.d_model)
784
+
785
+ self.embed_positions = nn.Embedding(
786
+ projector_audio_config.max_source_positions, projector_audio_config.d_model
787
+ )
788
+
789
+ self.layers = nn.ModuleList(
790
+ [
791
+ whisper.WhisperEncoderLayer(projector_audio_config)
792
+ for _ in range(config.num_projector_layers)
793
+ ]
794
+ )
795
+
796
+ self.ln_post = RMSNorm(projector_audio_config.d_model, init=config.norm_init)
797
+ dim_out = config.text_config.hidden_size
798
+ self.linear_out = nn.Linear(projector_audio_config.d_model, dim_out)
799
+
800
+ def forward(
801
+ self, audio_features: torch.Tensor, audio_token_len: torch.Tensor
802
+ ) -> torch.Tensor:
803
+ audio_features = self._pad_and_stack(audio_features)
804
+
805
+ max_len_stacked = audio_features.shape[1]
806
+ attention_mask = torch.arange(max_len_stacked, device=audio_features.device)[
807
+ None, :
808
+ ].lt(audio_token_len[:, None])
809
+ extended_attention_mask = self.get_extended_attention_mask(
810
+ attention_mask, attention_mask.shape, audio_features.dtype
811
+ )
812
+
813
+ hidden_states = self.ln_pre(audio_features)
814
+
815
+ hidden_states = self.linear_in(hidden_states)
816
+
817
+ positions = self.embed_positions(
818
+ torch.arange(hidden_states.size(1), device=hidden_states.device)
819
+ )
820
+ hidden_states = hidden_states + positions
821
+
822
+ for layer in self.layers:
823
+ layer_outputs = layer(
824
+ hidden_states,
825
+ attention_mask=extended_attention_mask,
826
+ layer_head_mask=None,
827
+ )
828
+ hidden_states = layer_outputs[0]
829
+
830
+ hidden_states = self.ln_post(hidden_states)
831
+ hidden_states = self.linear_out(hidden_states)
832
+ return hidden_states
833
+
834
+ class ModifiedWhisperEncoder(
835
+ whisper.WhisperEncoder, transformers.modeling_utils.ModuleUtilsMixin
836
+ ):
837
+ """
838
+ Encoder portion of OpenAI's Whisper model.
839
+
840
+ This implementation is a slightly modified version of HF Transformers' Whisper Encoder, with only a few fixes:
841
+ 1. base_model_prefix updated to allow for doing `.from_pretrained` directly on the encoder
842
+ 2. allow less than 30 second of audio padding to be passed in:
843
+ - relaxed ValueError check for `input_features` length to be less than or equal to `expected_seq_length` instead of strictly equal
844
+ - embed_pos is now sliced to match the length of `inputs_embeds`
845
+
846
+ Original: https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py
847
+ """
848
+
849
+ base_model_prefix = "model.encoder"
850
+ _no_split_modules = ["WhisperEncoderLayer"]
851
+ _keys_to_ignore_on_load_unexpected = ["model.decoder.*"]
852
+
853
+ def __init__(self, config: transformers.WhisperConfig):
854
+ super().__init__(config)
855
+ self.config.is_decoder = False
856
+
857
+ @property
858
+ def max_context_length(self):
859
+ return (
860
+ self.config.max_source_positions
861
+ * self.conv1.stride[0]
862
+ * self.conv2.stride[0]
863
+ )
864
+
865
+ def init_latency_mask(
866
+ self, audio_latency_block_size: int | None, dtype: torch.dtype
867
+ ):
868
+ if audio_latency_block_size is None:
869
+ self.audio_streaming_mask = None
870
+ return
871
+
872
+ # Use max_context_length directly in the calculation
873
+ max_seqlen = self.max_context_length
874
+ assert (
875
+ max_seqlen > 0
876
+ ), f"maximum sequence length must be positive, got {max_seqlen}"
877
+ assert (
878
+ max_seqlen % audio_latency_block_size == 0
879
+ ), f"audio_latency_block_size {audio_latency_block_size} must divide {max_seqlen} evenly."
880
+ # Given the block size, we calculate number of blocks.
881
+ audio_latency_nblocks = max_seqlen // audio_latency_block_size
882
+ audio_streaming_mask = (
883
+ torch.tril(
884
+ torch.ones(audio_latency_nblocks, audio_latency_nblocks),
885
+ diagonal=0,
886
+ )
887
+ .repeat_interleave(audio_latency_block_size, dim=0)
888
+ .repeat_interleave(audio_latency_block_size, dim=1)
889
+ )
890
+ audio_streaming_mask = (1.0 - audio_streaming_mask) * torch.finfo(dtype).min
891
+ audio_streaming_mask = audio_streaming_mask[None, None, :, :]
892
+ self.register_buffer(
893
+ "audio_streaming_mask", audio_streaming_mask, persistent=False
894
+ )
895
+
896
+ def forward(
897
+ self,
898
+ input_features,
899
+ audio_len=None,
900
+ head_mask=None,
901
+ output_attentions=None,
902
+ output_hidden_states=None,
903
+ return_dict=None,
904
+ ):
905
+ expected_seq_length = self.max_context_length
906
+ if input_features.shape[-1] > expected_seq_length:
907
+ raise ValueError(
908
+ 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}."
909
+ )
910
+
911
+ output_attentions = (
912
+ output_attentions
913
+ if output_attentions is not None
914
+ else self.config.output_attentions
915
+ )
916
+ output_hidden_states = (
917
+ output_hidden_states
918
+ if output_hidden_states is not None
919
+ else self.config.output_hidden_states
920
+ )
921
+ return_dict = (
922
+ return_dict if return_dict is not None else self.config.use_return_dict
923
+ )
924
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
925
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
926
+
927
+ inputs_embeds = inputs_embeds.permute(0, 2, 1)
928
+ embed_pos = self.embed_positions.weight[: inputs_embeds.size(-2)]
929
+
930
+ hidden_states = inputs_embeds + embed_pos
931
+ hidden_states = nn.functional.dropout(
932
+ hidden_states, p=self.dropout, training=self.training
933
+ )
934
+
935
+ encoder_states = () if output_hidden_states else None
936
+ all_attentions = () if output_attentions else None
937
+
938
+ # Create attention mask based on audio lengths to mask out padding tokens
939
+ # For each sample in batch:
940
+ # - Convert raw audio length to feature length after convolutions
941
+ # - Create boolean mask that is True for valid positions and False for padding
942
+ # - Convert to extended attention mask format expected by transformer layers
943
+ # (1.0 for positions to attend to, large negative for positions to ignore)
944
+ # This masking ensures consistent behavior between training and inference
945
+ # by preventing the model from attending to padding tokens in both cases
946
+ attention_mask = None
947
+ if audio_len is not None:
948
+ audio_feature_len = self._get_feat_extract_output_lengths(audio_len)
949
+ max_seq_len = hidden_states.shape[1]
950
+ attention_mask = torch.arange(max_seq_len, device=hidden_states.device)[
951
+ None, :
952
+ ].lt(audio_feature_len.view(-1, 1))
953
+ attention_mask = self.get_extended_attention_mask(
954
+ attention_mask,
955
+ None,
956
+ dtype=hidden_states.dtype,
957
+ )
958
+
959
+ if self.audio_streaming_mask is not None:
960
+ seqlen = hidden_states.size(-2)
961
+ if attention_mask is not None:
962
+ attention_mask = torch.minimum(
963
+ self.audio_streaming_mask[:, :, :seqlen, :seqlen], attention_mask
964
+ ) # merge
965
+ else:
966
+ attention_mask = self.audio_streaming_mask[:, :, :seqlen, :seqlen]
967
+ attention_mask = attention_mask.to(hidden_states.dtype)
968
+
969
+ # check if head_mask has a correct number of layers specified if desired
970
+ if head_mask is not None:
971
+ assert head_mask.size()[0] == (
972
+ len(self.layers)
973
+ ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
974
+
975
+ for idx, encoder_layer in enumerate(self.layers):
976
+ if output_hidden_states:
977
+ encoder_states = encoder_states + (hidden_states,)
978
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
979
+ to_drop = False
980
+ if self.training:
981
+ dropout_probability = torch.rand([])
982
+ if dropout_probability < self.layerdrop: # skip the layer
983
+ to_drop = True
984
+
985
+ if to_drop:
986
+ layer_outputs = (None, None)
987
+ else:
988
+ if self.gradient_checkpointing and self.training:
989
+ layer_outputs = self._gradient_checkpointing_func(
990
+ encoder_layer.__call__,
991
+ hidden_states,
992
+ attention_mask,
993
+ (head_mask[idx] if head_mask is not None else None),
994
+ output_attentions,
995
+ )
996
+ else:
997
+ layer_outputs = encoder_layer(
998
+ hidden_states,
999
+ attention_mask,
1000
+ layer_head_mask=(
1001
+ head_mask[idx] if head_mask is not None else None
1002
+ ),
1003
+ output_attentions=output_attentions,
1004
+ )
1005
+
1006
+ hidden_states = layer_outputs[0]
1007
+
1008
+ if output_attentions:
1009
+ all_attentions = all_attentions + (layer_outputs[1],)
1010
+
1011
+ hidden_states = self.layer_norm(hidden_states)
1012
+ if output_hidden_states:
1013
+ encoder_states = encoder_states + (hidden_states,)
1014
+
1015
+ if not return_dict:
1016
+ return tuple(
1017
+ v
1018
+ for v in [hidden_states, encoder_states, all_attentions]
1019
+ if v is not None
1020
+ )
1021
+ return transformers.modeling_outputs.BaseModelOutput(
1022
+ last_hidden_state=hidden_states,
1023
+ hidden_states=encoder_states,
1024
+ attentions=all_attentions,
1025
+ )
1026
+
1027
+
1028
+ UltravoxConfig.register_for_auto_class()
1029
+ UltravoxModel.register_for_auto_class()
1030
+ UltravoxProcessor.register_for_auto_class()
1031
+
1032
+ transformers.AutoConfig.register("ultravox", UltravoxConfig)
1033
+ transformers.AutoModel.register(UltravoxConfig, UltravoxModel)
1034
+ transformers.AutoProcessor.register(
1035
+ UltravoxConfig, UltravoxProcessor, UltravoxProcessor
1036
+ )
1037
+
1038
+ transformers.activations.ACT2FN["swiglu"] = SwiGLU
ultravox_pipeline.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ chat_template: Optional[str] = None,
22
+ **kwargs,
23
+ ):
24
+ if tokenizer is None:
25
+ try:
26
+ tokenizer = from_pretrained_text_tokenizer(model.config._name_or_path)
27
+ except: # noqa: E722
28
+ tokenizer = from_pretrained_text_tokenizer(
29
+ model.config.text_model_id or model.config.text_config._name_or_path
30
+ )
31
+ if chat_template:
32
+ tokenizer.chat_template = chat_template
33
+
34
+ if chat_template:
35
+ tokenizer.chat_template = chat_template
36
+
37
+ model.config.audio_token_index = get_audio_token_id(tokenizer)
38
+
39
+ if audio_processor is None:
40
+ audio_processor = transformers.AutoProcessor.from_pretrained(
41
+ model.config.audio_model_id or model.config.audio_config._name_or_path
42
+ )
43
+
44
+ super().__init__(model=model, tokenizer=tokenizer, **kwargs)
45
+
46
+ self.processor = UltravoxProcessor(
47
+ audio_processor=audio_processor,
48
+ tokenizer=tokenizer,
49
+ stack_factor=model.config.stack_factor,
50
+ audio_context_size=model.audio_tower_context_length,
51
+ )
52
+
53
+ def _sanitize_parameters(self, **kwargs):
54
+ generation_keys = ["temperature", "max_new_tokens", "repetition_penalty"]
55
+ generation_kwargs = {k: kwargs[k] for k in kwargs if k in generation_keys}
56
+ return {}, generation_kwargs, {}
57
+
58
+ def preprocess(self, inputs: Dict[str, Any]):
59
+ turns: list = inputs.get("turns", [])
60
+
61
+ audio = inputs.get("audio", None)
62
+ # Convert to float32 if needed.
63
+ if isinstance(audio, np.ndarray):
64
+ if audio.dtype == np.float64:
65
+ audio = audio.astype(np.float32)
66
+ elif audio.dtype == np.int16:
67
+ audio = audio.astype(np.float32) / np.float32(32768.0)
68
+ elif audio.dtype == np.int32:
69
+ audio = audio.astype(np.float32) / np.float32(2147483648.0)
70
+
71
+ if audio is not None and (len(turns) == 0 or turns[-1]["role"] != "user"):
72
+ prompt = inputs.get("prompt", "<|audio|>")
73
+ if "<|audio|>" not in prompt:
74
+ logging.warning(
75
+ "Prompt does not contain '<|audio|>', appending '<|audio|>' to the end of the prompt."
76
+ )
77
+
78
+ prompt += " <|audio|>"
79
+ turns.append({"role": "user", "content": prompt})
80
+
81
+ text = self.processor.tokenizer.apply_chat_template(
82
+ turns, add_generation_prompt=True, tokenize=False
83
+ )
84
+
85
+ if "sampling_rate" not in inputs and audio is not None:
86
+ logging.warning(
87
+ "No sampling rate provided, using default of 16kHz. We highly recommend providing the correct sampling rate."
88
+ )
89
+
90
+ output = self.processor(
91
+ text=text,
92
+ audio=audio,
93
+ sampling_rate=inputs.get("sampling_rate", 16000),
94
+ )
95
+ if "audio_values" in output:
96
+ output["audio_values"] = output["audio_values"].to(self.model.dtype)
97
+
98
+ return output
99
+
100
+ def _forward(
101
+ self,
102
+ model_inputs: Dict[str, Any],
103
+ temperature: Optional[float] = None,
104
+ max_new_tokens: Optional[int] = None,
105
+ repetition_penalty: float = 1.1,
106
+ ) -> List[int]:
107
+ temperature = temperature or None
108
+ do_sample = temperature is not None
109
+
110
+ terminators = [self.tokenizer.eos_token_id]
111
+ if "<|eot_id|>" in self.tokenizer.added_tokens_encoder:
112
+ terminators.append(self.tokenizer.convert_tokens_to_ids("<|eot_id|>"))
113
+
114
+ input_len = model_inputs["input_ids"].shape[1]
115
+
116
+ outputs = self.model.generate(
117
+ **model_inputs,
118
+ do_sample=do_sample,
119
+ temperature=temperature,
120
+ max_new_tokens=max_new_tokens,
121
+ repetition_penalty=repetition_penalty,
122
+ eos_token_id=terminators,
123
+ )
124
+ return outputs[0][input_len:]
125
+
126
+ def postprocess(self, model_outputs) -> str:
127
+ output_text = self.tokenizer.decode(model_outputs, skip_special_tokens=True)
128
+ return output_text
129
+
130
+
131
+ transformers.pipelines.PIPELINE_REGISTRY.register_pipeline(
132
+ "ultravox-pipeline",
133
+ pipeline_class=UltravoxPipeline,
134
+ pt_model=transformers.AutoModel,
135
+ type="multimodal",
136
+ )
ultravox_processing.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Only process audio fields if we have non-empty audio values
44
+ if audio_values and len(audio_values) > 0 and len(audio_values[0]) > 0:
45
+ batch["audio_token_start_idx"] = torch.stack(audio_token_start_idx)
46
+ batch["audio_lens"] = torch.stack(audio_lens)
47
+ batch["audio_token_len"] = torch.stack(audio_token_len)
48
+ # Pad the last dimension of all audio_values to the same length, with 0s on the right.
49
+ max_len = max([x.shape[-1] for x in audio_values])
50
+ batch["audio_values"] = torch.stack(
51
+ [F.pad(x, (0, max_len - x.shape[-1])) for x in audio_values]
52
+ )
53
+ if self.tokenizer.padding_side == "left":
54
+ input_ids_lens = torch.LongTensor(
55
+ [f["input_ids"].shape[-1] for f in features]
56
+ )
57
+ displacement = batch["input_ids"].shape[-1] - input_ids_lens
58
+ displacement = displacement.repeat_interleave(
59
+ batch["audio_batch_size"].squeeze(-1)
60
+ )
61
+ batch["audio_token_start_idx"] += displacement.to(
62
+ batch["audio_token_start_idx"].device
63
+ )
64
+ return batch
65
+
66
+
67
+ class UltravoxProcessor(transformers.ProcessorMixin):
68
+ """
69
+ Constructs an Ultravox processor which wraps an audio processor and a tokenizer into a single processor.
70
+
71
+ Args:
72
+ audio_processor: The audio processor for the audio encoder.
73
+ tokenizer: The tokenizer for the language model.
74
+ """
75
+
76
+ attributes = ["audio_processor", "tokenizer"]
77
+ audio_processor_class = ("WhisperProcessor",)
78
+ tokenizer_class = (
79
+ "PreTrainedTokenizer",
80
+ "PreTrainedTokenizerFast",
81
+ )
82
+
83
+ tokenizer: transformers.PreTrainedTokenizerBase
84
+ audio_processor: transformers.ProcessorMixin
85
+
86
+ def __init__(
87
+ self,
88
+ audio_processor=None,
89
+ tokenizer=None,
90
+ audio_padding: str = "longest",
91
+ encoder_ds_factor: int = 2,
92
+ stack_factor: int = 8,
93
+ audio_placeholder: str = "<|audio|>",
94
+ # Defaults to whisper encoder context size
95
+ audio_context_size: Optional[int] = 3000,
96
+ ):
97
+ """
98
+ Args:
99
+ audio_processor: The audio processor for the audio encoder.
100
+ tokenizer: The tokenizer for the language model.
101
+ audio_padding: The padding strategy for the audio encoder.
102
+ stack_factor: The factor by which the audio encoder output is stacked in the multimodal projector.
103
+ encoder_ds_factor: The downsampling factor of the audio encoder.
104
+ audio_placeholder: The placeholder for the audio in the text.
105
+ audio_context_size: The maximum number of frames that the audio encoder can handle.
106
+ """
107
+ self.audio_padding = audio_padding
108
+ self.encoder_ds_factor = encoder_ds_factor
109
+ self.stack_factor = stack_factor
110
+ self.audio_placeholder = audio_placeholder
111
+ self.audio_context_size = audio_context_size
112
+ assert (
113
+ tokenizer.eos_token is not None
114
+ ), "The tokenizer has no EOS token. Cannot recover."
115
+ self.vocab = tokenizer.get_vocab()
116
+ # VLLM currently relies on updating audio_token_replacement, hence to be safe
117
+ # we should not update it. This dependency should be removed in the future.
118
+ self.audio_token_replacement = tokenizer.eos_token
119
+ if tokenizer.pad_token_id is None:
120
+ tokenizer.pad_token_id = tokenizer.eos_token_id
121
+
122
+ # Use a dummy audio processor to satisfy the base class for text-only training
123
+ if audio_processor is None:
124
+ audio_processor = transformers.AutoProcessor.from_pretrained(
125
+ "openai/whisper-tiny"
126
+ )
127
+
128
+ super().__init__(audio_processor=audio_processor, tokenizer=tokenizer)
129
+
130
+ @classmethod
131
+ def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
132
+ config: UltravoxConfig = transformers.AutoConfig.from_pretrained(
133
+ pretrained_model_name_or_path, **kwargs
134
+ )
135
+ audio_processor = transformers.AutoProcessor.from_pretrained(
136
+ config.audio_model_id
137
+ or config.audio_config._name_or_path
138
+ or "openai/whisper-tiny"
139
+ )
140
+
141
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
142
+ pretrained_model_name_or_path, **kwargs
143
+ )
144
+ tokenizer.padding_side = "left"
145
+ tokenizer.pad_token = tokenizer.eos_token
146
+
147
+ return cls(
148
+ audio_processor=audio_processor,
149
+ tokenizer=tokenizer,
150
+ stack_factor=config.stack_factor,
151
+ )
152
+
153
+ def _chunk_and_pad_audio(
154
+ self,
155
+ audio_values: torch.Tensor,
156
+ audio_lens: torch.Tensor,
157
+ include_audio_num_chunks: bool = False,
158
+ ) -> Dict[str, Any]:
159
+ """
160
+ Processes the audio batch by chunking any items in the batch according to the audio_context_size,
161
+ padding the last chunk if needed, and returns a dictionary with updated audio data.
162
+
163
+ Args:
164
+ audio_values (torch.Tensor): A tensor of audio values (e.g., in B, D, T format).
165
+ audio_lens (torch.Tensor): A tensor of audio lengths.
166
+
167
+ Returns:
168
+ Dict[str, Any]: Dictionary with the following keys:
169
+ - "audio_values": The concatenated audio tensor after chunking and padding.
170
+ - "audio_lens": Tensor of lengths for each chunk.
171
+ - "audio_is_continuation": Tensor of booleans indicating if the chunk is a continuation of the previous chunk.
172
+ - "audio_batch_size": A Tensor with one integer representing the number of chunks.
173
+
174
+ """
175
+ chunked_audio_values: List[torch.Tensor] = []
176
+ chunked_audio_lens: List[int] = []
177
+ is_continuation_list: List[bool] = []
178
+ num_chunks: List[int] = []
179
+ context_size = self.audio_context_size or audio_values.shape[-1]
180
+
181
+ for i in range(audio_values.shape[0]): # iterate over the batch
182
+ num_chunks.append(int(np.ceil(audio_lens[i] / context_size)))
183
+ for offset in range(0, audio_lens[i], context_size):
184
+ is_continuation = offset > 0
185
+ chunk = audio_values[i, :, offset : offset + context_size]
186
+ if is_continuation and chunk.shape[-1] < context_size:
187
+ # N.B. We only need to pad continuation chunks. If none of the samples require chunking, the
188
+ # batch might not (need to) be padded all the way to the audio_context_size, in which case
189
+ # we've already included the padding above. On the other hand, if we have any continuation
190
+ # chunks we know that the batch needs to be padded to audio_context_size because that's what
191
+ # we're slicing to.
192
+ chunk = F.pad(chunk, (0, context_size - chunk.shape[-1]))
193
+ chunked_audio_values.append(chunk)
194
+ chunked_audio_lens.append(
195
+ min(int(audio_lens[i].item()) - offset, context_size)
196
+ )
197
+ is_continuation_list.append(is_continuation)
198
+
199
+ data = {
200
+ "audio_values": torch.stack(chunked_audio_values, dim=0),
201
+ "audio_lens": torch.tensor(
202
+ chunked_audio_lens, dtype=torch.int64, device=audio_values.device
203
+ ),
204
+ "audio_is_continuation": torch.tensor(
205
+ is_continuation_list, dtype=torch.bool, device=audio_values.device
206
+ ),
207
+ "audio_batch_size": torch.tensor(
208
+ [len(chunked_audio_values)], device=audio_values.device
209
+ ),
210
+ }
211
+ if include_audio_num_chunks:
212
+ data["audio_num_chunks"] = torch.tensor(
213
+ num_chunks, dtype=torch.int64, device=audio_values.device
214
+ )
215
+ return data
216
+
217
+ def __call__(
218
+ self,
219
+ text: Optional[str] = None,
220
+ audio: Optional[Union[np.ndarray, torch.Tensor]] = None,
221
+ audios: Optional[
222
+ Union[
223
+ List[Union[np.ndarray, torch.Tensor]], Union[np.ndarray, torch.Tensor]
224
+ ]
225
+ ] = None,
226
+ sampling_rate: Optional[int] = None,
227
+ return_tensors: Optional[
228
+ Union[str, transformers.TensorType]
229
+ ] = transformers.TensorType.PYTORCH,
230
+ include_audio_num_chunks: bool = False,
231
+ **kwargs,
232
+ ) -> transformers.BatchFeature:
233
+ """
234
+ Main method to prepare for the model one text sequence and audio. This method forwards the `text`
235
+ and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
236
+ the text. To prepare the audio(s), this method forwards the `audio`, `sampling_rate` and `kwargs` arguments to
237
+ audio processor's [`~WhisperProcessor.__call__`] if `audio` is not `None`. Please refer to the docstring
238
+ of the above two methods for more information.
239
+
240
+ Args:
241
+ text (`str`, `List[str]`):
242
+ The sequence to be encoded. Sequence can be a string or (pretokenized string).
243
+ audio (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
244
+ The audio to be prepared. Audio can be a single-channel (1-dimensional) NumPy array or PyTorch tensor.
245
+ audios (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
246
+ A list or two dimensional array of audio to be prepared.
247
+ sampling_rate (`int`, *optional*, defaults to 16000):
248
+ Sampling rate of the input audio. We expect 16kHz audio. Don't change this value unless you know what
249
+ you are doing.
250
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
251
+ If set, will return tensors of a particular framework. Acceptable values are:
252
+
253
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
254
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
255
+ - `'np'`: Return NumPy `np.ndarray` objects.
256
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
257
+
258
+ Returns:
259
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
260
+
261
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
262
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
263
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
264
+ `None`).
265
+ - **audio_values** -- Processed audio values to be fed to a model. Returned when `audio` is not `None`.
266
+ - **audio_token_len** -- Predicted number of audio frames: this value is guaranteed to be a close upper bound.
267
+ Returned when `audio` is not `None`.
268
+ - **audio_token_start_idx** -- The index in the tokenized text where the audio starts. Returned when `audio` is not `None`.
269
+ """
270
+ # TODO: Add support for multiple text inputs.
271
+ if audio is not None and audios is not None:
272
+ raise ValueError("Only one of `audio` or `audios` should be provided.")
273
+ elif audio is not None:
274
+ audios = audio if isinstance(audio, list) or audio.ndim == 2 else [audio]
275
+ elif audios is None:
276
+ audios = []
277
+
278
+ data = {}
279
+ audio_is_continuation = []
280
+ if len(audios) > 0:
281
+ audios = [x.numpy() if isinstance(x, torch.Tensor) else x for x in audios]
282
+
283
+ # Pad out each audio to at least 2 hops (the minimum required by the processor).
284
+ hop_length = self.audio_processor.feature_extractor.hop_length
285
+ audios = [
286
+ (
287
+ np.pad(x, (0, 2 * hop_length - len(x)), mode="constant")
288
+ if len(x) < 2 * hop_length
289
+ else x
290
+ )
291
+ for x in audios
292
+ ]
293
+
294
+ # Main audio processing. The processor is model-specific.
295
+ x: transformers.BatchFeature = self.audio_processor(
296
+ audios,
297
+ sampling_rate=sampling_rate,
298
+ padding="longest",
299
+ pad_to_multiple_of=hop_length, # The attention mask effectively gets padded to the hop length, so pad the audio to be consistent.
300
+ truncation=False,
301
+ return_attention_mask=True,
302
+ **kwargs,
303
+ )
304
+
305
+ data.update(
306
+ self._chunk_and_pad_audio(
307
+ audio_values=torch.as_tensor(
308
+ x.input_features if "input_features" in x else x.input_values
309
+ ),
310
+ audio_lens=torch.as_tensor(x.attention_mask).sum(-1),
311
+ include_audio_num_chunks=include_audio_num_chunks,
312
+ )
313
+ )
314
+
315
+ audio_is_continuation = data.pop("audio_is_continuation")
316
+ data["audio_token_len"] = torch.ceil(
317
+ data["audio_lens"] / (self.encoder_ds_factor * self.stack_factor)
318
+ ).to(dtype=torch.int)
319
+
320
+ if text is not None:
321
+ if not isinstance(text, str):
322
+ raise ValueError("Text must be a string. Batch mode not supported yet.")
323
+
324
+ # Special tokens like BOS should already have been added by the caller.
325
+ tokenized_parts = self.tokenizer(
326
+ text.split(
327
+ "<|audio|>" # The placeholder isn't part of the vocabulary, so split the text around it.
328
+ ),
329
+ add_special_tokens=False,
330
+ **kwargs,
331
+ )
332
+
333
+ audio_token_start_idx = []
334
+ placeholder_index = -1
335
+ split_input_ids = tokenized_parts["input_ids"]
336
+ input_ids: List[int] = []
337
+
338
+ audio_replacement_token_id = self.vocab[self.audio_token_replacement]
339
+
340
+ for i, token_len in enumerate(data.get("audio_token_len", [])):
341
+ if not audio_is_continuation[i]:
342
+ placeholder_index += 1
343
+ if placeholder_index >= len(split_input_ids):
344
+ raise ValueError(
345
+ f"Text contains too few audio placeholders. (Expected {len(audios)} placeholders)"
346
+ )
347
+
348
+ input_ids.extend(split_input_ids[placeholder_index])
349
+
350
+ audio_token_start_idx.append(len(input_ids))
351
+
352
+ input_ids.extend([audio_replacement_token_id] * token_len)
353
+
354
+ # Include any tokens after the last audio.
355
+ placeholder_index += 1
356
+ if placeholder_index != len(split_input_ids) - 1:
357
+ raise ValueError(
358
+ f"Text contains too many audio placeholders. (Expected {len(audios)} placeholders)"
359
+ )
360
+ input_ids.extend(split_input_ids[placeholder_index])
361
+
362
+ if "audio_token_len" in data:
363
+ data["audio_token_start_idx"] = torch.as_tensor(audio_token_start_idx)
364
+
365
+ data["input_ids"] = [input_ids]
366
+ data["attention_mask"] = [[1] * len(input_ids)]
367
+
368
+ # Ensure that there are no audio placeholders after the last audio.
369
+
370
+ return transformers.BatchFeature(data=data, tensor_type=return_tensors)
371
+
372
+ def batch_decode(self, *args, **kwargs):
373
+ return self.tokenizer.batch_decode(*args, **kwargs)
374
+
375
+ def decode(self, *args, **kwargs):
376
+ return self.tokenizer.decode(*args, **kwargs)
377
+
378
+ @property
379
+ def model_input_names(self):
380
+ tokenizer_input_names = self.tokenizer.model_input_names
381
+ audio_processor_input_names = self.audio_processor.model_input_names
382
+ return list(set(tokenizer_input_names + audio_processor_input_names))
383
+
384
+
385
+ UltravoxProcessor.register_for_auto_class()
386
+
387
+ 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]