zqhuang commited on
Commit
89060ea
·
verified ·
1 Parent(s): c21aec2

Upload UltravoxPipeline

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