step 1, run_id uovmto44
Browse files- README.md +199 -0
- config.json +29 -0
- config.py +166 -0
- generation_config.json +6 -0
- model.py +727 -0
- model.safetensors +3 -0
README.md
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
tags: []
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
config.json
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"UltravoxModel"
|
4 |
+
],
|
5 |
+
"audio_latency_block_size": null,
|
6 |
+
"audio_model_id": "openai/whisper-tiny",
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "config.UltravoxConfig",
|
9 |
+
"AutoModel": "model.UltravoxModel"
|
10 |
+
},
|
11 |
+
"hidden_size": 4096,
|
12 |
+
"ignore_index": -100,
|
13 |
+
"initializer_range": 0.02,
|
14 |
+
"model_type": "ultravox",
|
15 |
+
"norm_init": 0.4,
|
16 |
+
"projector_act": "swiglu",
|
17 |
+
"stack_factor": 8,
|
18 |
+
"text_config": {
|
19 |
+
"head_dim": 2,
|
20 |
+
"hidden_size": 64,
|
21 |
+
"model_type": "llama",
|
22 |
+
"num_hidden_layers": 1,
|
23 |
+
"vocab_size": 128128
|
24 |
+
},
|
25 |
+
"text_model_id": null,
|
26 |
+
"torch_dtype": "bfloat16",
|
27 |
+
"transformers_version": "4.46.3",
|
28 |
+
"vocab_size": 128128
|
29 |
+
}
|
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.KL_Divergence
|
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
|
generation_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
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
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 team17.modeling.config import LossConfig, LossFunction, UltravoxConfig
|
17 |
+
|
18 |
+
|
19 |
+
class UltravoxModel(transformers.LlamaPreTrainedModel):
|
20 |
+
"""
|
21 |
+
The Ultravox model which consists of an audio encoder and a language model.
|
22 |
+
|
23 |
+
Audio input is processed by the audio encoder, then every `stack_factor` frames are stacked together and
|
24 |
+
projected to the language model's embedding space using a few linear layers.
|
25 |
+
The text is embedded by the language model as usual and then the audio and text embeddings are merged together.
|
26 |
+
|
27 |
+
A special token `<|audio|>` is used to indicate the start of the audio embeddings in the merged embeddings.
|
28 |
+
|
29 |
+
Parameters:
|
30 |
+
config: Model configuration class with all the parameters of the model.
|
31 |
+
"""
|
32 |
+
|
33 |
+
config_class = UltravoxConfig
|
34 |
+
config: UltravoxConfig # for type hinting
|
35 |
+
# Usually we load encoder and LLM weights from a pretrained model separately, so they are allowed to be missing
|
36 |
+
_keys_to_ignore_on_load_missing = ["audio_tower.*", "language_model.*"]
|
37 |
+
|
38 |
+
def __init__(self, config: UltravoxConfig):
|
39 |
+
super().__init__(config)
|
40 |
+
self._register_load_state_dict_pre_hook(self._pre_load_state_dict_hook)
|
41 |
+
|
42 |
+
self.keep_params: Set[str] = set()
|
43 |
+
self.vocab_size = config.vocab_size
|
44 |
+
print(config)
|
45 |
+
self.audio_tower = self._create_audio_tower(config)
|
46 |
+
self.multi_modal_projector = self._create_multi_modal_projector(config)
|
47 |
+
self.language_model = self._create_language_model(config)
|
48 |
+
|
49 |
+
# Determine no_split_modules dynamically to use with FSDP auto_wrap policy.
|
50 |
+
# FSDP throws an error if some of the layer types are not found in the model.
|
51 |
+
# This would be something like ["LlamaDecoderLayer", "WhisperEncoderLayer"]
|
52 |
+
self._no_split_modules = (self.language_model._no_split_modules or []) + (
|
53 |
+
self.audio_tower._no_split_modules or []
|
54 |
+
)
|
55 |
+
|
56 |
+
self.loss_config = LossConfig()
|
57 |
+
self.post_init()
|
58 |
+
|
59 |
+
def get_input_embeddings(self):
|
60 |
+
return self.language_model.get_input_embeddings()
|
61 |
+
|
62 |
+
def set_input_embeddings(self, value):
|
63 |
+
self.language_model.set_input_embeddings(value)
|
64 |
+
|
65 |
+
def get_output_embeddings(self):
|
66 |
+
return self.language_model.get_output_embeddings()
|
67 |
+
|
68 |
+
def set_output_embeddings(self, new_embeddings):
|
69 |
+
self.language_model.set_output_embeddings(new_embeddings)
|
70 |
+
|
71 |
+
def set_decoder(self, decoder):
|
72 |
+
self.language_model.set_decoder(decoder)
|
73 |
+
|
74 |
+
def get_decoder(self):
|
75 |
+
return self.language_model.get_decoder()
|
76 |
+
|
77 |
+
def tie_weights(self):
|
78 |
+
return self.language_model.tie_weights()
|
79 |
+
|
80 |
+
def set_loss_config(self, loss_config: LossConfig):
|
81 |
+
self.loss_config = loss_config
|
82 |
+
|
83 |
+
def _setup_cache(
|
84 |
+
self, cache_cls, max_batch_size: int, max_cache_len: Optional[int] = None
|
85 |
+
):
|
86 |
+
self.language_model._setup_cache(cache_cls, max_batch_size, max_cache_len)
|
87 |
+
|
88 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
89 |
+
return self.language_model._reorder_cache(past_key_values, beam_idx)
|
90 |
+
|
91 |
+
def resize_token_embeddings(
|
92 |
+
self,
|
93 |
+
new_num_tokens: Optional[int] = None,
|
94 |
+
pad_to_multiple_of: Optional[int] = None,
|
95 |
+
) -> nn.Embedding:
|
96 |
+
model_embeds = self.language_model.resize_token_embeddings(
|
97 |
+
new_num_tokens, pad_to_multiple_of
|
98 |
+
)
|
99 |
+
# update vocab size
|
100 |
+
self.config.text_config.vocab_size = model_embeds.num_embeddings
|
101 |
+
self.config.vocab_size = model_embeds.num_embeddings
|
102 |
+
self.vocab_size = model_embeds.num_embeddings
|
103 |
+
return model_embeds
|
104 |
+
|
105 |
+
def _compute_kl_loss(
|
106 |
+
self,
|
107 |
+
lm_output: transformers.modeling_outputs.CausalLMOutputWithPast,
|
108 |
+
labels: Optional[torch.Tensor] = None,
|
109 |
+
past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
|
110 |
+
alt_input_ids: Optional[torch.Tensor] = None,
|
111 |
+
alt_attention_mask: Optional[torch.Tensor] = None,
|
112 |
+
alt_labels: Optional[torch.Tensor] = None,
|
113 |
+
**kwargs,
|
114 |
+
):
|
115 |
+
# disable gradient computation for the teacher model
|
116 |
+
with torch.no_grad():
|
117 |
+
# compute the teacher (text-only) model's distribution
|
118 |
+
alt_inputs_embeds = self.get_input_embeddings().forward(alt_input_ids)
|
119 |
+
alt_lm_output = self.language_model.forward(
|
120 |
+
inputs_embeds=alt_inputs_embeds,
|
121 |
+
labels=alt_labels,
|
122 |
+
attention_mask=alt_attention_mask,
|
123 |
+
past_key_values=past_key_values,
|
124 |
+
**kwargs,
|
125 |
+
)
|
126 |
+
# compute the KL divergence loss between the two models
|
127 |
+
kl_loss = F.kl_div(
|
128 |
+
F.log_softmax(
|
129 |
+
lm_output.logits[labels != -100] / self.loss_config.kl_temperature,
|
130 |
+
dim=-1,
|
131 |
+
),
|
132 |
+
F.softmax(
|
133 |
+
alt_lm_output.logits[alt_labels != -100]
|
134 |
+
/ self.loss_config.kl_temperature,
|
135 |
+
dim=-1,
|
136 |
+
),
|
137 |
+
reduction="batchmean",
|
138 |
+
)
|
139 |
+
return {"loss": kl_loss}
|
140 |
+
|
141 |
+
def forward(
|
142 |
+
self,
|
143 |
+
input_ids: torch.Tensor,
|
144 |
+
audio_values: Optional[torch.FloatTensor] = None,
|
145 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
146 |
+
labels: Optional[torch.Tensor] = None,
|
147 |
+
attention_mask: Optional[torch.Tensor] = None,
|
148 |
+
audio_token_start_idx: Optional[torch.Tensor] = None,
|
149 |
+
audio_len: Optional[torch.Tensor] = None,
|
150 |
+
audio_token_len: Optional[torch.Tensor] = None,
|
151 |
+
past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
|
152 |
+
# the alt_* fields are needed for KL divergence loss
|
153 |
+
alt_input_ids: Optional[torch.Tensor] = None,
|
154 |
+
alt_attention_mask: Optional[torch.Tensor] = None,
|
155 |
+
alt_labels: Optional[torch.Tensor] = None,
|
156 |
+
**kwargs,
|
157 |
+
) -> Union[Tuple, transformers.modeling_outputs.CausalLMOutputWithPast]:
|
158 |
+
"""
|
159 |
+
Forward pass for the Ultravox model.
|
160 |
+
|
161 |
+
`input_ids` are the tokenized text input. They are embedded by the language model as usual.
|
162 |
+
`audio_values` are processed by the audio encoder and then every `stack_factor` frames are stacked together and
|
163 |
+
projected to the language model's embedding space using a few linear layers.
|
164 |
+
The audio and text embeddings are merged together. A special token `<|audio|>` is used to indicate the start
|
165 |
+
of the audio embeddings in the merged embeddings.
|
166 |
+
|
167 |
+
Args:
|
168 |
+
input_ids: The tokenized text input.
|
169 |
+
audio_values: The processed audio values.
|
170 |
+
inputs_embeds: The embeddings for the input tokens.
|
171 |
+
labels: The tokenized text labels.
|
172 |
+
attention_mask: The attention mask for the input.
|
173 |
+
position_ids: The position ids for the input.
|
174 |
+
past_key_values: The past key value cache for the language model attention layers.
|
175 |
+
**kwargs: Additional keyword arguments. Passed directly to the language model.
|
176 |
+
"""
|
177 |
+
if inputs_embeds is None:
|
178 |
+
# B x T -> B x T x D
|
179 |
+
inputs_embeds = self.get_input_embeddings().forward(input_ids)
|
180 |
+
|
181 |
+
if audio_values is not None:
|
182 |
+
assert (
|
183 |
+
audio_token_start_idx is not None and audio_token_len is not None
|
184 |
+
), "audio_token_start_idx and audio_token_len must be provided if audio_values are provided."
|
185 |
+
assert (
|
186 |
+
len(audio_token_start_idx) == len(audio_token_len) == len(audio_values)
|
187 |
+
), "audio_token_start_idx, audio_token_len, and audio_values must have the same batch size."
|
188 |
+
|
189 |
+
# B x A/3200 x D
|
190 |
+
audio_tower_output = self.audio_tower.forward(
|
191 |
+
audio_values.to(self.audio_tower.dtype),
|
192 |
+
audio_len=audio_len,
|
193 |
+
).last_hidden_state
|
194 |
+
audio_tower_output = audio_tower_output.to(inputs_embeds.dtype)
|
195 |
+
|
196 |
+
audio_embeds = self.multi_modal_projector.forward(audio_tower_output)
|
197 |
+
|
198 |
+
# combine audio and text embeddings
|
199 |
+
for i, (audio, start, length) in enumerate(
|
200 |
+
zip(audio_embeds, audio_token_start_idx, audio_token_len)
|
201 |
+
):
|
202 |
+
length = min(length, audio.shape[0])
|
203 |
+
inputs_embeds[i, start : start + length] = audio[:length]
|
204 |
+
|
205 |
+
lm_output = self.language_model.forward(
|
206 |
+
inputs_embeds=inputs_embeds,
|
207 |
+
labels=labels,
|
208 |
+
attention_mask=attention_mask,
|
209 |
+
past_key_values=past_key_values,
|
210 |
+
**kwargs,
|
211 |
+
)
|
212 |
+
if self.training:
|
213 |
+
if self.loss_config.loss_function == LossFunction.CrossEntropy:
|
214 |
+
return lm_output
|
215 |
+
elif self.loss_config.loss_function == LossFunction.KL_Divergence:
|
216 |
+
return self._compute_kl_loss(
|
217 |
+
lm_output=lm_output,
|
218 |
+
labels=labels,
|
219 |
+
past_key_values=past_key_values,
|
220 |
+
alt_input_ids=alt_input_ids,
|
221 |
+
alt_attention_mask=alt_attention_mask,
|
222 |
+
alt_labels=alt_labels,
|
223 |
+
**kwargs,
|
224 |
+
)
|
225 |
+
else:
|
226 |
+
raise ValueError(
|
227 |
+
f"Unsupported loss function: {self.loss_config.loss_function}"
|
228 |
+
)
|
229 |
+
else:
|
230 |
+
return lm_output
|
231 |
+
|
232 |
+
def prepare_inputs_for_generation(
|
233 |
+
self,
|
234 |
+
input_ids: torch.Tensor,
|
235 |
+
audio_values: Optional[torch.FloatTensor] = None,
|
236 |
+
audio_token_start_idx: Optional[torch.Tensor] = None,
|
237 |
+
audio_token_len: Optional[torch.Tensor] = None,
|
238 |
+
audio_len: Optional[torch.Tensor] = None,
|
239 |
+
past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
|
240 |
+
attention_mask: Optional[torch.Tensor] = None,
|
241 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
242 |
+
cache_position: Optional[torch.Tensor] = None,
|
243 |
+
**kwargs,
|
244 |
+
) -> Dict[str, Any]:
|
245 |
+
model_input = self.language_model.prepare_inputs_for_generation(
|
246 |
+
input_ids=input_ids,
|
247 |
+
past_key_values=past_key_values,
|
248 |
+
attention_mask=attention_mask,
|
249 |
+
inputs_embeds=inputs_embeds,
|
250 |
+
cache_position=cache_position,
|
251 |
+
**kwargs,
|
252 |
+
)
|
253 |
+
|
254 |
+
# include audio information in model_input only when it is needed during prefilling
|
255 |
+
# audio_token_start_idx should always be relative to the current cache position
|
256 |
+
prefill_start_idx = 0 if cache_position is None else cache_position[0]
|
257 |
+
if (
|
258 |
+
audio_values is not None
|
259 |
+
and audio_token_start_idx is not None
|
260 |
+
and prefill_start_idx <= torch.max(audio_token_start_idx)
|
261 |
+
):
|
262 |
+
model_input["audio_values"] = audio_values
|
263 |
+
model_input["audio_token_start_idx"] = (
|
264 |
+
audio_token_start_idx - prefill_start_idx
|
265 |
+
)
|
266 |
+
model_input["audio_token_len"] = audio_token_len
|
267 |
+
model_input["audio_len"] = audio_len
|
268 |
+
|
269 |
+
return model_input
|
270 |
+
|
271 |
+
@classmethod
|
272 |
+
def _create_multi_modal_projector(
|
273 |
+
cls, config: UltravoxConfig
|
274 |
+
) -> "UltravoxProjector":
|
275 |
+
projector = UltravoxProjector(config)
|
276 |
+
projector.to(config.torch_dtype)
|
277 |
+
return projector
|
278 |
+
|
279 |
+
@classmethod
|
280 |
+
def _create_audio_tower(
|
281 |
+
cls, config: UltravoxConfig
|
282 |
+
) -> Union[transformers.Wav2Vec2Model, "ModifiedWhisperEncoder"]:
|
283 |
+
if config.audio_model_id is not None:
|
284 |
+
if "whisper" in config.audio_model_id is not None:
|
285 |
+
audio_tower = ModifiedWhisperEncoder.from_pretrained(
|
286 |
+
config.audio_model_id, torch_dtype=config.torch_dtype
|
287 |
+
)
|
288 |
+
audio_tower.init_latency_mask(
|
289 |
+
config.audio_latency_block_size, dtype=config.torch_dtype
|
290 |
+
)
|
291 |
+
else:
|
292 |
+
assert (
|
293 |
+
config.audio_latency_block_size
|
294 |
+
not in (
|
295 |
+
None,
|
296 |
+
0,
|
297 |
+
)
|
298 |
+
), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
|
299 |
+
audio_tower = transformers.AutoModel.from_pretrained(
|
300 |
+
config.audio_model_id, torch_dtype=config.torch_dtype
|
301 |
+
)
|
302 |
+
else:
|
303 |
+
if "whisper" in config.audio_config._name_or_path:
|
304 |
+
audio_tower = ModifiedWhisperEncoder(config.audio_config)
|
305 |
+
audio_tower.init_latency_mask(
|
306 |
+
config.audio_latency_block_size, dtype=config.torch_dtype
|
307 |
+
)
|
308 |
+
else:
|
309 |
+
assert (
|
310 |
+
config.audio_latency_block_size
|
311 |
+
not in (
|
312 |
+
None,
|
313 |
+
0,
|
314 |
+
)
|
315 |
+
), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
|
316 |
+
with transformers.modeling_utils.no_init_weights():
|
317 |
+
# we only ever use from_config if the weights are retrained, hence initializing is not
|
318 |
+
# required. This makes the model quite creation faster since init on CPU is quite slow.
|
319 |
+
audio_tower = transformers.AutoModel.from_config(
|
320 |
+
config.audio_config
|
321 |
+
)
|
322 |
+
|
323 |
+
if isinstance(
|
324 |
+
audio_tower,
|
325 |
+
(transformers.Wav2Vec2BertModel, transformers.WhisperModel),
|
326 |
+
):
|
327 |
+
# For these models we only need the encoder part
|
328 |
+
# Wav2Vec2BertModel -> Wav2Vec2BertEncoder
|
329 |
+
# WhisperModel -> WhisperEncoder
|
330 |
+
audio_tower = audio_tower.encoder
|
331 |
+
|
332 |
+
audio_tower = apply_lora(audio_tower, config.audio_model_lora_config)
|
333 |
+
return audio_tower
|
334 |
+
|
335 |
+
@classmethod
|
336 |
+
def _create_language_model(
|
337 |
+
cls, config: UltravoxConfig
|
338 |
+
) -> transformers.LlamaForCausalLM:
|
339 |
+
if config.text_model_id is not None:
|
340 |
+
language_model = transformers.AutoModelForCausalLM.from_pretrained(
|
341 |
+
config.text_model_id,
|
342 |
+
attn_implementation=config._attn_implementation,
|
343 |
+
torch_dtype=config.torch_dtype,
|
344 |
+
)
|
345 |
+
else:
|
346 |
+
with transformers.modeling_utils.no_init_weights():
|
347 |
+
# we only ever use from_config if the weights are retrained, hence initializing is not
|
348 |
+
# required. This makes the model quite creation faster since init on CPU is quite slow.
|
349 |
+
language_model = transformers.AutoModelForCausalLM.from_config(
|
350 |
+
config.text_config,
|
351 |
+
attn_implementation=config._attn_implementation,
|
352 |
+
torch_dtype=config.torch_dtype,
|
353 |
+
)
|
354 |
+
|
355 |
+
language_model = apply_lora(language_model, config.text_model_lora_config)
|
356 |
+
return language_model
|
357 |
+
|
358 |
+
def merge_and_unload(self):
|
359 |
+
if isinstance(self.language_model, peft.PeftModel):
|
360 |
+
self.language_model = self.language_model.merge_and_unload()
|
361 |
+
# no need to download base language model weights anymore, so we can remove the id
|
362 |
+
self.config.text_model_id = None
|
363 |
+
self.keep_params.update(
|
364 |
+
set(
|
365 |
+
[
|
366 |
+
f"language_model.{name}"
|
367 |
+
for name, _ in self.language_model.named_parameters()
|
368 |
+
]
|
369 |
+
)
|
370 |
+
)
|
371 |
+
|
372 |
+
if isinstance(self.audio_tower, peft.PeftModel):
|
373 |
+
self.audio_tower = self.audio_tower.merge_and_unload()
|
374 |
+
# no need to download base audio model weights anymore, so we can remove the id
|
375 |
+
self.config.audio_model_id = None
|
376 |
+
self.keep_params.update(
|
377 |
+
set(
|
378 |
+
[
|
379 |
+
f"audio_tower.{name}"
|
380 |
+
for name, _ in self.audio_tower.named_parameters()
|
381 |
+
]
|
382 |
+
)
|
383 |
+
)
|
384 |
+
|
385 |
+
for param in ["text_model_lora_config", "audio_model_lora_config"]:
|
386 |
+
if hasattr(self.config, param):
|
387 |
+
delattr(self.config, param)
|
388 |
+
|
389 |
+
def push_to_hub(self, *args, **kwargs):
|
390 |
+
self.merge_and_unload()
|
391 |
+
self.to(self.language_model.dtype)
|
392 |
+
return super().push_to_hub(*args, **kwargs)
|
393 |
+
|
394 |
+
def save_pretrained(
|
395 |
+
self, *args, state_dict: Optional[Dict[str, Any]] = None, **kwargs
|
396 |
+
):
|
397 |
+
if state_dict is None:
|
398 |
+
state_dict = super().state_dict()
|
399 |
+
|
400 |
+
named_params = dict(self.named_parameters())
|
401 |
+
|
402 |
+
state_dict = {
|
403 |
+
k: v
|
404 |
+
for k, v in state_dict.items()
|
405 |
+
if k in self.keep_params
|
406 |
+
or (k in named_params and named_params[k].requires_grad)
|
407 |
+
}
|
408 |
+
|
409 |
+
super().save_pretrained(*args, state_dict=state_dict, **kwargs)
|
410 |
+
|
411 |
+
def _pre_load_state_dict_hook(self, state_dict: Dict[str, Any], *args, **kwargs):
|
412 |
+
self.keep_params.update(set(state_dict.keys()))
|
413 |
+
|
414 |
+
def print_trainable_parameters(self):
|
415 |
+
"""
|
416 |
+
Prints the number of trainable parameters in the model (reuses Peft model's method)
|
417 |
+
"""
|
418 |
+
count_params = peft.peft_model.PeftModel.get_nb_trainable_parameters
|
419 |
+
|
420 |
+
trainable_params, all_param = count_params(self)
|
421 |
+
|
422 |
+
logging.info(
|
423 |
+
f"trainable params: {trainable_params:,d} || all params: {all_param:,d}"
|
424 |
+
f" || trainable%: {100 * trainable_params / all_param:.1f}%"
|
425 |
+
)
|
426 |
+
|
427 |
+
lm_trainable_params, lm_all_params = count_params(self.language_model)
|
428 |
+
audio_trainable_params, audio_all_params = count_params(self.audio_tower)
|
429 |
+
|
430 |
+
projector_trainable_params = (
|
431 |
+
trainable_params - lm_trainable_params - audio_trainable_params
|
432 |
+
)
|
433 |
+
projector_all_params = all_param - lm_all_params - audio_all_params
|
434 |
+
|
435 |
+
logging.info(
|
436 |
+
f"Trainable%: "
|
437 |
+
f" LLM: {100 * lm_trainable_params / lm_all_params:.1f}%"
|
438 |
+
f" || Audio Encoder: {100 * audio_trainable_params / audio_all_params:.1f}%"
|
439 |
+
f" || Projector: {100 * projector_trainable_params / projector_all_params:.1f}%"
|
440 |
+
)
|
441 |
+
|
442 |
+
|
443 |
+
def is_cache_empty(
|
444 |
+
past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]],
|
445 |
+
) -> bool:
|
446 |
+
"""
|
447 |
+
Check if the cache is empty.
|
448 |
+
"""
|
449 |
+
if past_key_values is None:
|
450 |
+
return True
|
451 |
+
if isinstance(past_key_values, tuple):
|
452 |
+
return all(len(c) == 0 for c in past_key_values)
|
453 |
+
return past_key_values.get_seq_length() == 0
|
454 |
+
|
455 |
+
|
456 |
+
def apply_lora(model: torch.nn.Module, lora_config: dict) -> torch.nn.Module:
|
457 |
+
"""
|
458 |
+
Applies LoRA finetuning to the model. If the `r` parameter is set to 0, the model is frozen instead.
|
459 |
+
"""
|
460 |
+
lora_config = peft.LoraConfig(**lora_config or {})
|
461 |
+
|
462 |
+
if lora_config.r == 0:
|
463 |
+
# freeze the model entirely
|
464 |
+
for param in model.parameters():
|
465 |
+
param.requires_grad = False
|
466 |
+
else:
|
467 |
+
model = peft.get_peft_model(model, lora_config)
|
468 |
+
|
469 |
+
return model
|
470 |
+
|
471 |
+
|
472 |
+
class StackAudioFrames(nn.Module):
|
473 |
+
"""
|
474 |
+
Stack the audio embedding frames to reduce the sequence length by a factor of `stack_factor`.
|
475 |
+
|
476 |
+
The number of output frames will be `ceil(T / stack_factor) + 1` where `T` is the number of input frames.
|
477 |
+
NOTE: the extra +1 is intentional: in case the number of audio tokens are over-estimated by the processor,
|
478 |
+
we want to make sure `processor.audio_token_replacement` (i.e. EOS) doesn't get leaked into the middle of embeddings.
|
479 |
+
In most cases this extra padding will get removed in the model's forward function so it has no effect.
|
480 |
+
"""
|
481 |
+
|
482 |
+
def __init__(self, stack_factor: int = 8):
|
483 |
+
super().__init__()
|
484 |
+
self.stack_factor = stack_factor
|
485 |
+
|
486 |
+
def forward(self, audio_embeds: torch.Tensor) -> torch.Tensor:
|
487 |
+
B, T, C = audio_embeds.shape
|
488 |
+
T_pad = (T + self.stack_factor - 1) // self.stack_factor * self.stack_factor
|
489 |
+
audio_embeds = F.pad(audio_embeds, (0, 0, 0, T_pad - T + self.stack_factor))
|
490 |
+
B, T, C = audio_embeds.shape
|
491 |
+
audio_embeds = audio_embeds.view(
|
492 |
+
B, T // self.stack_factor, C * self.stack_factor
|
493 |
+
)
|
494 |
+
return audio_embeds
|
495 |
+
|
496 |
+
|
497 |
+
class RMSNorm(transformers.models.llama.modeling_llama.LlamaRMSNorm):
|
498 |
+
def __init__(self, hidden_size: int, init: float = 1, eps: float = 1e-6):
|
499 |
+
super().__init__(hidden_size=hidden_size, eps=eps)
|
500 |
+
self.weight.data.fill_(init)
|
501 |
+
|
502 |
+
|
503 |
+
class SwiGLU(nn.Module):
|
504 |
+
def forward(self, x):
|
505 |
+
x, gate = x.chunk(2, dim=-1)
|
506 |
+
return F.silu(gate) * x
|
507 |
+
|
508 |
+
|
509 |
+
class UltravoxProjector(nn.Sequential):
|
510 |
+
def __init__(self, config: UltravoxConfig):
|
511 |
+
super().__init__()
|
512 |
+
self.hidden_dim = config.hidden_size
|
513 |
+
self._pad_and_stack = StackAudioFrames(config.stack_factor)
|
514 |
+
dim = config.audio_config.hidden_size * config.stack_factor
|
515 |
+
self.ln_pre = RMSNorm(dim, init=config.norm_init)
|
516 |
+
self.linear_1 = nn.Linear(dim, self.hidden_dim, bias=False)
|
517 |
+
dim = self.hidden_dim
|
518 |
+
self.act = transformers.activations.get_activation(config.projector_act)
|
519 |
+
dim = dim // 2 if config.projector_act == "swiglu" else dim
|
520 |
+
self.linear_2 = nn.Linear(dim, config.text_config.hidden_size, bias=False)
|
521 |
+
self.ln_post = RMSNorm(config.text_config.hidden_size, init=config.norm_init)
|
522 |
+
|
523 |
+
def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
|
524 |
+
audio_features = self._pad_and_stack(audio_features)
|
525 |
+
audio_features = self.ln_pre(audio_features)
|
526 |
+
hidden_states = self.linear_1(audio_features)
|
527 |
+
hidden_states = self.act(hidden_states)
|
528 |
+
hidden_states = self.linear_2(hidden_states)
|
529 |
+
hidden_states = self.ln_post(hidden_states)
|
530 |
+
return hidden_states
|
531 |
+
|
532 |
+
|
533 |
+
class ModifiedWhisperEncoder(
|
534 |
+
whisper.WhisperEncoder, transformers.modeling_utils.ModuleUtilsMixin
|
535 |
+
):
|
536 |
+
"""
|
537 |
+
Encoder portion of OpenAI's Whisper model.
|
538 |
+
|
539 |
+
This implementation is a slightly modified version of HF Transformers' Whisper Encoder, with only a few fixes:
|
540 |
+
1. base_model_prefix updated to allow for doing `.from_pretrained` directly on the encoder
|
541 |
+
2. allow less than 30 second of audio padding to be passed in:
|
542 |
+
- relaxed ValueError check for `input_features` length to be less than or equal to `expected_seq_length` instead of strictly equal
|
543 |
+
- embed_pos is now sliced to match the length of `inputs_embeds`
|
544 |
+
|
545 |
+
Original: https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py
|
546 |
+
"""
|
547 |
+
|
548 |
+
base_model_prefix = "model.encoder"
|
549 |
+
_no_split_modules = ["WhisperEncoderLayer"]
|
550 |
+
|
551 |
+
def init_latency_mask(self, audio_latency_block_size: int, dtype: torch.dtype):
|
552 |
+
if audio_latency_block_size is None:
|
553 |
+
self.audio_streaming_mask = None
|
554 |
+
return
|
555 |
+
|
556 |
+
# maximum sequence length
|
557 |
+
max_seqlen = (
|
558 |
+
self.config.max_source_positions
|
559 |
+
* self.conv1.stride[0]
|
560 |
+
* self.conv2.stride[0]
|
561 |
+
)
|
562 |
+
assert (
|
563 |
+
max_seqlen > 0
|
564 |
+
), f"maximum sequence length must be positive, got {max_seqlen}"
|
565 |
+
assert (
|
566 |
+
max_seqlen % audio_latency_block_size == 0
|
567 |
+
), f"audio_latency_block_size {audio_latency_block_size} must divide {max_seqlen} evenly."
|
568 |
+
# Given the block size, we calculate number of blocks.
|
569 |
+
audio_latency_nblocks = max_seqlen // audio_latency_block_size
|
570 |
+
audio_streaming_mask = (
|
571 |
+
torch.tril(
|
572 |
+
torch.ones(audio_latency_nblocks, audio_latency_nblocks),
|
573 |
+
diagonal=0,
|
574 |
+
)
|
575 |
+
.repeat_interleave(audio_latency_block_size, dim=0)
|
576 |
+
.repeat_interleave(audio_latency_block_size, dim=1)
|
577 |
+
)
|
578 |
+
audio_streaming_mask = (1.0 - audio_streaming_mask) * torch.finfo(dtype).min
|
579 |
+
audio_streaming_mask = audio_streaming_mask[None, None, :, :]
|
580 |
+
self.register_buffer(
|
581 |
+
"audio_streaming_mask", audio_streaming_mask, persistent=False
|
582 |
+
)
|
583 |
+
|
584 |
+
def forward(
|
585 |
+
self,
|
586 |
+
input_features,
|
587 |
+
audio_len=None,
|
588 |
+
head_mask=None,
|
589 |
+
output_attentions=None,
|
590 |
+
output_hidden_states=None,
|
591 |
+
return_dict=None,
|
592 |
+
):
|
593 |
+
expected_seq_length = (
|
594 |
+
self.config.max_source_positions
|
595 |
+
* self.conv1.stride[0]
|
596 |
+
* self.conv2.stride[0]
|
597 |
+
)
|
598 |
+
if input_features.shape[-1] > expected_seq_length:
|
599 |
+
raise ValueError(
|
600 |
+
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}."
|
601 |
+
)
|
602 |
+
|
603 |
+
output_attentions = (
|
604 |
+
output_attentions
|
605 |
+
if output_attentions is not None
|
606 |
+
else self.config.output_attentions
|
607 |
+
)
|
608 |
+
output_hidden_states = (
|
609 |
+
output_hidden_states
|
610 |
+
if output_hidden_states is not None
|
611 |
+
else self.config.output_hidden_states
|
612 |
+
)
|
613 |
+
return_dict = (
|
614 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
615 |
+
)
|
616 |
+
inputs_embeds = nn.functional.gelu(self.conv1(input_features))
|
617 |
+
inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
|
618 |
+
|
619 |
+
inputs_embeds = inputs_embeds.permute(0, 2, 1)
|
620 |
+
embed_pos = self.embed_positions.weight[: inputs_embeds.size(-2)]
|
621 |
+
|
622 |
+
hidden_states = inputs_embeds + embed_pos
|
623 |
+
hidden_states = nn.functional.dropout(
|
624 |
+
hidden_states, p=self.dropout, training=self.training
|
625 |
+
)
|
626 |
+
|
627 |
+
encoder_states = () if output_hidden_states else None
|
628 |
+
all_attentions = () if output_attentions else None
|
629 |
+
|
630 |
+
# Create attention mask based on audio lengths to mask out padding tokens
|
631 |
+
# For each sample in batch:
|
632 |
+
# - Convert raw audio length to feature length after convolutions
|
633 |
+
# - Create boolean mask that is True for valid positions and False for padding
|
634 |
+
# - Convert to extended attention mask format expected by transformer layers
|
635 |
+
# (1.0 for positions to attend to, large negative for positions to ignore)
|
636 |
+
# This masking ensures consistent behavior between training and inference
|
637 |
+
# by preventing the model from attending to padding tokens in both cases
|
638 |
+
attention_mask = None
|
639 |
+
if audio_len is not None:
|
640 |
+
audio_feature_len = self._get_feat_extract_output_lengths(audio_len)
|
641 |
+
max_seq_len = hidden_states.shape[1]
|
642 |
+
attention_mask = torch.arange(max_seq_len, device=hidden_states.device)[
|
643 |
+
None, :
|
644 |
+
].lt(audio_feature_len.view(-1, 1))
|
645 |
+
attention_mask = self.get_extended_attention_mask(
|
646 |
+
attention_mask,
|
647 |
+
None,
|
648 |
+
device=hidden_states.device,
|
649 |
+
dtype=hidden_states.dtype,
|
650 |
+
)
|
651 |
+
|
652 |
+
if self.audio_streaming_mask is not None:
|
653 |
+
seqlen = hidden_states.size(-2)
|
654 |
+
if attention_mask is not None:
|
655 |
+
attention_mask = torch.minimum(
|
656 |
+
self.audio_streaming_mask[:, :, :seqlen, :seqlen], attention_mask
|
657 |
+
) # merge
|
658 |
+
else:
|
659 |
+
attention_mask = self.audio_streaming_mask[:, :, :seqlen, :seqlen]
|
660 |
+
attention_mask = attention_mask.to(hidden_states.dtype)
|
661 |
+
|
662 |
+
# check if head_mask has a correct number of layers specified if desired
|
663 |
+
if head_mask is not None:
|
664 |
+
assert (
|
665 |
+
head_mask.size()[0] == (len(self.layers))
|
666 |
+
), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
|
667 |
+
|
668 |
+
for idx, encoder_layer in enumerate(self.layers):
|
669 |
+
if output_hidden_states:
|
670 |
+
encoder_states = encoder_states + (hidden_states,)
|
671 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
672 |
+
to_drop = False
|
673 |
+
if self.training:
|
674 |
+
dropout_probability = torch.rand([])
|
675 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
676 |
+
to_drop = True
|
677 |
+
|
678 |
+
if to_drop:
|
679 |
+
layer_outputs = (None, None)
|
680 |
+
else:
|
681 |
+
if self.gradient_checkpointing and self.training:
|
682 |
+
layer_outputs = self._gradient_checkpointing_func(
|
683 |
+
encoder_layer.__call__,
|
684 |
+
hidden_states,
|
685 |
+
attention_mask,
|
686 |
+
(head_mask[idx] if head_mask is not None else None),
|
687 |
+
output_attentions,
|
688 |
+
)
|
689 |
+
else:
|
690 |
+
layer_outputs = encoder_layer(
|
691 |
+
hidden_states,
|
692 |
+
attention_mask,
|
693 |
+
layer_head_mask=(
|
694 |
+
head_mask[idx] if head_mask is not None else None
|
695 |
+
),
|
696 |
+
output_attentions=output_attentions,
|
697 |
+
)
|
698 |
+
|
699 |
+
hidden_states = layer_outputs[0]
|
700 |
+
|
701 |
+
if output_attentions:
|
702 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
703 |
+
|
704 |
+
hidden_states = self.layer_norm(hidden_states)
|
705 |
+
if output_hidden_states:
|
706 |
+
encoder_states = encoder_states + (hidden_states,)
|
707 |
+
|
708 |
+
if not return_dict:
|
709 |
+
return tuple(
|
710 |
+
v
|
711 |
+
for v in [hidden_states, encoder_states, all_attentions]
|
712 |
+
if v is not None
|
713 |
+
)
|
714 |
+
return transformers.modeling_outputs.BaseModelOutput(
|
715 |
+
last_hidden_state=hidden_states,
|
716 |
+
hidden_states=encoder_states,
|
717 |
+
attentions=all_attentions,
|
718 |
+
)
|
719 |
+
|
720 |
+
|
721 |
+
UltravoxConfig.register_for_auto_class()
|
722 |
+
UltravoxModel.register_for_auto_class()
|
723 |
+
|
724 |
+
transformers.AutoConfig.register("ultravox", UltravoxConfig)
|
725 |
+
transformers.AutoModel.register(UltravoxConfig, UltravoxModel)
|
726 |
+
|
727 |
+
transformers.activations.ACT2FN["swiglu"] = SwiGLU
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b98801d56507f1f4289adb66703a71da5bd07b29d1786abebff40203d3756af4
|
3 |
+
size 60501952
|