elyx commited on
Commit
8ffb4a7
·
verified ·
1 Parent(s): 4dcb805

step 500, run_id ybu66h2v

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