Upload folder using huggingface_hub
Browse files- ultravox_config.py +141 -0
- ultravox_model.py +407 -0
- ultravox_pipeline.py +110 -0
- ultravox_processing.py +172 -0
- whisper_model_modified.py +141 -0
ultravox_config.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
from typing import Any, Dict, List, Optional
|
3 |
+
|
4 |
+
import transformers
|
5 |
+
|
6 |
+
|
7 |
+
@dataclasses.dataclass
|
8 |
+
class LoraConfigSimplified:
|
9 |
+
"""
|
10 |
+
Low Rank Approximation (LoRA) configuration.
|
11 |
+
|
12 |
+
Used for language and audio models separately.
|
13 |
+
"""
|
14 |
+
|
15 |
+
# The rank of the approximation
|
16 |
+
r: int = 0
|
17 |
+
lora_alpha: float = 8
|
18 |
+
target_modules: Optional[List[str]] = dataclasses.field(
|
19 |
+
default_factory=lambda: ["k_proj", "q_proj", "linear_k", "linear_q"]
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
class UltravoxConfig(transformers.PretrainedConfig):
|
24 |
+
r"""
|
25 |
+
This is the configuration class to store the configuration of a [`UltravoxForConditionalGeneration`]. It is used to instantiate an
|
26 |
+
Ultravox model according to the specified arguments, defining the model architecture.
|
27 |
+
|
28 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
29 |
+
documentation from [`PretrainedConfig`] for more information.
|
30 |
+
|
31 |
+
Args:
|
32 |
+
audio_config (`Wav2Vec2Config`, *optional*):
|
33 |
+
Custom audio config or dict
|
34 |
+
text_config (`Union[AutoConfig, dict]`, *optional*):
|
35 |
+
The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`.
|
36 |
+
ignore_index (`int`, *optional*, defaults to -100):
|
37 |
+
The ignore index for the loss function.
|
38 |
+
audio_token_index (`int`, *optional*, defaults to 32000):
|
39 |
+
The audio token index to encode the audio prompt.
|
40 |
+
stack_factor (`int`, *optional*, defaults to 8):
|
41 |
+
Audio downsampling factor for the multimodal projector.
|
42 |
+
norm_init (`float`, *optional*, defaults to 0.4):
|
43 |
+
The initialization value for the layer normalization.
|
44 |
+
projector_act (`str`, *optional*, defaults to `"swiglu"`):
|
45 |
+
The activation function used by the multimodal projector.
|
46 |
+
text_model_lora_config (`LoraConfigSimplified`, *optional*):
|
47 |
+
The LoRA configuration for finetuning the text model.
|
48 |
+
audio_model_lora_config (`LoraConfigSimplified`, *optional*):
|
49 |
+
The LoRA configuration for finetuning the audio model.
|
50 |
+
|
51 |
+
|
52 |
+
Example:
|
53 |
+
|
54 |
+
```python
|
55 |
+
>>> from transformers import UltravoxForConditionalGeneration, Wav2Vec2Config, UltravoxConfig, LlamaConfig
|
56 |
+
|
57 |
+
>>> # Initializing an audio encoder config
|
58 |
+
>>> audio_config = Wav2Vec2Config()
|
59 |
+
|
60 |
+
>>> # Initializing a Llama config
|
61 |
+
>>> text_config = LlamaConfig()
|
62 |
+
|
63 |
+
>>> # Initializing a default configuration
|
64 |
+
>>> configuration = UltravoxConfig(audio_config, text_config)
|
65 |
+
|
66 |
+
>>> # Initializing a completely untrained model from the configuration
|
67 |
+
>>> model = UltravoxForConditionalGeneration(configuration)
|
68 |
+
|
69 |
+
>>> # Accessing the model configuration
|
70 |
+
>>> configuration = model.config
|
71 |
+
|
72 |
+
>>> # Initialize a model from pretrained checkpoints and random projector weights
|
73 |
+
>>> config = UltravoxConfig(audio_model_id="facebook/wav2vec2-base-960h", text_model_id="meta-llama/Llama-2-7b-chat-hf")
|
74 |
+
```"""
|
75 |
+
|
76 |
+
model_type = "ultravox"
|
77 |
+
is_composition = False
|
78 |
+
|
79 |
+
def __init__(
|
80 |
+
self,
|
81 |
+
audio_config: Optional[Dict[str, Any]] = None,
|
82 |
+
text_config: Optional[Dict[str, Any]] = None,
|
83 |
+
audio_model_id: Optional[str] = None,
|
84 |
+
text_model_id: Optional[str] = None,
|
85 |
+
ignore_index: int = -100,
|
86 |
+
audio_token_index: int = 32000,
|
87 |
+
hidden_size: int = 4096,
|
88 |
+
stack_factor: int = 8,
|
89 |
+
norm_init: float = 0.4,
|
90 |
+
projector_act: str = "swiglu",
|
91 |
+
text_model_lora_config: Optional[LoraConfigSimplified] = None,
|
92 |
+
audio_model_lora_config: Optional[LoraConfigSimplified] = None,
|
93 |
+
**kwargs,
|
94 |
+
):
|
95 |
+
self.ignore_index = ignore_index
|
96 |
+
|
97 |
+
self.audio_model_id = audio_model_id
|
98 |
+
self.text_model_id = text_model_id
|
99 |
+
self.audio_token_index = audio_token_index
|
100 |
+
|
101 |
+
self.hidden_size = hidden_size
|
102 |
+
self.stack_factor = stack_factor
|
103 |
+
self.norm_init = norm_init
|
104 |
+
self.projector_act = projector_act
|
105 |
+
|
106 |
+
if text_model_id is not None:
|
107 |
+
self.text_config: transformers.LlamaConfig = (
|
108 |
+
transformers.AutoConfig.from_pretrained(text_model_id)
|
109 |
+
)
|
110 |
+
else:
|
111 |
+
text_config = text_config or {}
|
112 |
+
self.text_config = transformers.CONFIG_MAPPING[
|
113 |
+
text_config.get("model_type", "llama")
|
114 |
+
](**text_config)
|
115 |
+
|
116 |
+
if audio_model_id is not None:
|
117 |
+
self.audio_config: transformers.PretrainedConfig = (
|
118 |
+
transformers.AutoConfig.from_pretrained(audio_model_id)
|
119 |
+
)
|
120 |
+
else:
|
121 |
+
audio_config = audio_config or {}
|
122 |
+
self.audio_config = transformers.CONFIG_MAPPING[
|
123 |
+
audio_config.get("model_type", "wav2vec2")
|
124 |
+
](**audio_config)
|
125 |
+
|
126 |
+
self.text_model_lora_config = (
|
127 |
+
text_model_lora_config
|
128 |
+
if isinstance(text_model_lora_config, dict)
|
129 |
+
else dataclasses.asdict(text_model_lora_config or LoraConfigSimplified())
|
130 |
+
)
|
131 |
+
self.audio_model_lora_config = (
|
132 |
+
audio_model_lora_config
|
133 |
+
if isinstance(audio_model_lora_config, dict)
|
134 |
+
else dataclasses.asdict(audio_model_lora_config or LoraConfigSimplified())
|
135 |
+
)
|
136 |
+
|
137 |
+
self.vocab_size = self.text_config.vocab_size
|
138 |
+
|
139 |
+
self.initializer_range = self.text_config.initializer_range
|
140 |
+
|
141 |
+
super().__init__(**kwargs)
|
ultravox_model.py
ADDED
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
13 |
+
# We must use relative import in this directory to allow uploading to HF Hub
|
14 |
+
# Even "from . import X" pattern doesn't work (undocumented and unclear why)
|
15 |
+
from .ultravox_config import UltravoxConfig
|
16 |
+
from .whisper_model_modified import WhisperEncoder as ModifiedWhisperEncoder
|
17 |
+
|
18 |
+
|
19 |
+
class UltravoxModel(
|
20 |
+
transformers.LlamaPreTrainedModel,
|
21 |
+
transformers.GenerationMixin,
|
22 |
+
):
|
23 |
+
"""
|
24 |
+
The Ultravox model which consists of an audio encoder and a language model.
|
25 |
+
|
26 |
+
Audio input is processed by the audio encoder, then every `stack_factor` frames are stacked together and
|
27 |
+
projected to the language model's embedding space using a few linear layers.
|
28 |
+
The text is embedded by the language model as usual and then the audio and text embeddings are merged together.
|
29 |
+
|
30 |
+
A special token `<|audio|>` is used to indicate the start of the audio embeddings in the merged embeddings.
|
31 |
+
|
32 |
+
Parameters:
|
33 |
+
config: Model configuration class with all the parameters of the model.
|
34 |
+
"""
|
35 |
+
|
36 |
+
config_class = UltravoxConfig
|
37 |
+
config: UltravoxConfig # for type hinting
|
38 |
+
_no_split_modules = ["Wav2Vec2Model", "WhisperEncoder", "LlamaDecoderLayer"]
|
39 |
+
|
40 |
+
def __init__(self, config: UltravoxConfig):
|
41 |
+
super().__init__(config)
|
42 |
+
|
43 |
+
self.keep_params: Set[str] = set()
|
44 |
+
self.vocab_size = config.vocab_size
|
45 |
+
|
46 |
+
self.audio_tower = self._create_audio_tower(config)
|
47 |
+
self.multi_modal_projector = UltravoxProjector(config)
|
48 |
+
self.language_model = self._create_language_model(config)
|
49 |
+
|
50 |
+
self.post_init()
|
51 |
+
|
52 |
+
def get_input_embeddings(self):
|
53 |
+
return self.language_model.get_input_embeddings()
|
54 |
+
|
55 |
+
def set_input_embeddings(self, value):
|
56 |
+
self.language_model.set_input_embeddings(value)
|
57 |
+
|
58 |
+
def get_output_embeddings(self):
|
59 |
+
return self.language_model.get_output_embeddings()
|
60 |
+
|
61 |
+
def set_output_embeddings(self, new_embeddings):
|
62 |
+
self.language_model.set_output_embeddings(new_embeddings)
|
63 |
+
|
64 |
+
def set_decoder(self, decoder):
|
65 |
+
self.language_model.set_decoder(decoder)
|
66 |
+
|
67 |
+
def get_decoder(self):
|
68 |
+
return self.language_model.get_decoder()
|
69 |
+
|
70 |
+
def tie_weights(self):
|
71 |
+
return self.language_model.tie_weights()
|
72 |
+
|
73 |
+
def _setup_cache(
|
74 |
+
self, cache_cls, max_batch_size: int, max_cache_len: Optional[int] = None
|
75 |
+
):
|
76 |
+
self.language_model._setup_cache(cache_cls, max_batch_size, max_cache_len)
|
77 |
+
|
78 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
79 |
+
return self.language_model._reorder_cache(past_key_values, beam_idx)
|
80 |
+
|
81 |
+
def resize_token_embeddings(
|
82 |
+
self,
|
83 |
+
new_num_tokens: Optional[int] = None,
|
84 |
+
pad_to_multiple_of: Optional[int] = None,
|
85 |
+
) -> nn.Embedding:
|
86 |
+
model_embeds = self.language_model.resize_token_embeddings(
|
87 |
+
new_num_tokens, pad_to_multiple_of
|
88 |
+
)
|
89 |
+
# update vocab size
|
90 |
+
self.config.text_config.vocab_size = model_embeds.num_embeddings
|
91 |
+
self.config.vocab_size = model_embeds.num_embeddings
|
92 |
+
self.vocab_size = model_embeds.num_embeddings
|
93 |
+
return model_embeds
|
94 |
+
|
95 |
+
def forward(
|
96 |
+
self,
|
97 |
+
input_ids: torch.Tensor,
|
98 |
+
audio_values: Optional[torch.FloatTensor] = None,
|
99 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
100 |
+
labels: Optional[torch.Tensor] = None,
|
101 |
+
attention_mask: Optional[torch.Tensor] = None,
|
102 |
+
audio_token_start_idx: Optional[torch.Tensor] = None,
|
103 |
+
audio_token_len: Optional[torch.Tensor] = None,
|
104 |
+
past_key_values: Optional[Tuple] = None,
|
105 |
+
**kwargs,
|
106 |
+
) -> Union[Tuple, transformers.modeling_outputs.CausalLMOutputWithPast]:
|
107 |
+
"""
|
108 |
+
Forward pass for the Ultravox model.
|
109 |
+
|
110 |
+
`input_ids` are the tokenized text input. They are embedded by the language model as usual.
|
111 |
+
`audio_values` are processed by the audio encoder and then every `stack_factor` frames are stacked together and
|
112 |
+
projected to the language model's embedding space using a few linear layers.
|
113 |
+
The audio and text embeddings are merged together. A special token `<|audio|>` is used to indicate the start
|
114 |
+
of the audio embeddings in the merged embeddings.
|
115 |
+
|
116 |
+
Args:
|
117 |
+
input_ids: The tokenized text input.
|
118 |
+
audio_values: The processed audio values.
|
119 |
+
inputs_embeds: The embeddings for the input tokens.
|
120 |
+
labels: The tokenized text labels.
|
121 |
+
attention_mask: The attention mask for the input.
|
122 |
+
position_ids: The position ids for the input.
|
123 |
+
past_key_values: The past key value cache for the language model attention layers.
|
124 |
+
**kwargs: Additional keyword arguments. Passed directly to the language model.
|
125 |
+
"""
|
126 |
+
if inputs_embeds is None:
|
127 |
+
# B x T -> B x T x D
|
128 |
+
inputs_embeds = self.get_input_embeddings().forward(input_ids)
|
129 |
+
|
130 |
+
if audio_values is not None:
|
131 |
+
assert (
|
132 |
+
audio_token_start_idx is not None and audio_token_len is not None
|
133 |
+
), "audio_token_start_idx and audio_token_len must be provided if audio_values are provided."
|
134 |
+
assert (
|
135 |
+
len(audio_token_start_idx) == len(audio_token_len) == len(audio_values)
|
136 |
+
), "audio_token_start_idx, audio_token_len, and audio_values must have the same batch size."
|
137 |
+
|
138 |
+
# B x A/3200 x D
|
139 |
+
audio_tower_output = self.audio_tower.forward(
|
140 |
+
audio_values
|
141 |
+
).last_hidden_state
|
142 |
+
audio_tower_output = audio_tower_output.to(inputs_embeds.dtype)
|
143 |
+
|
144 |
+
audio_embeds = self.multi_modal_projector.forward(audio_tower_output)
|
145 |
+
|
146 |
+
# combine audio and text embeddings
|
147 |
+
for i, (audio, start, length) in enumerate(
|
148 |
+
zip(audio_embeds, audio_token_start_idx, audio_token_len)
|
149 |
+
):
|
150 |
+
length = min(length, audio.shape[0])
|
151 |
+
inputs_embeds[i, start : start + length] = audio[:length]
|
152 |
+
|
153 |
+
lm_output = self.language_model.forward(
|
154 |
+
inputs_embeds=inputs_embeds,
|
155 |
+
labels=labels,
|
156 |
+
attention_mask=attention_mask,
|
157 |
+
past_key_values=past_key_values,
|
158 |
+
**kwargs,
|
159 |
+
)
|
160 |
+
|
161 |
+
return lm_output
|
162 |
+
|
163 |
+
def prepare_inputs_for_generation(
|
164 |
+
self,
|
165 |
+
input_ids: torch.Tensor,
|
166 |
+
audio_values: Optional[torch.FloatTensor] = None,
|
167 |
+
audio_token_start_idx: Optional[torch.Tensor] = None,
|
168 |
+
audio_token_len: Optional[torch.Tensor] = None,
|
169 |
+
past_key_values: Optional[Tuple] = None,
|
170 |
+
attention_mask: Optional[torch.Tensor] = None,
|
171 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
172 |
+
**kwargs,
|
173 |
+
) -> Dict[str, Any]:
|
174 |
+
model_input = self.language_model.prepare_inputs_for_generation(
|
175 |
+
input_ids=input_ids,
|
176 |
+
past_key_values=past_key_values,
|
177 |
+
attention_mask=attention_mask,
|
178 |
+
inputs_embeds=inputs_embeds,
|
179 |
+
**kwargs,
|
180 |
+
)
|
181 |
+
|
182 |
+
if past_key_values is None and audio_values is not None:
|
183 |
+
# We only want to use audio features in the 1st generation step
|
184 |
+
model_input["audio_values"] = audio_values
|
185 |
+
model_input["audio_token_start_idx"] = audio_token_start_idx
|
186 |
+
model_input["audio_token_len"] = audio_token_len
|
187 |
+
|
188 |
+
return model_input
|
189 |
+
|
190 |
+
@classmethod
|
191 |
+
def _create_audio_tower(
|
192 |
+
cls, config: UltravoxConfig
|
193 |
+
) -> Union[transformers.Wav2Vec2Model, ModifiedWhisperEncoder]:
|
194 |
+
if config.audio_model_id is not None:
|
195 |
+
if "whisper" in config.audio_model_id is not None:
|
196 |
+
audio_tower = ModifiedWhisperEncoder.from_pretrained(
|
197 |
+
config.audio_model_id
|
198 |
+
)
|
199 |
+
else:
|
200 |
+
audio_tower = transformers.AutoModel.from_pretrained(
|
201 |
+
config.audio_model_id
|
202 |
+
)
|
203 |
+
else:
|
204 |
+
if "whisper" in config.audio_config._name_or_path:
|
205 |
+
audio_tower = ModifiedWhisperEncoder(config.audio_config)
|
206 |
+
else:
|
207 |
+
audio_tower = transformers.AutoModel.from_config(config.audio_config)
|
208 |
+
|
209 |
+
if isinstance(
|
210 |
+
audio_tower,
|
211 |
+
(transformers.Wav2Vec2BertModel, transformers.WhisperModel),
|
212 |
+
):
|
213 |
+
# For these models we only need the encoder part
|
214 |
+
# Wav2Vec2BertModel -> Wav2Vec2BertEncoder
|
215 |
+
# WhisperModel -> WhisperEncoder
|
216 |
+
audio_tower = audio_tower.encoder
|
217 |
+
|
218 |
+
audio_tower = apply_lora(audio_tower, config.audio_model_lora_config)
|
219 |
+
return audio_tower
|
220 |
+
|
221 |
+
@classmethod
|
222 |
+
def _create_language_model(
|
223 |
+
cls, config: UltravoxConfig
|
224 |
+
) -> transformers.LlamaForCausalLM:
|
225 |
+
if config.text_model_id is not None:
|
226 |
+
language_model = transformers.AutoModelForCausalLM.from_pretrained(
|
227 |
+
config.text_model_id, attn_implementation=config._attn_implementation
|
228 |
+
)
|
229 |
+
else:
|
230 |
+
language_model = transformers.AutoModelForCausalLM.from_config(
|
231 |
+
config.text_config, attn_implementation=config._attn_implementation
|
232 |
+
)
|
233 |
+
|
234 |
+
language_model = apply_lora(language_model, config.text_model_lora_config)
|
235 |
+
return language_model
|
236 |
+
|
237 |
+
def merge_and_unload(self):
|
238 |
+
if isinstance(self.language_model, peft.PeftModel):
|
239 |
+
self.language_model = self.language_model.merge_and_unload()
|
240 |
+
# no need to download base language model weights anymore, so we can remove the id
|
241 |
+
self.config.text_model_id = None
|
242 |
+
self.keep_params.update(
|
243 |
+
set(
|
244 |
+
[
|
245 |
+
f"language_model.{name}"
|
246 |
+
for name, _ in self.language_model.named_parameters()
|
247 |
+
]
|
248 |
+
)
|
249 |
+
)
|
250 |
+
|
251 |
+
if isinstance(self.audio_tower, peft.PeftModel):
|
252 |
+
self.audio_tower = self.audio_tower.merge_and_unload()
|
253 |
+
# no need to download base audio model weights anymore, so we can remove the id
|
254 |
+
self.config.audio_model_id = None
|
255 |
+
self.keep_params.update(
|
256 |
+
set(
|
257 |
+
[
|
258 |
+
f"audio_tower.{name}"
|
259 |
+
for name, _ in self.audio_tower.named_parameters()
|
260 |
+
]
|
261 |
+
)
|
262 |
+
)
|
263 |
+
|
264 |
+
for param in ["text_model_lora_config", "audio_model_lora_config"]:
|
265 |
+
if hasattr(self.config, param):
|
266 |
+
delattr(self.config, param)
|
267 |
+
|
268 |
+
def push_to_hub(self, *args, **kwargs):
|
269 |
+
self.merge_and_unload()
|
270 |
+
self.to(self.language_model.dtype)
|
271 |
+
return super().push_to_hub(*args, **kwargs)
|
272 |
+
|
273 |
+
def state_dict(self, *args, **kwargs):
|
274 |
+
named_params = dict(self.named_parameters())
|
275 |
+
state_dict = super().state_dict(*args, **kwargs)
|
276 |
+
|
277 |
+
state_dict = {
|
278 |
+
k: v
|
279 |
+
for k, v in state_dict.items()
|
280 |
+
if k in self.keep_params
|
281 |
+
or (k in named_params and named_params[k].requires_grad)
|
282 |
+
}
|
283 |
+
return state_dict
|
284 |
+
|
285 |
+
def load_state_dict(
|
286 |
+
self,
|
287 |
+
state_dict: Dict[str, Any],
|
288 |
+
*args,
|
289 |
+
**kwargs,
|
290 |
+
):
|
291 |
+
self.keep_params.update(set(state_dict.keys()))
|
292 |
+
return super().load_state_dict(state_dict, *args, **kwargs)
|
293 |
+
|
294 |
+
def print_trainable_parameters(self):
|
295 |
+
"""
|
296 |
+
Prints the number of trainable parameters in the model (reuses Peft model's method)
|
297 |
+
"""
|
298 |
+
count_params = peft.peft_model.PeftModel.get_nb_trainable_parameters
|
299 |
+
|
300 |
+
trainable_params, all_param = count_params(self)
|
301 |
+
|
302 |
+
logging.info(
|
303 |
+
f"trainable params: {trainable_params:,d} || all params: {all_param:,d}"
|
304 |
+
f" || trainable%: {100 * trainable_params / all_param:.1f}%"
|
305 |
+
)
|
306 |
+
|
307 |
+
lm_trainable_params, lm_all_params = count_params(self.language_model)
|
308 |
+
audio_trainable_params, audio_all_params = count_params(self.audio_tower)
|
309 |
+
|
310 |
+
projector_trainable_params = (
|
311 |
+
trainable_params - lm_trainable_params - audio_trainable_params
|
312 |
+
)
|
313 |
+
projector_all_params = all_param - lm_all_params - audio_all_params
|
314 |
+
|
315 |
+
logging.info(
|
316 |
+
f"Trainable%: "
|
317 |
+
f" LLM: {100 * lm_trainable_params / lm_all_params:.1f}%"
|
318 |
+
f" || Audio Encoder: {100 * audio_trainable_params / audio_all_params:.1f}%"
|
319 |
+
f" || Projector: {100 * projector_trainable_params / projector_all_params:.1f}%"
|
320 |
+
)
|
321 |
+
|
322 |
+
|
323 |
+
def apply_lora(model: torch.nn.Module, lora_config: dict) -> torch.nn.Module:
|
324 |
+
"""
|
325 |
+
Applies LoRA finetuning to the model. If the `r` parameter is set to 0, the model is frozen instead.
|
326 |
+
"""
|
327 |
+
lora_config = peft.LoraConfig(**lora_config or {})
|
328 |
+
|
329 |
+
if lora_config.r == 0:
|
330 |
+
# freeze the model entirely
|
331 |
+
for param in model.parameters():
|
332 |
+
param.requires_grad = False
|
333 |
+
else:
|
334 |
+
model = peft.get_peft_model(model, lora_config)
|
335 |
+
|
336 |
+
return model
|
337 |
+
|
338 |
+
|
339 |
+
class StackAudioFrames(nn.Module):
|
340 |
+
"""
|
341 |
+
Stack the audio embedding frames to reduce the sequence length by a factor of `stack_factor`.
|
342 |
+
|
343 |
+
The number of output frames will be `ceil(T / stack_factor) + 1` where `T` is the number of input frames.
|
344 |
+
NOTE: the extra +1 is intentional: in case the number of audio tokens are over-estimated by the processor,
|
345 |
+
we want to make sure `processor.audio_token_replacement` (i.e. EOS) doesn't get leaked into the middle of embeddings.
|
346 |
+
In most cases this extra padding will get removed in the model's forward function so it has no effect.
|
347 |
+
"""
|
348 |
+
|
349 |
+
def __init__(self, stack_factor: int = 8):
|
350 |
+
super().__init__()
|
351 |
+
self.stack_factor = stack_factor
|
352 |
+
|
353 |
+
def forward(self, audio_embeds: torch.Tensor) -> torch.Tensor:
|
354 |
+
B, T, C = audio_embeds.shape
|
355 |
+
T_pad = (T + self.stack_factor - 1) // self.stack_factor * self.stack_factor
|
356 |
+
audio_embeds = F.pad(audio_embeds, (0, 0, 0, T_pad - T + self.stack_factor))
|
357 |
+
B, T, C = audio_embeds.shape
|
358 |
+
audio_embeds = audio_embeds.view(
|
359 |
+
B, T // self.stack_factor, C * self.stack_factor
|
360 |
+
)
|
361 |
+
return audio_embeds
|
362 |
+
|
363 |
+
|
364 |
+
class RMSNorm(transformers.models.llama.modeling_llama.LlamaRMSNorm):
|
365 |
+
def __init__(self, hidden_size: int, init: float = 1, eps: float = 1e-6):
|
366 |
+
super().__init__(hidden_size=hidden_size, eps=eps)
|
367 |
+
self.weight.data.fill_(init)
|
368 |
+
|
369 |
+
|
370 |
+
class SwiGLU(nn.Module):
|
371 |
+
def forward(self, x):
|
372 |
+
x, gate = x.chunk(2, dim=-1)
|
373 |
+
return F.silu(gate) * x
|
374 |
+
|
375 |
+
|
376 |
+
class UltravoxProjector(nn.Sequential):
|
377 |
+
def __init__(self, config: UltravoxConfig):
|
378 |
+
super().__init__()
|
379 |
+
self.hidden_dim = config.hidden_size
|
380 |
+
self._pad_and_stack = StackAudioFrames(config.stack_factor)
|
381 |
+
dim = config.audio_config.hidden_size * config.stack_factor
|
382 |
+
self.ln_pre = RMSNorm(dim, init=config.norm_init)
|
383 |
+
self.linear_1 = nn.Linear(dim, self.hidden_dim, bias=False)
|
384 |
+
dim = self.hidden_dim
|
385 |
+
self.act = transformers.activations.get_activation(config.projector_act)
|
386 |
+
dim = dim // 2 if config.projector_act == "swiglu" else dim
|
387 |
+
self.linear_2 = nn.Linear(dim, config.text_config.hidden_size, bias=False)
|
388 |
+
self.ln_post = RMSNorm(config.text_config.hidden_size, init=config.norm_init)
|
389 |
+
|
390 |
+
def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
|
391 |
+
audio_features = self._pad_and_stack(audio_features)
|
392 |
+
audio_features = self.ln_pre(audio_features)
|
393 |
+
hidden_states = self.linear_1(audio_features)
|
394 |
+
hidden_states = self.act(hidden_states)
|
395 |
+
hidden_states = self.linear_2(hidden_states)
|
396 |
+
hidden_states = self.ln_post(hidden_states)
|
397 |
+
return hidden_states
|
398 |
+
|
399 |
+
|
400 |
+
UltravoxConfig.register_for_auto_class()
|
401 |
+
UltravoxModel.register_for_auto_class()
|
402 |
+
|
403 |
+
transformers.AutoConfig.register("ultravox", UltravoxConfig)
|
404 |
+
transformers.AutoModel.register(UltravoxConfig, UltravoxModel)
|
405 |
+
# transformers.AutoProcessor.register(UltravoxConfig, UltravoxProcessor) # TODO: make processo work standalone
|
406 |
+
|
407 |
+
transformers.activations.ACT2FN["swiglu"] = SwiGLU
|
ultravox_pipeline.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from typing import Any, Dict, List, Optional
|
3 |
+
|
4 |
+
import transformers
|
5 |
+
|
6 |
+
# We must use relative import in this directory to allow uploading to HF Hub
|
7 |
+
# Even "from . import X" pattern doesn't work (undocumented and unclear why)
|
8 |
+
from .ultravox_model import UltravoxModel
|
9 |
+
from .ultravox_processing import UltravoxProcessor
|
10 |
+
|
11 |
+
|
12 |
+
class UltravoxPipeline(transformers.Pipeline):
|
13 |
+
def __init__(
|
14 |
+
self,
|
15 |
+
model: UltravoxModel,
|
16 |
+
tokenizer: Optional[transformers.PreTrainedTokenizerBase] = None,
|
17 |
+
audio_processor: Optional[transformers.ProcessorMixin] = None,
|
18 |
+
**kwargs
|
19 |
+
):
|
20 |
+
if tokenizer is None:
|
21 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
22 |
+
model.config._name_or_path
|
23 |
+
)
|
24 |
+
|
25 |
+
if audio_processor is None:
|
26 |
+
audio_processor = transformers.Wav2Vec2Processor.from_pretrained(
|
27 |
+
model.config.audio_model_id
|
28 |
+
)
|
29 |
+
|
30 |
+
self.processor = UltravoxProcessor(
|
31 |
+
audio_processor, tokenizer=tokenizer, stack_factor=model.config.stack_factor
|
32 |
+
)
|
33 |
+
|
34 |
+
super().__init__(model=model, tokenizer=tokenizer, **kwargs)
|
35 |
+
|
36 |
+
def _sanitize_parameters(self, **kwargs):
|
37 |
+
generation_kwargs = {}
|
38 |
+
if "temperature" in kwargs:
|
39 |
+
generation_kwargs["temperature"] = kwargs["temperature"]
|
40 |
+
if "max_new_tokens" in kwargs:
|
41 |
+
generation_kwargs["max_new_tokens"] = kwargs["max_new_tokens"]
|
42 |
+
if "repetition_penalty" in kwargs:
|
43 |
+
generation_kwargs["repetition_penalty"] = kwargs["repetition_penalty"]
|
44 |
+
return {}, generation_kwargs, {}
|
45 |
+
|
46 |
+
def preprocess(self, inputs: Dict[str, Any]):
|
47 |
+
if "turns" in inputs:
|
48 |
+
turns = inputs["turns"]
|
49 |
+
else:
|
50 |
+
prompt = inputs.get("prompt", "<|audio|>")
|
51 |
+
if "<|audio|>" not in prompt:
|
52 |
+
logging.warning(
|
53 |
+
"Prompt does not contain '<|audio|>', appending '<|audio|>' to the end of the prompt."
|
54 |
+
)
|
55 |
+
prompt += " <|audio|>"
|
56 |
+
turns = [{"role": "user", "content": prompt}]
|
57 |
+
|
58 |
+
text = self.processor.tokenizer.apply_chat_template(turns, tokenize=False)
|
59 |
+
|
60 |
+
# TODO: allow text-only mode?
|
61 |
+
assert "audio" in inputs, "Audio input is required"
|
62 |
+
|
63 |
+
if "sampling_rate" not in inputs:
|
64 |
+
logging.warning(
|
65 |
+
"No sampling rate provided, using default of 16kHz. We highly recommend providing the correct sampling rate."
|
66 |
+
)
|
67 |
+
|
68 |
+
return self.processor(
|
69 |
+
text=text,
|
70 |
+
audio=inputs["audio"],
|
71 |
+
sampling_rate=inputs.get("sampling_rate", 16000),
|
72 |
+
)
|
73 |
+
|
74 |
+
def _forward(
|
75 |
+
self,
|
76 |
+
model_inputs: Dict[str, Any],
|
77 |
+
temperature: Optional[float] = None,
|
78 |
+
max_new_tokens: Optional[int] = None,
|
79 |
+
repetition_penalty: float = 1.1,
|
80 |
+
) -> List[int]:
|
81 |
+
temperature = temperature or None
|
82 |
+
do_sample = temperature is not None
|
83 |
+
|
84 |
+
terminators = [self.tokenizer.eos_token_id]
|
85 |
+
if "<|eot_id|>" in self.tokenizer.added_tokens_encoder:
|
86 |
+
terminators.append(self.tokenizer.convert_tokens_to_ids("<|eot_id|>"))
|
87 |
+
|
88 |
+
input_len = model_inputs["input_ids"].shape[1]
|
89 |
+
|
90 |
+
outputs = self.model.generate(
|
91 |
+
**model_inputs,
|
92 |
+
do_sample=do_sample,
|
93 |
+
temperature=temperature,
|
94 |
+
max_new_tokens=max_new_tokens,
|
95 |
+
repetition_penalty=repetition_penalty,
|
96 |
+
eos_token_id=terminators
|
97 |
+
)
|
98 |
+
return outputs[0][input_len:]
|
99 |
+
|
100 |
+
def postprocess(self, model_outputs) -> str:
|
101 |
+
output_text = self.tokenizer.decode(model_outputs, skip_special_tokens=True)
|
102 |
+
return output_text
|
103 |
+
|
104 |
+
|
105 |
+
transformers.pipelines.PIPELINE_REGISTRY.register_pipeline(
|
106 |
+
"ultravox-pipeline",
|
107 |
+
pipeline_class=UltravoxPipeline,
|
108 |
+
pt_model=transformers.AutoModel,
|
109 |
+
type="multimodal",
|
110 |
+
)
|
ultravox_processing.py
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional, Union
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import transformers
|
6 |
+
|
7 |
+
|
8 |
+
class UltravoxProcessor(transformers.ProcessorMixin):
|
9 |
+
"""
|
10 |
+
Constructs an Ultravox processor which wraps an audio processor and a tokenizer into a single processor.
|
11 |
+
|
12 |
+
Args:
|
13 |
+
audio_processor: The audio processor for the audio encoder.
|
14 |
+
tokenizer: The tokenizer for the language model.
|
15 |
+
"""
|
16 |
+
|
17 |
+
attributes = ["audio_processor", "tokenizer"]
|
18 |
+
audio_processor_class = (
|
19 |
+
"Wav2Vec2Processor",
|
20 |
+
"SeamlessM4TFeatureExtractor",
|
21 |
+
"WhisperProcessor",
|
22 |
+
)
|
23 |
+
tokenizer_class = (
|
24 |
+
"PreTrainedTokenizer",
|
25 |
+
"PreTrainedTokenizerFast",
|
26 |
+
)
|
27 |
+
|
28 |
+
tokenizer: transformers.PreTrainedTokenizerBase
|
29 |
+
audio_processor: transformers.ProcessorMixin
|
30 |
+
|
31 |
+
def __init__(
|
32 |
+
self,
|
33 |
+
audio_processor=None,
|
34 |
+
tokenizer=None,
|
35 |
+
audio_padding: str = "longest",
|
36 |
+
encoder_ds_factor: int = 320,
|
37 |
+
stack_factor: int = 8,
|
38 |
+
audio_placeholder: str = "<|audio|>",
|
39 |
+
):
|
40 |
+
"""
|
41 |
+
Args:
|
42 |
+
audio_processor: The audio processor for the audio encoder.
|
43 |
+
tokenizer: The tokenizer for the language model.
|
44 |
+
audio_padding: The padding strategy for the audio encoder.
|
45 |
+
encoder_ds_factor: The downsample factor of the audio encoder.
|
46 |
+
stack_factor: The factor by which the audio encoder output is stacked in the multimodal projector.
|
47 |
+
audio_placeholder: The placeholder for the audio in the text.
|
48 |
+
"""
|
49 |
+
self.audio_padding = audio_padding
|
50 |
+
self.encoder_ds_factor = encoder_ds_factor
|
51 |
+
self.stack_factor = stack_factor
|
52 |
+
self.audio_placeholder = audio_placeholder
|
53 |
+
self.audio_token_replacement = tokenizer.eos_token
|
54 |
+
assert (
|
55 |
+
self.audio_token_replacement is not None
|
56 |
+
), "The tokenizer has no EOS token. Cannot recover."
|
57 |
+
super().__init__(audio_processor=audio_processor, tokenizer=tokenizer)
|
58 |
+
|
59 |
+
def __call__(
|
60 |
+
self,
|
61 |
+
text: Optional[str] = None,
|
62 |
+
audio: Optional[Union[np.ndarray, torch.Tensor]] = None,
|
63 |
+
sampling_rate: Optional[int] = None,
|
64 |
+
return_tensors: Optional[
|
65 |
+
Union[str, transformers.TensorType]
|
66 |
+
] = transformers.TensorType.PYTORCH,
|
67 |
+
**kwargs,
|
68 |
+
) -> transformers.BatchFeature:
|
69 |
+
"""
|
70 |
+
Main method to prepare for the model one text sequence and audio. This method forwards the `text`
|
71 |
+
and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
|
72 |
+
the text. To prepare the audio(s), this method forwards the `audio`, `sampling_rate` and `kwargs` arguments to
|
73 |
+
audio processor's [`~Wav2Vec2Processor.__call__`] if `audio` is not `None`. Please refer to the docstring
|
74 |
+
of the above two methods for more information.
|
75 |
+
|
76 |
+
Args:
|
77 |
+
text (`str`, `List[str]`):
|
78 |
+
The sequence to be encoded. Sequence can be a string or (pretokenized string).
|
79 |
+
audio (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
80 |
+
The audio to be prepared. Audio can be NumPy array or PyTorch tensor. In case of a
|
81 |
+
NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels, and T the
|
82 |
+
sample length of the audio.
|
83 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
84 |
+
Sampling rate of the input audio. We expect 16kHz audio. Don't change this value unless you know what
|
85 |
+
you are doing.
|
86 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
87 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
88 |
+
|
89 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
90 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
91 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
92 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
93 |
+
|
94 |
+
Returns:
|
95 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
96 |
+
|
97 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
98 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
99 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
100 |
+
`None`).
|
101 |
+
- **audio_values** -- Processed audio values to be fed to a model. Returned when `audio` is not `None`.
|
102 |
+
- **audio_token_len** -- Predicted number of audio frames: this value is guaranteed to be a close upper bound.
|
103 |
+
Returned when `audio` is not `None`.
|
104 |
+
- **audio_token_start_idx** -- The index in the tokenized text where the audio starts. Returned when `audio` is not `None`.
|
105 |
+
"""
|
106 |
+
# TODO: Add support for multiple audio and text inputs.
|
107 |
+
data = {}
|
108 |
+
audio_embed_frames = 0
|
109 |
+
if audio is not None and len(audio) > 0:
|
110 |
+
if self.audio_padding == "max_length":
|
111 |
+
# 30 seconds is the expected length for Whisper
|
112 |
+
assert sampling_rate is not None, "Sampling rate must be provided."
|
113 |
+
audio_len = 30 * sampling_rate
|
114 |
+
else:
|
115 |
+
audio_len = audio.shape[-1]
|
116 |
+
# It's guaranteed that the number of frames is less than or equal to this amount.
|
117 |
+
# For Whisper this is exact AFAICT, but for Wav2Vec2 it's an upper bound.
|
118 |
+
# Currently, StackAudioFrames makes sure an over-estimation won't cause issues by padding the audio embeddings.
|
119 |
+
nb_encoder_frames = int(round(audio_len / self.encoder_ds_factor + 1e-4))
|
120 |
+
audio_embed_frames = int(np.ceil(nb_encoder_frames / self.stack_factor))
|
121 |
+
data["audio_token_len"] = [audio_embed_frames]
|
122 |
+
|
123 |
+
x = self.audio_processor(
|
124 |
+
audio,
|
125 |
+
sampling_rate=sampling_rate,
|
126 |
+
padding="longest",
|
127 |
+
max_length=audio_len,
|
128 |
+
**kwargs,
|
129 |
+
)
|
130 |
+
if "input_features" in x:
|
131 |
+
data["audio_values"] = x.input_features
|
132 |
+
else:
|
133 |
+
data["audio_values"] = x.input_values
|
134 |
+
|
135 |
+
if text is not None:
|
136 |
+
assert isinstance(
|
137 |
+
text, str
|
138 |
+
), "Text must be a string. Batch mode not supported yet."
|
139 |
+
if self.audio_placeholder in text:
|
140 |
+
if "audio_token_len" not in data:
|
141 |
+
raise ValueError(
|
142 |
+
f"audio must be provided when using audio placeholder ({self.audio_placeholder}) in text."
|
143 |
+
)
|
144 |
+
|
145 |
+
start_idx = len(
|
146 |
+
self.tokenizer.encode(
|
147 |
+
text[: text.index(self.audio_placeholder)],
|
148 |
+
add_special_tokens=False,
|
149 |
+
)
|
150 |
+
)
|
151 |
+
data["audio_token_start_idx"] = [start_idx]
|
152 |
+
text = text.replace(
|
153 |
+
self.audio_placeholder,
|
154 |
+
self.audio_token_replacement * audio_embed_frames,
|
155 |
+
)
|
156 |
+
|
157 |
+
# Special tokens like BOS should already have been added by the caller.
|
158 |
+
data.update(self.tokenizer([text], add_special_tokens=False, **kwargs))
|
159 |
+
|
160 |
+
return transformers.BatchFeature(data=data, tensor_type=return_tensors)
|
161 |
+
|
162 |
+
def batch_decode(self, *args, **kwargs):
|
163 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
164 |
+
|
165 |
+
def decode(self, *args, **kwargs):
|
166 |
+
return self.tokenizer.decode(*args, **kwargs)
|
167 |
+
|
168 |
+
@property
|
169 |
+
def model_input_names(self):
|
170 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
171 |
+
audio_processor_input_names = self.audio_processor.model_input_names
|
172 |
+
return list(set(tokenizer_input_names + audio_processor_input_names))
|
whisper_model_modified.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modified from https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py
|
2 |
+
# see this issue for the commentary: https://github.com/huggingface/transformers/issues/25744
|
3 |
+
#
|
4 |
+
# Copyright 2022 The OpenAI Authors and The HuggingFace Inc. team. All rights reserved.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
import torch
|
18 |
+
import torch.nn as nn
|
19 |
+
import transformers
|
20 |
+
import transformers.modeling_outputs
|
21 |
+
from transformers.models.whisper import modeling_whisper as whisper
|
22 |
+
|
23 |
+
|
24 |
+
class WhisperEncoder(whisper.WhisperEncoder):
|
25 |
+
"""
|
26 |
+
Encoder portion of OpenAI's Whisper model.
|
27 |
+
|
28 |
+
This implementation is a slightly modified version of HF Transformers' Whisper Encoder, with only a few fixes:
|
29 |
+
1. base_model_prefix updated to allow for doing `.from_pretrained` directly on the encoder
|
30 |
+
2. allow less than 30 second of audio padding to be passed in:
|
31 |
+
- relaxed ValueError check for `input_features` length to be less than or equal to `expected_seq_length` instead of strictly equal
|
32 |
+
- embed_pos is now sliced to match the length of `inputs_embeds`
|
33 |
+
|
34 |
+
Original: https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py
|
35 |
+
"""
|
36 |
+
|
37 |
+
base_model_prefix = "model.encoder"
|
38 |
+
|
39 |
+
def forward(
|
40 |
+
self,
|
41 |
+
input_features,
|
42 |
+
attention_mask=None,
|
43 |
+
head_mask=None,
|
44 |
+
output_attentions=None,
|
45 |
+
output_hidden_states=None,
|
46 |
+
return_dict=None,
|
47 |
+
):
|
48 |
+
expected_seq_length = (
|
49 |
+
self.config.max_source_positions
|
50 |
+
* self.conv1.stride[0]
|
51 |
+
* self.conv2.stride[0]
|
52 |
+
)
|
53 |
+
if input_features.shape[-1] > expected_seq_length:
|
54 |
+
raise ValueError(
|
55 |
+
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}."
|
56 |
+
)
|
57 |
+
|
58 |
+
output_attentions = (
|
59 |
+
output_attentions
|
60 |
+
if output_attentions is not None
|
61 |
+
else self.config.output_attentions
|
62 |
+
)
|
63 |
+
output_hidden_states = (
|
64 |
+
output_hidden_states
|
65 |
+
if output_hidden_states is not None
|
66 |
+
else self.config.output_hidden_states
|
67 |
+
)
|
68 |
+
return_dict = (
|
69 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
70 |
+
)
|
71 |
+
inputs_embeds = nn.functional.gelu(self.conv1(input_features))
|
72 |
+
inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
|
73 |
+
|
74 |
+
inputs_embeds = inputs_embeds.permute(0, 2, 1)
|
75 |
+
embed_pos = self.embed_positions.weight[: inputs_embeds.size(-2)]
|
76 |
+
|
77 |
+
hidden_states = inputs_embeds + embed_pos
|
78 |
+
hidden_states = nn.functional.dropout(
|
79 |
+
hidden_states, p=self.dropout, training=self.training
|
80 |
+
)
|
81 |
+
|
82 |
+
encoder_states = () if output_hidden_states else None
|
83 |
+
all_attentions = () if output_attentions else None
|
84 |
+
|
85 |
+
# check if head_mask has a correct number of layers specified if desired
|
86 |
+
if head_mask is not None:
|
87 |
+
assert head_mask.size()[0] == (
|
88 |
+
len(self.layers)
|
89 |
+
), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
|
90 |
+
|
91 |
+
for idx, encoder_layer in enumerate(self.layers):
|
92 |
+
if output_hidden_states:
|
93 |
+
encoder_states = encoder_states + (hidden_states,)
|
94 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
95 |
+
to_drop = False
|
96 |
+
if self.training:
|
97 |
+
dropout_probability = torch.rand([])
|
98 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
99 |
+
to_drop = True
|
100 |
+
|
101 |
+
if to_drop:
|
102 |
+
layer_outputs = (None, None)
|
103 |
+
else:
|
104 |
+
if self.gradient_checkpointing and self.training:
|
105 |
+
layer_outputs = self._gradient_checkpointing_func(
|
106 |
+
encoder_layer.__call__,
|
107 |
+
hidden_states,
|
108 |
+
None,
|
109 |
+
(head_mask[idx] if head_mask is not None else None),
|
110 |
+
output_attentions,
|
111 |
+
)
|
112 |
+
else:
|
113 |
+
layer_outputs = encoder_layer(
|
114 |
+
hidden_states,
|
115 |
+
None,
|
116 |
+
layer_head_mask=(
|
117 |
+
head_mask[idx] if head_mask is not None else None
|
118 |
+
),
|
119 |
+
output_attentions=output_attentions,
|
120 |
+
)
|
121 |
+
|
122 |
+
hidden_states = layer_outputs[0]
|
123 |
+
|
124 |
+
if output_attentions:
|
125 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
126 |
+
|
127 |
+
hidden_states = self.layer_norm(hidden_states)
|
128 |
+
if output_hidden_states:
|
129 |
+
encoder_states = encoder_states + (hidden_states,)
|
130 |
+
|
131 |
+
if not return_dict:
|
132 |
+
return tuple(
|
133 |
+
v
|
134 |
+
for v in [hidden_states, encoder_states, all_attentions]
|
135 |
+
if v is not None
|
136 |
+
)
|
137 |
+
return transformers.modeling_outputs.BaseModelOutput(
|
138 |
+
last_hidden_state=hidden_states,
|
139 |
+
hidden_states=encoder_states,
|
140 |
+
attentions=all_attentions,
|
141 |
+
)
|