alex-ht commited on
Commit
24d5d7b
1 Parent(s): 4cf7f1f

first commit

Browse files
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "UltravoxModel"
4
+ ],
5
+ "audio_model_id": "AlexHung29629/wav2vec2-lv-60-espeak-cv-ft",
6
+ "auto_map": {
7
+ "AutoConfig": "ultravox_config.UltravoxConfig",
8
+ "AutoModel": "ultravox_model.UltravoxModel",
9
+ "AutoProcessor": "ultravox_processing.UltravoxProcessor"
10
+ },
11
+ "custom_pipelines": {
12
+ "ultravox-pipeline": {
13
+ "impl": "ultravox_pipeline.UltravoxPipeline",
14
+ "pt": [
15
+ "AutoModel"
16
+ ],
17
+ "tf": [],
18
+ "type": "multimodal"
19
+ }
20
+ },
21
+ "hidden_size": 4096,
22
+ "ignore_index": -100,
23
+ "initializer_range": 0.02,
24
+ "model_type": "ultravox",
25
+ "norm_init": 0.4,
26
+ "pad_token_id": 128009,
27
+ "projector_act": "swiglu",
28
+ "stack_factor": 8,
29
+ "text_model_id": "voidful/Llama-3.2-8B-Instruct",
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.46.2",
32
+ "vocab_size": 128256
33
+ }
generation_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 128000,
4
+ "eos_token_id": [
5
+ 128001,
6
+ 128008,
7
+ 128009
8
+ ],
9
+ "pad_token_id": 128009,
10
+ "transformers_version": "4.46.2"
11
+ }
ultravox_config.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
23
+
24
+ class LossFunction(str, Enum):
25
+ CrossEntropy = "ce"
26
+ KL_Divergence = "kl"
27
+
28
+
29
+ @dataclasses.dataclass
30
+ class LossConfig:
31
+ loss_function: LossFunction = LossFunction.CrossEntropy
32
+ kl_temperature: float = 2.0
33
+
34
+ @property
35
+ def requires_alt_fields(self):
36
+ return self.loss_function == LossFunction.KL_Divergence
37
+
38
+
39
+ class UltravoxConfig(transformers.PretrainedConfig):
40
+ r"""
41
+ This is the configuration class to store the configuration of a [`UltravoxForConditionalGeneration`]. It is used to instantiate an
42
+ Ultravox model according to the specified arguments, defining the model architecture.
43
+
44
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
45
+ documentation from [`PretrainedConfig`] for more information.
46
+
47
+ Args:
48
+ audio_config (`Wav2Vec2Config`, *optional*):
49
+ Custom audio config or dict
50
+ text_config (`Union[AutoConfig, dict]`, *optional*):
51
+ The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`.
52
+ ignore_index (`int`, *optional*, defaults to -100):
53
+ The ignore index for the loss function.
54
+ audio_token_index (`int`, *optional*, defaults to 32000):
55
+ The audio token index to encode the audio prompt.
56
+ stack_factor (`int`, *optional*, defaults to 8):
57
+ Audio downsampling factor for the multimodal projector.
58
+ norm_init (`float`, *optional*, defaults to 0.4):
59
+ The initialization value for the layer normalization.
60
+ projector_act (`str`, *optional*, defaults to `"swiglu"`):
61
+ The activation function used by the multimodal projector.
62
+ text_model_lora_config (`LoraConfigSimplified`, *optional*):
63
+ The LoRA configuration for finetuning the text model.
64
+ audio_model_lora_config (`LoraConfigSimplified`, *optional*):
65
+ The LoRA configuration for finetuning the audio model.
66
+
67
+
68
+ Example:
69
+
70
+ ```python
71
+ >>> from transformers import UltravoxForConditionalGeneration, Wav2Vec2Config, UltravoxConfig, LlamaConfig
72
+
73
+ >>> # Initializing an audio encoder config
74
+ >>> audio_config = Wav2Vec2Config()
75
+
76
+ >>> # Initializing a Llama config
77
+ >>> text_config = LlamaConfig()
78
+
79
+ >>> # Initializing a default configuration
80
+ >>> configuration = UltravoxConfig(audio_config, text_config)
81
+
82
+ >>> # Initializing a completely untrained model from the configuration
83
+ >>> model = UltravoxForConditionalGeneration(configuration)
84
+
85
+ >>> # Accessing the model configuration
86
+ >>> configuration = model.config
87
+
88
+ >>> # Initialize a model from pretrained checkpoints and random projector weights
89
+ >>> config = UltravoxConfig(audio_model_id="facebook/wav2vec2-base-960h", text_model_id="meta-llama/Llama-2-7b-chat-hf")
90
+ ```"""
91
+
92
+ model_type = "ultravox"
93
+ is_composition = False
94
+
95
+ def __init__(
96
+ self,
97
+ audio_config: Optional[Dict[str, Any]] = None,
98
+ text_config: Optional[Dict[str, Any]] = None,
99
+ audio_model_id: Optional[str] = None,
100
+ text_model_id: Optional[str] = None,
101
+ ignore_index: int = -100,
102
+ hidden_size: int = 4096,
103
+ stack_factor: int = 8,
104
+ norm_init: float = 0.4,
105
+ projector_act: str = "swiglu",
106
+ text_model_lora_config: Optional[LoraConfigSimplified] = None,
107
+ audio_model_lora_config: Optional[LoraConfigSimplified] = None,
108
+ **kwargs,
109
+ ):
110
+ self.ignore_index = ignore_index
111
+
112
+ self.audio_model_id = audio_model_id
113
+ self.text_model_id = text_model_id
114
+
115
+ self.hidden_size = hidden_size
116
+ self.stack_factor = stack_factor
117
+ self.norm_init = norm_init
118
+ self.projector_act = projector_act
119
+
120
+ if text_model_id is not None:
121
+ self.text_config: transformers.LlamaConfig = (
122
+ transformers.AutoConfig.from_pretrained(text_model_id)
123
+ )
124
+ else:
125
+ text_config = text_config or {}
126
+ self.text_config = transformers.CONFIG_MAPPING[
127
+ text_config.get("model_type", "llama")
128
+ ](**text_config)
129
+
130
+ if audio_model_id is not None:
131
+ self.audio_config: transformers.PretrainedConfig = (
132
+ transformers.AutoConfig.from_pretrained(audio_model_id)
133
+ )
134
+ else:
135
+ audio_config = audio_config or {}
136
+ self.audio_config = transformers.CONFIG_MAPPING[
137
+ audio_config.get("model_type", "wav2vec2")
138
+ ](**audio_config)
139
+
140
+ self.text_model_lora_config = (
141
+ text_model_lora_config
142
+ if isinstance(text_model_lora_config, dict)
143
+ else dataclasses.asdict(text_model_lora_config or LoraConfigSimplified())
144
+ )
145
+ self.audio_model_lora_config = (
146
+ audio_model_lora_config
147
+ if isinstance(audio_model_lora_config, dict)
148
+ else dataclasses.asdict(audio_model_lora_config or LoraConfigSimplified())
149
+ )
150
+
151
+ self.vocab_size = self.text_config.vocab_size
152
+
153
+ self.initializer_range = self.text_config.initializer_range
154
+
155
+ super().__init__(**kwargs)
156
+
157
+ def to_diff_dict(self) -> Dict[str, Any]:
158
+ diff_dict = super().to_diff_dict()
159
+
160
+ # remove text_config and audio_config if text_model_id and audio_model_id are present
161
+ if self.text_model_id is not None:
162
+ diff_dict.pop("text_config", None)
163
+ if self.audio_model_id is not None:
164
+ diff_dict.pop("audio_config", None)
165
+
166
+ return diff_dict
ultravox_model.py ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Any, Dict, Optional, Set, Tuple, Union
3
+
4
+ import peft
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ import transformers
9
+ import transformers.activations
10
+ import transformers.modeling_outputs
11
+ import transformers.models
12
+ from transformers.models.whisper import modeling_whisper as whisper
13
+
14
+ # We must use relative import in this directory to allow uploading to HF Hub
15
+ # Even "from . import X" pattern doesn't work (undocumented and unclear why)
16
+ from .ultravox_config import LossConfig
17
+ from .ultravox_config import LossFunction
18
+ from .ultravox_config import UltravoxConfig
19
+
20
+
21
+ class UltravoxModel(transformers.LlamaPreTrainedModel):
22
+ """
23
+ The Ultravox model which consists of an audio encoder and a language model.
24
+ Audio input is processed by the audio encoder, then every `stack_factor` frames are stacked together and
25
+ projected to the language model's embedding space using a few linear layers.
26
+ The text is embedded by the language model as usual and then the audio and text embeddings are merged together.
27
+ A special token `<|audio|>` is used to indicate the start of the audio embeddings in the merged embeddings.
28
+ Parameters:
29
+ config: Model configuration class with all the parameters of the model.
30
+ """
31
+
32
+ config_class = UltravoxConfig
33
+ config: UltravoxConfig # for type hinting
34
+ # Usually we load encoder and LLM weights from a pretrained model separately, so they are allowed to be missing
35
+ _keys_to_ignore_on_load_missing = ["audio_tower.*", "language_model.*"]
36
+
37
+ def __init__(self, config: UltravoxConfig):
38
+ super().__init__(config)
39
+ self._register_load_state_dict_pre_hook(self._pre_load_state_dict_hook)
40
+
41
+ self.keep_params: Set[str] = set()
42
+ self.vocab_size = config.vocab_size
43
+
44
+ self.audio_tower = self._create_audio_tower(config)
45
+ self.multi_modal_projector = self._create_multi_modal_projector(config)
46
+ self.language_model = self._create_language_model(config)
47
+
48
+ # Determine no_split_modules dynamically to use with FSDP auto_wrap policy.
49
+ # FSDP throws an error if some of the layer types are not found in the model.
50
+ # This would be something like ["LlamaDecoderLayer", "WhisperEncoderLayer"]
51
+ self._no_split_modules = (self.language_model._no_split_modules or []) + (
52
+ self.audio_tower._no_split_modules or []
53
+ )
54
+
55
+ self.loss_config = LossConfig()
56
+ self.post_init()
57
+
58
+ def get_input_embeddings(self):
59
+ return self.language_model.get_input_embeddings()
60
+
61
+ def set_input_embeddings(self, value):
62
+ self.language_model.set_input_embeddings(value)
63
+
64
+ def get_output_embeddings(self):
65
+ return self.language_model.get_output_embeddings()
66
+
67
+ def set_output_embeddings(self, new_embeddings):
68
+ self.language_model.set_output_embeddings(new_embeddings)
69
+
70
+ def set_decoder(self, decoder):
71
+ self.language_model.set_decoder(decoder)
72
+
73
+ def get_decoder(self):
74
+ return self.language_model.get_decoder()
75
+
76
+ def tie_weights(self):
77
+ return self.language_model.tie_weights()
78
+
79
+ def set_loss_config(self, loss_config: LossConfig):
80
+ self.loss_config = loss_config
81
+
82
+ def _setup_cache(
83
+ self, cache_cls, max_batch_size: int, max_cache_len: Optional[int] = None
84
+ ):
85
+ self.language_model._setup_cache(cache_cls, max_batch_size, max_cache_len)
86
+
87
+ def _reorder_cache(self, past_key_values, beam_idx):
88
+ return self.language_model._reorder_cache(past_key_values, beam_idx)
89
+
90
+ def resize_token_embeddings(
91
+ self,
92
+ new_num_tokens: Optional[int] = None,
93
+ pad_to_multiple_of: Optional[int] = None,
94
+ ) -> nn.Embedding:
95
+ model_embeds = self.language_model.resize_token_embeddings(
96
+ new_num_tokens, pad_to_multiple_of
97
+ )
98
+ # update vocab size
99
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
100
+ self.config.vocab_size = model_embeds.num_embeddings
101
+ self.vocab_size = model_embeds.num_embeddings
102
+ return model_embeds
103
+
104
+ def _compute_kl_loss(
105
+ self,
106
+ lm_output: transformers.modeling_outputs.CausalLMOutputWithPast,
107
+ labels: Optional[torch.Tensor] = None,
108
+ past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
109
+ alt_input_ids: Optional[torch.Tensor] = None,
110
+ alt_attention_mask: Optional[torch.Tensor] = None,
111
+ alt_labels: Optional[torch.Tensor] = None,
112
+ **kwargs,
113
+ ):
114
+ # disable gradient computation for the teacher model
115
+ with torch.no_grad():
116
+ # compute the teacher (text-only) model's distribution
117
+ alt_inputs_embeds = self.get_input_embeddings().forward(alt_input_ids)
118
+ alt_lm_output = self.language_model.forward(
119
+ inputs_embeds=alt_inputs_embeds,
120
+ labels=alt_labels,
121
+ attention_mask=alt_attention_mask,
122
+ past_key_values=past_key_values,
123
+ **kwargs,
124
+ )
125
+ # compute the KL divergence loss between the two models
126
+ kl_loss = F.kl_div(
127
+ F.log_softmax(
128
+ lm_output.logits[labels != -100] / self.loss_config.kl_temperature,
129
+ dim=-1,
130
+ ),
131
+ F.softmax(
132
+ alt_lm_output.logits[alt_labels != -100]
133
+ / self.loss_config.kl_temperature,
134
+ dim=-1,
135
+ ),
136
+ reduction="batchmean",
137
+ )
138
+ return {"loss": kl_loss}
139
+
140
+ def forward(
141
+ self,
142
+ input_ids: torch.Tensor,
143
+ audio_values: Optional[torch.FloatTensor] = None,
144
+ inputs_embeds: Optional[torch.FloatTensor] = None,
145
+ labels: Optional[torch.Tensor] = None,
146
+ attention_mask: Optional[torch.Tensor] = None,
147
+ audio_token_start_idx: Optional[torch.Tensor] = None,
148
+ audio_len: Optional[torch.Tensor] = None,
149
+ audio_token_len: Optional[torch.Tensor] = None,
150
+ past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
151
+ # the alt_* fields are needed for KL divergence loss
152
+ alt_input_ids: Optional[torch.Tensor] = None,
153
+ alt_attention_mask: Optional[torch.Tensor] = None,
154
+ alt_labels: Optional[torch.Tensor] = None,
155
+ **kwargs,
156
+ ) -> Union[Tuple, transformers.modeling_outputs.CausalLMOutputWithPast]:
157
+ """
158
+ Forward pass for the Ultravox model.
159
+ `input_ids` are the tokenized text input. They are embedded by the language model as usual.
160
+ `audio_values` are processed by the audio encoder and then every `stack_factor` frames are stacked together and
161
+ projected to the language model's embedding space using a few linear layers.
162
+ The audio and text embeddings are merged together. A special token `<|audio|>` is used to indicate the start
163
+ of the audio embeddings in the merged embeddings.
164
+ Args:
165
+ input_ids: The tokenized text input.
166
+ audio_values: The processed audio values.
167
+ inputs_embeds: The embeddings for the input tokens.
168
+ labels: The tokenized text labels.
169
+ attention_mask: The attention mask for the input.
170
+ position_ids: The position ids for the input.
171
+ past_key_values: The past key value cache for the language model attention layers.
172
+ **kwargs: Additional keyword arguments. Passed directly to the language model.
173
+ """
174
+ if inputs_embeds is None:
175
+ # B x T -> B x T x D
176
+ inputs_embeds = self.get_input_embeddings().forward(input_ids)
177
+
178
+ if audio_values is not None:
179
+ assert (
180
+ audio_token_start_idx is not None and audio_token_len is not None
181
+ ), "audio_token_start_idx and audio_token_len must be provided if audio_values are provided."
182
+ assert (
183
+ len(audio_token_start_idx) == len(audio_token_len) == len(audio_values)
184
+ ), "audio_token_start_idx, audio_token_len, and audio_values must have the same batch size."
185
+
186
+ # B x A/3200 x D
187
+ audio_tower_output = self.audio_tower.forward(
188
+ audio_values.to(self.audio_tower.dtype),
189
+ audio_len = audio_len
190
+ ).last_hidden_state
191
+ audio_tower_output = audio_tower_output.to(inputs_embeds.dtype)
192
+
193
+ audio_embeds = self.multi_modal_projector.forward(audio_tower_output)
194
+
195
+ # combine audio and text embeddings
196
+ for i, (audio, start, length) in enumerate(
197
+ zip(audio_embeds, audio_token_start_idx, audio_token_len)
198
+ ):
199
+ assert length <= audio.shape[0]
200
+ inputs_embeds[i, start : start + length].copy_(audio[:length])
201
+
202
+
203
+ lm_output = self.language_model.forward(
204
+ inputs_embeds=inputs_embeds,
205
+ labels=labels,
206
+ attention_mask=attention_mask,
207
+ past_key_values=past_key_values,
208
+ **kwargs,
209
+ )
210
+ if self.training:
211
+ if self.loss_config.loss_function == LossFunction.CrossEntropy:
212
+ return lm_output
213
+ elif self.loss_config.loss_function == LossFunction.KL_Divergence:
214
+ return self._compute_kl_loss(
215
+ lm_output=lm_output,
216
+ labels=labels,
217
+ past_key_values=past_key_values,
218
+ alt_input_ids=alt_input_ids,
219
+ alt_attention_mask=alt_attention_mask,
220
+ alt_labels=alt_labels,
221
+ **kwargs,
222
+ )
223
+ else:
224
+ raise ValueError(
225
+ f"Unsupported loss function: {self.loss_config.loss_function}"
226
+ )
227
+ else:
228
+ return lm_output
229
+
230
+ def prepare_inputs_for_generation(
231
+ self,
232
+ input_ids: torch.Tensor,
233
+ audio_values: Optional[torch.FloatTensor] = None,
234
+ audio_token_start_idx: Optional[torch.Tensor] = None,
235
+ audio_token_len: Optional[torch.Tensor] = None,
236
+ audio_len: Optional[torch.Tensor] = None,
237
+ past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
238
+ attention_mask: Optional[torch.Tensor] = None,
239
+ inputs_embeds: Optional[torch.Tensor] = None,
240
+ cache_position: Optional[torch.Tensor] = None,
241
+ **kwargs,
242
+ ) -> Dict[str, Any]:
243
+ model_input = self.language_model.prepare_inputs_for_generation(
244
+ input_ids=input_ids,
245
+ past_key_values=past_key_values,
246
+ attention_mask=attention_mask,
247
+ inputs_embeds=inputs_embeds,
248
+ cache_position=cache_position,
249
+ **kwargs,
250
+ )
251
+
252
+ # include audio information in model_input only when it is needed during prefilling
253
+ # audio_token_start_idx should always be relative to the current cache position
254
+ prefill_start_idx = 0 if cache_position is None else cache_position[0]
255
+ if (
256
+ audio_values is not None
257
+ and audio_token_start_idx is not None
258
+ and prefill_start_idx <= torch.max(audio_token_start_idx)
259
+ ):
260
+ model_input["audio_values"] = audio_values
261
+ model_input["audio_token_start_idx"] = (
262
+ audio_token_start_idx - prefill_start_idx
263
+ )
264
+ model_input["audio_token_len"] = audio_token_len
265
+ model_input["audio_len"] = audio_len
266
+
267
+ return model_input
268
+
269
+ @classmethod
270
+ def _create_multi_modal_projector(
271
+ cls, config: UltravoxConfig
272
+ ) -> "UltravoxProjector":
273
+ projector = UltravoxProjector(config)
274
+ projector.to(config.torch_dtype)
275
+ return projector
276
+
277
+ @classmethod
278
+ def _create_audio_tower(
279
+ cls, config: UltravoxConfig
280
+ ) -> Union[transformers.Wav2Vec2Model, "ModifiedWhisperEncoder"]:
281
+ if config.audio_model_id is not None:
282
+ if "whisper" in config.audio_model_id is not None:
283
+ audio_tower = ModifiedWhisperEncoder.from_pretrained(
284
+ config.audio_model_id, torch_dtype=config.torch_dtype
285
+ )
286
+ else:
287
+ audio_tower = transformers.AutoModel.from_pretrained(
288
+ config.audio_model_id, torch_dtype=config.torch_dtype
289
+ )
290
+ else:
291
+ if "whisper" in config.audio_config._name_or_path:
292
+ audio_tower = ModifiedWhisperEncoder(config.audio_config)
293
+ else:
294
+ with transformers.modeling_utils.no_init_weights():
295
+ # we only ever use from_config if the weights are retrained, hence initializing is not
296
+ # required. This makes the model quite creation faster since init on CPU is quite slow.
297
+ audio_tower = transformers.AutoModel.from_config(
298
+ config.audio_config
299
+ )
300
+
301
+ if isinstance(
302
+ audio_tower,
303
+ (transformers.Wav2Vec2BertModel, transformers.WhisperModel),
304
+ ):
305
+ # For these models we only need the encoder part
306
+ # Wav2Vec2BertModel -> Wav2Vec2BertEncoder
307
+ # WhisperModel -> WhisperEncoder
308
+ audio_tower = audio_tower.encoder
309
+
310
+ audio_tower = apply_lora(audio_tower, config.audio_model_lora_config)
311
+ return audio_tower
312
+
313
+ @classmethod
314
+ def _create_language_model(
315
+ cls, config: UltravoxConfig
316
+ ) -> transformers.LlamaForCausalLM:
317
+ if config.text_model_id is not None:
318
+ language_model = transformers.AutoModelForCausalLM.from_pretrained(
319
+ config.text_model_id,
320
+ attn_implementation=config._attn_implementation,
321
+ torch_dtype=config.torch_dtype,
322
+ )
323
+ else:
324
+ with transformers.modeling_utils.no_init_weights():
325
+ # we only ever use from_config if the weights are retrained, hence initializing is not
326
+ # required. This makes the model quite creation faster since init on CPU is quite slow.
327
+ language_model = transformers.AutoModelForCausalLM.from_config(
328
+ config.text_config,
329
+ attn_implementation=config._attn_implementation,
330
+ torch_dtype=config.torch_dtype,
331
+ )
332
+
333
+ language_model = apply_lora(language_model, config.text_model_lora_config)
334
+ return language_model
335
+
336
+ def merge_and_unload(self):
337
+ if isinstance(self.language_model, peft.PeftModel):
338
+ self.language_model = self.language_model.merge_and_unload()
339
+ # no need to download base language model weights anymore, so we can remove the id
340
+ self.config.text_model_id = None
341
+ self.keep_params.update(
342
+ set(
343
+ [
344
+ f"language_model.{name}"
345
+ for name, _ in self.language_model.named_parameters()
346
+ ]
347
+ )
348
+ )
349
+
350
+ if isinstance(self.audio_tower, peft.PeftModel):
351
+ self.audio_tower = self.audio_tower.merge_and_unload()
352
+ # no need to download base audio model weights anymore, so we can remove the id
353
+ self.config.audio_model_id = None
354
+ self.keep_params.update(
355
+ set(
356
+ [
357
+ f"audio_tower.{name}"
358
+ for name, _ in self.audio_tower.named_parameters()
359
+ ]
360
+ )
361
+ )
362
+
363
+ for param in ["text_model_lora_config", "audio_model_lora_config"]:
364
+ if hasattr(self.config, param):
365
+ delattr(self.config, param)
366
+
367
+ def push_to_hub(self, *args, **kwargs):
368
+ self.merge_and_unload()
369
+ self.to(self.language_model.dtype)
370
+ return super().push_to_hub(*args, **kwargs)
371
+
372
+ def save_pretrained(
373
+ self, *args, state_dict: Optional[Dict[str, Any]] = None, **kwargs
374
+ ):
375
+ if state_dict is None:
376
+ state_dict = super().state_dict()
377
+
378
+ named_params = dict(self.named_parameters())
379
+
380
+ state_dict = {
381
+ k: v
382
+ for k, v in state_dict.items()
383
+ if k in self.keep_params
384
+ or (k in named_params and named_params[k].requires_grad)
385
+ }
386
+
387
+ super().save_pretrained(*args, state_dict=state_dict, **kwargs)
388
+
389
+ def _pre_load_state_dict_hook(self, state_dict: Dict[str, Any], *args, **kwargs):
390
+ self.keep_params.update(set(state_dict.keys()))
391
+
392
+ def print_trainable_parameters(self):
393
+ """
394
+ Prints the number of trainable parameters in the model (reuses Peft model's method)
395
+ """
396
+ count_params = peft.peft_model.PeftModel.get_nb_trainable_parameters
397
+
398
+ trainable_params, all_param = count_params(self)
399
+
400
+ logging.info(
401
+ f"trainable params: {trainable_params:,d} || all params: {all_param:,d}"
402
+ f" || trainable%: {100 * trainable_params / all_param:.1f}%"
403
+ )
404
+
405
+ lm_trainable_params, lm_all_params = count_params(self.language_model)
406
+ audio_trainable_params, audio_all_params = count_params(self.audio_tower)
407
+
408
+ projector_trainable_params = (
409
+ trainable_params - lm_trainable_params - audio_trainable_params
410
+ )
411
+ projector_all_params = all_param - lm_all_params - audio_all_params
412
+
413
+ logging.info(
414
+ f"Trainable%: "
415
+ f" LLM: {100 * lm_trainable_params / lm_all_params:.1f}%"
416
+ f" || Audio Encoder: {100 * audio_trainable_params / audio_all_params:.1f}%"
417
+ f" || Projector: {100 * projector_trainable_params / projector_all_params:.1f}%"
418
+ )
419
+
420
+
421
+ def is_cache_empty(
422
+ past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]]
423
+ ) -> bool:
424
+ """
425
+ Check if the cache is empty.
426
+ """
427
+ if past_key_values is None:
428
+ return True
429
+ if isinstance(past_key_values, tuple):
430
+ return all(len(c) == 0 for c in past_key_values)
431
+ return past_key_values.get_seq_length() == 0
432
+
433
+
434
+ def apply_lora(model: torch.nn.Module, lora_config: dict) -> torch.nn.Module:
435
+ """
436
+ Applies LoRA finetuning to the model. If the `r` parameter is set to 0, the model is frozen instead.
437
+ """
438
+ lora_config = peft.LoraConfig(**lora_config or {})
439
+
440
+ if lora_config.r == 0:
441
+ # freeze the model entirely
442
+ for param in model.parameters():
443
+ param.requires_grad = False
444
+ else:
445
+ model = peft.get_peft_model(model, lora_config)
446
+
447
+ return model
448
+
449
+
450
+ class StackAudioFrames(nn.Module):
451
+ """
452
+ Stack the audio embedding frames to reduce the sequence length by a factor of `stack_factor`.
453
+ The number of output frames will be `ceil(T / stack_factor) + 1` where `T` is the number of input frames.
454
+ NOTE: the extra +1 is intentional: in case the number of audio tokens are over-estimated by the processor,
455
+ we want to make sure `processor.audio_token_replacement` (i.e. EOS) doesn't get leaked into the middle of embeddings.
456
+ In most cases this extra padding will get removed in the model's forward function so it has no effect.
457
+ """
458
+
459
+ def __init__(self, stack_factor: int = 8):
460
+ super().__init__()
461
+ self.stack_factor = stack_factor
462
+
463
+ def forward(self, audio_embeds: torch.Tensor) -> torch.Tensor:
464
+ B, T, C = audio_embeds.shape
465
+ T_pad = (T + self.stack_factor - 1) // self.stack_factor * self.stack_factor
466
+ audio_embeds = F.pad(audio_embeds, (0, 0, 0, T_pad - T + self.stack_factor))
467
+ B, T, C = audio_embeds.shape
468
+ audio_embeds = audio_embeds.view(
469
+ B, T // self.stack_factor, C * self.stack_factor
470
+ )
471
+ return audio_embeds
472
+
473
+
474
+ class RMSNorm(transformers.models.llama.modeling_llama.LlamaRMSNorm):
475
+ def __init__(self, hidden_size: int, init: float = 1, eps: float = 1e-6):
476
+ super().__init__(hidden_size=hidden_size, eps=eps)
477
+ self.weight.data.fill_(init)
478
+
479
+
480
+ class SwiGLU(nn.Module):
481
+ def forward(self, x):
482
+ x, gate = x.chunk(2, dim=-1)
483
+ return F.silu(gate) * x
484
+
485
+
486
+ class UltravoxProjector(nn.Sequential):
487
+ def __init__(self, config: UltravoxConfig):
488
+ super().__init__()
489
+ self.hidden_dim = config.hidden_size
490
+ self._pad_and_stack = StackAudioFrames(config.stack_factor)
491
+ dim = config.audio_config.hidden_size * config.stack_factor
492
+ self.ln_pre = RMSNorm(dim, init=config.norm_init)
493
+ self.linear_1 = nn.Linear(dim, self.hidden_dim, bias=False)
494
+ dim = self.hidden_dim
495
+ self.act = transformers.activations.get_activation(config.projector_act)
496
+ dim = dim // 2 if config.projector_act == "swiglu" else dim
497
+ self.linear_2 = nn.Linear(dim, config.text_config.hidden_size, bias=False)
498
+ self.ln_post = RMSNorm(config.text_config.hidden_size, init=config.norm_init)
499
+
500
+ def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
501
+ audio_features = self._pad_and_stack(audio_features)
502
+ audio_features = self.ln_pre(audio_features)
503
+ hidden_states = self.linear_1(audio_features)
504
+ hidden_states = self.act(hidden_states)
505
+ hidden_states = self.linear_2(hidden_states)
506
+ hidden_states = self.ln_post(hidden_states)
507
+ return hidden_states
508
+
509
+
510
+ class ModifiedWhisperEncoder(whisper.WhisperEncoder, transformers.modeling_utils.ModuleUtilsMixin):
511
+ """
512
+ Encoder portion of OpenAI's Whisper model.
513
+ This implementation is a slightly modified version of HF Transformers' Whisper Encoder, with only a few fixes:
514
+ 1. base_model_prefix updated to allow for doing `.from_pretrained` directly on the encoder
515
+ 2. allow less than 30 second of audio padding to be passed in:
516
+ - relaxed ValueError check for `input_features` length to be less than or equal to `expected_seq_length` instead of strictly equal
517
+ - embed_pos is now sliced to match the length of `inputs_embeds`
518
+ Original: https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py
519
+ """
520
+
521
+ base_model_prefix = "model.encoder"
522
+ _no_split_modules = ["WhisperEncoderLayer"]
523
+
524
+ def forward(
525
+ self,
526
+ input_features,
527
+ audio_len=None,
528
+ head_mask=None,
529
+ output_attentions=None,
530
+ output_hidden_states=None,
531
+ return_dict=None,
532
+ ):
533
+ expected_seq_length = (
534
+ self.config.max_source_positions
535
+ * self.conv1.stride[0]
536
+ * self.conv2.stride[0]
537
+ )
538
+ if input_features.shape[-1] > expected_seq_length:
539
+ raise ValueError(
540
+ 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}."
541
+ )
542
+
543
+ output_attentions = (
544
+ output_attentions
545
+ if output_attentions is not None
546
+ else self.config.output_attentions
547
+ )
548
+ output_hidden_states = (
549
+ output_hidden_states
550
+ if output_hidden_states is not None
551
+ else self.config.output_hidden_states
552
+ )
553
+ return_dict = (
554
+ return_dict if return_dict is not None else self.config.use_return_dict
555
+ )
556
+ inputs_embeds = nn.functional.gelu(self.conv1(input_features))
557
+ inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
558
+
559
+ inputs_embeds = inputs_embeds.permute(0, 2, 1)
560
+ embed_pos = self.embed_positions.weight[: inputs_embeds.size(-2)]
561
+
562
+ hidden_states = inputs_embeds + embed_pos
563
+ hidden_states = nn.functional.dropout(
564
+ hidden_states, p=self.dropout, training=self.training
565
+ )
566
+
567
+ encoder_states = () if output_hidden_states else None
568
+ all_attentions = () if output_attentions else None
569
+
570
+ attention_mask = None
571
+ if audio_len != None:
572
+ audio_feature_len = self._get_feat_extract_output_lengths(audio_len)
573
+ batch_size = hidden_states.shape[0]
574
+ max_seq_len = hidden_states.shape[1]
575
+ attention_mask = (
576
+ torch.arange(max_seq_len, device=hidden_states.device)[None, :]
577
+ .expand(batch_size, -1)
578
+ .lt(audio_feature_len.view(batch_size, 1))
579
+ )
580
+ attention_mask = self.get_extended_attention_mask(
581
+ attention_mask,
582
+ None,
583
+ device=hidden_states.device,
584
+ dtype=hidden_states.dtype,
585
+ )
586
+
587
+ # check if head_mask has a correct number of layers specified if desired
588
+ if head_mask is not None:
589
+ assert head_mask.size()[0] == (
590
+ len(self.layers)
591
+ ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
592
+
593
+ for idx, encoder_layer in enumerate(self.layers):
594
+ if output_hidden_states:
595
+ encoder_states = encoder_states + (hidden_states,)
596
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
597
+ to_drop = False
598
+ if self.training:
599
+ dropout_probability = torch.rand([])
600
+ if dropout_probability < self.layerdrop: # skip the layer
601
+ to_drop = True
602
+
603
+ if to_drop:
604
+ layer_outputs = (None, None)
605
+ else:
606
+ if self.gradient_checkpointing and self.training:
607
+ layer_outputs = self._gradient_checkpointing_func(
608
+ encoder_layer.__call__,
609
+ hidden_states,
610
+ attention_mask,
611
+ (head_mask[idx] if head_mask is not None else None),
612
+ output_attentions,
613
+ )
614
+ else:
615
+ layer_outputs = encoder_layer(
616
+ hidden_states,
617
+ attention_mask,
618
+ layer_head_mask=(
619
+ head_mask[idx] if head_mask is not None else None
620
+ ),
621
+ output_attentions=output_attentions,
622
+ )
623
+
624
+ hidden_states = layer_outputs[0]
625
+
626
+ if output_attentions:
627
+ all_attentions = all_attentions + (layer_outputs[1],)
628
+
629
+ hidden_states = self.layer_norm(hidden_states)
630
+ if output_hidden_states:
631
+ encoder_states = encoder_states + (hidden_states,)
632
+
633
+ if not return_dict:
634
+ return tuple(
635
+ v
636
+ for v in [hidden_states, encoder_states, all_attentions]
637
+ if v is not None
638
+ )
639
+ return transformers.modeling_outputs.BaseModelOutput(
640
+ last_hidden_state=hidden_states,
641
+ hidden_states=encoder_states,
642
+ attentions=all_attentions,
643
+ )
644
+
645
+
646
+ UltravoxConfig.register_for_auto_class()
647
+ UltravoxModel.register_for_auto_class()
648
+
649
+ transformers.AutoConfig.register("ultravox", UltravoxConfig)
650
+ transformers.AutoModel.register(UltravoxConfig, UltravoxModel)
651
+
652
+ transformers.activations.ACT2FN["swiglu"] = SwiGLU
ultravox_pipeline.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
12
+
13
+ class UltravoxPipeline(transformers.Pipeline):
14
+ def __init__(
15
+ self,
16
+ model: UltravoxModel,
17
+ tokenizer: Optional[transformers.PreTrainedTokenizerBase] = None,
18
+ audio_processor: Optional[transformers.ProcessorMixin] = None,
19
+ **kwargs
20
+ ):
21
+ if tokenizer is None:
22
+ try:
23
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
24
+ model.config._name_or_path
25
+ )
26
+ except:
27
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
28
+ model.config.text_model_id or model.config.text_config._name_or_path
29
+ )
30
+
31
+ if audio_processor is None:
32
+ audio_processor = transformers.AutoProcessor.from_pretrained(
33
+ model.config.audio_model_id or model.config.audio_config._name_or_path
34
+ )
35
+
36
+ super().__init__(model=model, tokenizer=tokenizer, **kwargs)
37
+
38
+ self.processor = UltravoxProcessor(
39
+ audio_processor=audio_processor,
40
+ tokenizer=tokenizer,
41
+ stack_factor=model.config.stack_factor,
42
+ )
43
+
44
+ def _sanitize_parameters(self, **kwargs):
45
+ generation_keys = ["temperature", "max_new_tokens", "repetition_penalty"]
46
+ generation_kwargs = {k: kwargs[k] for k in kwargs if k in generation_keys}
47
+ return {}, generation_kwargs, {}
48
+
49
+ def preprocess(self, inputs: Dict[str, Any]):
50
+ turns: list = inputs.get("turns", [])
51
+
52
+ audio = inputs.get("audio", None)
53
+ # Convert to float32 if needed.
54
+ if isinstance(audio, np.ndarray):
55
+ if audio.dtype == np.float64:
56
+ audio = audio.astype(np.float32)
57
+ elif audio.dtype == np.int16:
58
+ audio = audio.astype(np.float32) / np.float32(32768.0)
59
+ elif audio.dtype == np.int32:
60
+ audio = audio.astype(np.float32) / np.float32(2147483648.0)
61
+
62
+ if audio is not None and (len(turns) == 0 or turns[-1]["role"] != "user"):
63
+ prompt = inputs.get("prompt", "<|audio|>")
64
+ if "<|audio|>" not in prompt:
65
+ logging.warning(
66
+ "Prompt does not contain '<|audio|>', appending '<|audio|>' to the end of the prompt."
67
+ )
68
+
69
+ prompt += " <|audio|>"
70
+ turns.append({"role": "user", "content": prompt})
71
+
72
+ text = self.processor.tokenizer.apply_chat_template(
73
+ turns, add_generation_prompt=True, tokenize=False
74
+ )
75
+
76
+ if "sampling_rate" not in inputs and audio is not None:
77
+ logging.warning(
78
+ "No sampling rate provided, using default of 16kHz. We highly recommend providing the correct sampling rate."
79
+ )
80
+
81
+ output = self.processor(
82
+ text=text,
83
+ audio=audio,
84
+ sampling_rate=inputs.get("sampling_rate", 16000),
85
+ )
86
+ if "audio_values" in output:
87
+ output["audio_values"] = output["audio_values"].to(self.model.dtype)
88
+
89
+ return output
90
+
91
+ def _forward(
92
+ self,
93
+ model_inputs: Dict[str, Any],
94
+ temperature: Optional[float] = None,
95
+ max_new_tokens: Optional[int] = None,
96
+ repetition_penalty: float = 1.1,
97
+ ) -> List[int]:
98
+ temperature = temperature or None
99
+ do_sample = temperature is not None
100
+
101
+ terminators = [self.tokenizer.eos_token_id]
102
+ if "<|eot_id|>" in self.tokenizer.added_tokens_encoder:
103
+ terminators.append(self.tokenizer.convert_tokens_to_ids("<|eot_id|>"))
104
+
105
+ input_len = model_inputs["input_ids"].shape[1]
106
+
107
+ outputs = self.model.generate(
108
+ **model_inputs,
109
+ do_sample=do_sample,
110
+ temperature=temperature,
111
+ max_new_tokens=max_new_tokens,
112
+ repetition_penalty=repetition_penalty,
113
+ eos_token_id=terminators
114
+ )
115
+ return outputs[0][input_len:]
116
+
117
+ def postprocess(self, model_outputs) -> str:
118
+ output_text = self.tokenizer.decode(model_outputs, skip_special_tokens=True)
119
+ return output_text
120
+
121
+
122
+ transformers.pipelines.PIPELINE_REGISTRY.register_pipeline(
123
+ "ultravox-pipeline",
124
+ pipeline_class=UltravoxPipeline,
125
+ pt_model=transformers.AutoModel,
126
+ type="multimodal",
127
+ )
ultravox_processing.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+
3
+ import numpy as np
4
+ import torch
5
+ import transformers
6
+
7
+ from .ultravox_config import UltravoxConfig
8
+
9
+
10
+ class UltravoxProcessor(transformers.ProcessorMixin):
11
+ """
12
+ Constructs an Ultravox processor which wraps an audio processor and a tokenizer into a single processor.
13
+ Args:
14
+ audio_processor: The audio processor for the audio encoder.
15
+ tokenizer: The tokenizer for the language model.
16
+ """
17
+
18
+ attributes = ["audio_processor", "tokenizer"]
19
+ audio_processor_class = (
20
+ "Wav2Vec2Processor",
21
+ "SeamlessM4TFeatureExtractor",
22
+ "WhisperProcessor",
23
+ "Wav2Vec2BertProcessor",
24
+ )
25
+ tokenizer_class = (
26
+ "PreTrainedTokenizer",
27
+ "PreTrainedTokenizerFast",
28
+ )
29
+
30
+ tokenizer: transformers.PreTrainedTokenizerBase
31
+ audio_processor: transformers.ProcessorMixin
32
+
33
+ def __init__(
34
+ self,
35
+ audio_processor=None,
36
+ tokenizer=None,
37
+ audio_padding: str = "longest",
38
+ encoder_ds_factor: int = 320,
39
+ stack_factor: int = 8,
40
+ audio_placeholder: str = "<|audio|>",
41
+ ):
42
+ """
43
+ Args:
44
+ audio_processor: The audio processor for the audio encoder.
45
+ tokenizer: The tokenizer for the language model.
46
+ audio_padding: The padding strategy for the audio encoder.
47
+ encoder_ds_factor: The downsample factor of the audio encoder.
48
+ stack_factor: The factor by which the audio encoder output is stacked in the multimodal projector.
49
+ audio_placeholder: The placeholder for the audio in the text.
50
+ """
51
+ self.audio_padding = audio_padding
52
+ self.encoder_ds_factor = encoder_ds_factor
53
+ self.stack_factor = stack_factor
54
+ self.audio_placeholder = audio_placeholder
55
+ self.audio_token_replacement = tokenizer.eos_token
56
+ assert (
57
+ self.audio_token_replacement is not None
58
+ ), "The tokenizer has no EOS token. Cannot recover."
59
+ if tokenizer.pad_token_id is None:
60
+ tokenizer.pad_token_id = tokenizer.eos_token_id
61
+
62
+ super().__init__(audio_processor=audio_processor, tokenizer=tokenizer)
63
+
64
+ @classmethod
65
+ def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
66
+ config: UltravoxConfig = transformers.AutoConfig.from_pretrained(
67
+ pretrained_model_name_or_path, **kwargs
68
+ )
69
+ audio_processor = transformers.AutoProcessor.from_pretrained(
70
+ config.audio_model_id
71
+ or config.audio_config._name_or_path
72
+ or "facebook/wav2vec2-base-960h"
73
+ )
74
+
75
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
76
+ pretrained_model_name_or_path, **kwargs
77
+ )
78
+ tokenizer.padding_side = "left"
79
+ tokenizer.pad_token = tokenizer.eos_token
80
+
81
+ return cls(
82
+ audio_processor=audio_processor,
83
+ tokenizer=tokenizer,
84
+ stack_factor=config.stack_factor,
85
+ )
86
+
87
+ def __call__(
88
+ self,
89
+ text: Optional[str] = None,
90
+ audio: Optional[Union[np.ndarray, torch.Tensor]] = None,
91
+ sampling_rate: Optional[int] = None,
92
+ return_tensors: Optional[
93
+ Union[str, transformers.TensorType]
94
+ ] = transformers.TensorType.PYTORCH,
95
+ **kwargs,
96
+ ) -> transformers.BatchFeature:
97
+ """
98
+ Main method to prepare for the model one text sequence and audio. This method forwards the `text`
99
+ and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
100
+ the text. To prepare the audio(s), this method forwards the `audio`, `sampling_rate` and `kwargs` arguments to
101
+ audio processor's [`~Wav2Vec2Processor.__call__`] if `audio` is not `None`. Please refer to the docstring
102
+ of the above two methods for more information.
103
+ Args:
104
+ text (`str`, `List[str]`):
105
+ The sequence to be encoded. Sequence can be a string or (pretokenized string).
106
+ audio (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
107
+ The audio to be prepared. Audio can be NumPy array or PyTorch tensor. In case of a
108
+ NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels, and T the
109
+ sample length of the audio.
110
+ sampling_rate (`int`, *optional*, defaults to 16000):
111
+ Sampling rate of the input audio. We expect 16kHz audio. Don't change this value unless you know what
112
+ you are doing.
113
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
114
+ If set, will return tensors of a particular framework. Acceptable values are:
115
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
116
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
117
+ - `'np'`: Return NumPy `np.ndarray` objects.
118
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
119
+ Returns:
120
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
121
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
122
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
123
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
124
+ `None`).
125
+ - **audio_values** -- Processed audio values to be fed to a model. Returned when `audio` is not `None`.
126
+ - **audio_token_len** -- Predicted number of audio frames: this value is guaranteed to be a close upper bound.
127
+ Returned when `audio` is not `None`.
128
+ - **audio_token_start_idx** -- The index in the tokenized text where the audio starts. Returned when `audio` is not `None`.
129
+ """
130
+ # TODO: Add support for multiple audio and text inputs.
131
+ data = {}
132
+ audio_embed_frames = 0
133
+ if audio is not None and len(audio) > 0:
134
+ if self.audio_padding == "max_length":
135
+ # 30 seconds is the expected length for Whisper
136
+ assert sampling_rate is not None, "Sampling rate must be provided."
137
+ audio_len = [30 * sampling_rate] * len(audio)
138
+ else:
139
+ audio_len = [a.shape[-1] for a in audio]
140
+ # It's guaranteed that the number of frames is less than or equal to this amount.
141
+ # For Whisper this is exact AFAICT, but for Wav2Vec2 it's an upper bound.
142
+ # Currently, StackAudioFrames makes sure an over-estimation won't cause issues by padding the audio embeddings.
143
+ nb_encoder_frames = [int(round(a / self.encoder_ds_factor + 1e-4)) for a in audio_len]
144
+ audio_embed_frames = [int(np.ceil(n / self.stack_factor)) for n in nb_encoder_frames]
145
+ data["audio_token_len"] = audio_embed_frames
146
+
147
+ # Main audio processing. The processor is model-specific.
148
+ x = self.audio_processor(
149
+ audio,
150
+ sampling_rate=sampling_rate,
151
+ padding="longest",
152
+ max_length=max(audio_len),
153
+ return_attention_mask=True,
154
+ **kwargs,
155
+ )
156
+ if "input_features" in x:
157
+ data["audio_values"] = x.input_features
158
+ else:
159
+ data["audio_values"] = x.input_values
160
+ data["audio_len"] = x.attention_mask.sum(-1) - 1
161
+
162
+ if text is not None:
163
+ #assert isinstance(
164
+ # text, str
165
+ #), "Text must be a string. Batch mode not supported yet."
166
+ data["audio_token_start_idx"] = []
167
+ for t in text:
168
+ assert self.audio_placeholder in t
169
+ if "audio_token_len" not in data:
170
+ raise ValueError(
171
+ f"audio must be provided when using audio placeholder ({self.audio_placeholder}) in text."
172
+ )
173
+
174
+ start_idx = len(
175
+ self.tokenizer.encode(
176
+ t[: t.index(self.audio_placeholder)],
177
+ add_special_tokens=False,
178
+ )
179
+ )
180
+ data["audio_token_start_idx"].append(start_idx)
181
+
182
+ # Replace the audio placeholder with the audio token.
183
+ # e.g. "Transcribe\n<|audio|>" -> "Transcribe </s></s></s></s></s></s></s></s>"
184
+ # where the number of </s> is the number of audio frames.
185
+ text = [t.replace(self.audio_placeholder, self.audio_token_replacement * data["audio_token_len"][i]) for i, t in enumerate(text)]
186
+
187
+ # Special tokens like BOS should already have been added by the caller.
188
+ data.update(self.tokenizer(text, add_special_tokens=False, padding=True, **kwargs))
189
+
190
+ return transformers.BatchFeature(data=data, tensor_type=return_tensors)
191
+
192
+ def batch_decode(self, *args, **kwargs):
193
+ return self.tokenizer.batch_decode(*args, **kwargs)
194
+
195
+ def decode(self, *args, **kwargs):
196
+ return self.tokenizer.decode(*args, **kwargs)
197
+
198
+ @property
199
+ def model_input_names(self):
200
+ tokenizer_input_names = self.tokenizer.model_input_names
201
+ audio_processor_input_names = self.audio_processor.model_input_names
202
+ return list(set(tokenizer_input_names + audio_processor_input_names))
203
+
204
+
205
+ UltravoxProcessor.register_for_auto_class()
206
+
207
+ transformers.AutoProcessor.register(UltravoxConfig, UltravoxProcessor)