huseinzol05 commited on
Commit
ac916e4
1 Parent(s): 194f09a

Upload MM_LLMs

Browse files
Files changed (5) hide show
  1. README.md +201 -0
  2. config.json +294 -0
  3. generation_config.json +4 -0
  4. model.safetensors +3 -0
  5. modeling_audio.py +257 -0
README.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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]
200
+
201
+
config.json ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "audio-alignment-tinyllama/checkpoint-5800",
3
+ "architectures": [
4
+ "MM_LLMs"
5
+ ],
6
+ "audio_config": {
7
+ "_name_or_path": "mesolitica/malaysian-whisper-small",
8
+ "activation_dropout": 0.0,
9
+ "activation_function": "gelu",
10
+ "add_cross_attention": false,
11
+ "apply_spec_augment": false,
12
+ "architectures": [
13
+ "WhisperForConditionalGeneration"
14
+ ],
15
+ "attention_dropout": 0.0,
16
+ "bad_words_ids": null,
17
+ "begin_suppress_tokens": [
18
+ 220,
19
+ 50257
20
+ ],
21
+ "bos_token_id": 50257,
22
+ "chunk_size_feed_forward": 0,
23
+ "classifier_proj_size": 256,
24
+ "cross_attention_hidden_size": null,
25
+ "d_model": 768,
26
+ "decoder_attention_heads": 12,
27
+ "decoder_ffn_dim": 3072,
28
+ "decoder_layerdrop": 0.0,
29
+ "decoder_layers": 12,
30
+ "decoder_start_token_id": 50258,
31
+ "diversity_penalty": 0.0,
32
+ "do_sample": false,
33
+ "dropout": 0.0,
34
+ "early_stopping": false,
35
+ "encoder_attention_heads": 12,
36
+ "encoder_ffn_dim": 3072,
37
+ "encoder_layerdrop": 0.0,
38
+ "encoder_layers": 12,
39
+ "encoder_no_repeat_ngram_size": 0,
40
+ "eos_token_id": 50257,
41
+ "exponential_decay_length_penalty": null,
42
+ "finetuning_task": null,
43
+ "forced_bos_token_id": null,
44
+ "forced_decoder_ids": [
45
+ [
46
+ 1,
47
+ 50259
48
+ ],
49
+ [
50
+ 2,
51
+ 50359
52
+ ],
53
+ [
54
+ 3,
55
+ 50363
56
+ ]
57
+ ],
58
+ "forced_eos_token_id": null,
59
+ "id2label": {
60
+ "0": "LABEL_0",
61
+ "1": "LABEL_1"
62
+ },
63
+ "init_std": 0.02,
64
+ "is_decoder": false,
65
+ "is_encoder_decoder": true,
66
+ "label2id": {
67
+ "LABEL_0": 0,
68
+ "LABEL_1": 1
69
+ },
70
+ "length_penalty": 1.0,
71
+ "mask_feature_length": 10,
72
+ "mask_feature_min_masks": 0,
73
+ "mask_feature_prob": 0.0,
74
+ "mask_time_length": 10,
75
+ "mask_time_min_masks": 2,
76
+ "mask_time_prob": 0.05,
77
+ "max_length": 448,
78
+ "max_source_positions": 1500,
79
+ "max_target_positions": 448,
80
+ "median_filter_width": 7,
81
+ "min_length": 0,
82
+ "model_type": "whisper",
83
+ "no_repeat_ngram_size": 0,
84
+ "num_beam_groups": 1,
85
+ "num_beams": 1,
86
+ "num_hidden_layers": 12,
87
+ "num_mel_bins": 80,
88
+ "num_return_sequences": 1,
89
+ "output_attentions": false,
90
+ "output_hidden_states": false,
91
+ "output_scores": false,
92
+ "pad_token_id": 50257,
93
+ "prefix": null,
94
+ "problem_type": null,
95
+ "pruned_heads": {},
96
+ "remove_invalid_values": false,
97
+ "repetition_penalty": 1.0,
98
+ "return_dict": true,
99
+ "return_dict_in_generate": false,
100
+ "scale_embedding": false,
101
+ "sep_token_id": null,
102
+ "suppress_tokens": [
103
+ 1,
104
+ 2,
105
+ 7,
106
+ 8,
107
+ 9,
108
+ 10,
109
+ 14,
110
+ 25,
111
+ 26,
112
+ 27,
113
+ 28,
114
+ 29,
115
+ 31,
116
+ 58,
117
+ 59,
118
+ 60,
119
+ 61,
120
+ 62,
121
+ 63,
122
+ 90,
123
+ 91,
124
+ 92,
125
+ 93,
126
+ 359,
127
+ 503,
128
+ 522,
129
+ 542,
130
+ 873,
131
+ 893,
132
+ 902,
133
+ 918,
134
+ 922,
135
+ 931,
136
+ 1350,
137
+ 1853,
138
+ 1982,
139
+ 2460,
140
+ 2627,
141
+ 3246,
142
+ 3253,
143
+ 3268,
144
+ 3536,
145
+ 3846,
146
+ 3961,
147
+ 4183,
148
+ 4667,
149
+ 6585,
150
+ 6647,
151
+ 7273,
152
+ 9061,
153
+ 9383,
154
+ 10428,
155
+ 10929,
156
+ 11938,
157
+ 12033,
158
+ 12331,
159
+ 12562,
160
+ 13793,
161
+ 14157,
162
+ 14635,
163
+ 15265,
164
+ 15618,
165
+ 16553,
166
+ 16604,
167
+ 18362,
168
+ 18956,
169
+ 20075,
170
+ 21675,
171
+ 22520,
172
+ 26130,
173
+ 26161,
174
+ 26435,
175
+ 28279,
176
+ 29464,
177
+ 31650,
178
+ 32302,
179
+ 32470,
180
+ 36865,
181
+ 42863,
182
+ 47425,
183
+ 49870,
184
+ 50254,
185
+ 50258,
186
+ 50360,
187
+ 50361,
188
+ 50362
189
+ ],
190
+ "task_specific_params": null,
191
+ "temperature": 1.0,
192
+ "tf_legacy_loss": false,
193
+ "tie_encoder_decoder": false,
194
+ "tie_word_embeddings": true,
195
+ "tokenizer_class": null,
196
+ "top_k": 50,
197
+ "top_p": 1.0,
198
+ "torch_dtype": "bfloat16",
199
+ "torchscript": false,
200
+ "typical_p": 1.0,
201
+ "use_bfloat16": false,
202
+ "use_cache": true,
203
+ "use_weighted_layer_sum": false,
204
+ "vocab_size": 51865
205
+ },
206
+ "auto_map": {
207
+ "AutoConfig": "modeling_audio.MM_LLMs_Config",
208
+ "AutoModel": "modeling_audio.MM_LLMs"
209
+ },
210
+ "llm_config": {
211
+ "_name_or_path": "mesolitica/malaysian-tinyllama-1.1b-16k-instructions-v3",
212
+ "add_cross_attention": false,
213
+ "architectures": [
214
+ "LlamaForCausalLM"
215
+ ],
216
+ "attention_bias": false,
217
+ "attention_dropout": 0.0,
218
+ "bad_words_ids": null,
219
+ "begin_suppress_tokens": null,
220
+ "bos_token_id": 1,
221
+ "chunk_size_feed_forward": 0,
222
+ "cross_attention_hidden_size": null,
223
+ "decoder_start_token_id": null,
224
+ "diversity_penalty": 0.0,
225
+ "do_sample": false,
226
+ "early_stopping": false,
227
+ "encoder_no_repeat_ngram_size": 0,
228
+ "eos_token_id": 2,
229
+ "exponential_decay_length_penalty": null,
230
+ "finetuning_task": null,
231
+ "forced_bos_token_id": null,
232
+ "forced_eos_token_id": null,
233
+ "hidden_act": "silu",
234
+ "hidden_size": 2048,
235
+ "id2label": {
236
+ "0": "LABEL_0",
237
+ "1": "LABEL_1"
238
+ },
239
+ "initializer_range": 0.02,
240
+ "intermediate_size": 5632,
241
+ "is_decoder": false,
242
+ "is_encoder_decoder": false,
243
+ "label2id": {
244
+ "LABEL_0": 0,
245
+ "LABEL_1": 1
246
+ },
247
+ "length_penalty": 1.0,
248
+ "max_length": 20,
249
+ "max_position_embeddings": 32768,
250
+ "min_length": 0,
251
+ "model_type": "llama",
252
+ "no_repeat_ngram_size": 0,
253
+ "num_attention_heads": 32,
254
+ "num_beam_groups": 1,
255
+ "num_beams": 1,
256
+ "num_hidden_layers": 22,
257
+ "num_key_value_heads": 4,
258
+ "num_return_sequences": 1,
259
+ "output_attentions": false,
260
+ "output_hidden_states": false,
261
+ "output_scores": false,
262
+ "pad_token_id": null,
263
+ "prefix": null,
264
+ "pretraining_tp": 1,
265
+ "problem_type": null,
266
+ "pruned_heads": {},
267
+ "remove_invalid_values": false,
268
+ "repetition_penalty": 1.0,
269
+ "return_dict": true,
270
+ "return_dict_in_generate": false,
271
+ "rms_norm_eps": 1e-05,
272
+ "rope_scaling": null,
273
+ "rope_theta": 10000.0,
274
+ "sep_token_id": null,
275
+ "suppress_tokens": null,
276
+ "task_specific_params": null,
277
+ "temperature": 1.0,
278
+ "tf_legacy_loss": false,
279
+ "tie_encoder_decoder": false,
280
+ "tie_word_embeddings": false,
281
+ "tokenizer_class": null,
282
+ "top_k": 50,
283
+ "top_p": 1.0,
284
+ "torch_dtype": "bfloat16",
285
+ "torchscript": false,
286
+ "typical_p": 1.0,
287
+ "use_bfloat16": false,
288
+ "use_cache": true,
289
+ "vocab_size": 32004
290
+ },
291
+ "model_type": "mm_llms",
292
+ "torch_dtype": "bfloat16",
293
+ "transformers_version": "4.37.2"
294
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.37.2"
4
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3875b2eb90aa1bd7aea8ba2faed29ed0c5896cd341c86fdad8e49e2319d02e1
3
+ size 2817909376
modeling_audio.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import Counter, defaultdict
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import Tensor
6
+ from torch import nn
7
+ from torch.nn import CrossEntropyLoss
8
+ import copy
9
+ import math
10
+ from transformers.activations import gelu
11
+ from typing import List, Optional, Tuple, Union
12
+ from transformers.modeling_utils import PreTrainedModel, PretrainedConfig
13
+ from transformers import CONFIG_MAPPING
14
+ from transformers.modeling_outputs import BaseModelOutput
15
+ from transformers import GenerationConfig
16
+ from transformers import CLIPConfig, CLIPProcessor, CLIPModel, AutoModel
17
+ from transformers import WhisperConfig, WhisperPreTrainedModel, WhisperModel
18
+ from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig
19
+
20
+
21
+ def most_frequent_element(tensor):
22
+ flattened_list = tensor.flatten().tolist()
23
+ counter = Counter(flattened_list)
24
+ most_common_element = counter.most_common(1)[0][1]
25
+
26
+ return most_common_element
27
+
28
+
29
+ class MM_LLMs_Config(PretrainedConfig):
30
+ model_type = 'mm_llms'
31
+ is_composition = True
32
+
33
+ def __init__(
34
+ self,
35
+ audio_config=None,
36
+ llm_config=None,
37
+ **kwargs
38
+ ):
39
+
40
+ self.audio_config = audio_config
41
+ self.llm_config = llm_config
42
+
43
+ if isinstance(self.audio_config, dict):
44
+ audio_config["model_type"] = (
45
+ audio_config["model_type"] if "model_type" in audio_config else "whisper"
46
+ )
47
+ self.audio_config = CONFIG_MAPPING[audio_config["model_type"]](**audio_config)
48
+ if isinstance(self.llm_config, dict):
49
+ llm_config["model_type"] = llm_config["model_type"] if "model_type" in llm_config else "llama"
50
+ self.llm_config = CONFIG_MAPPING[llm_config["model_type"]](**llm_config)
51
+
52
+ super().__init__(**kwargs)
53
+
54
+
55
+ class LlavaMultiModalProjector(nn.Module):
56
+ def __init__(self, in_hidden_size, out_hidden_size, conv_kernel=None, conv_stride=3):
57
+ super().__init__()
58
+
59
+ self.conv_kernel = conv_kernel
60
+
61
+ if conv_kernel:
62
+ self.linear_1 = nn.Conv1d(
63
+ in_hidden_size,
64
+ out_hidden_size,
65
+ kernel_size=conv_kernel,
66
+ stride=conv_stride)
67
+ else:
68
+ self.linear_1 = nn.Linear(
69
+ in_hidden_size,
70
+ out_hidden_size,
71
+ bias=True,
72
+ )
73
+ self.act = gelu
74
+ self.linear_2 = nn.Linear(
75
+ out_hidden_size,
76
+ out_hidden_size,
77
+ bias=True)
78
+
79
+ def forward(self, image_features):
80
+ hidden_states = self.linear_1(image_features)
81
+ if self.conv_kernel:
82
+ hidden_states = hidden_states.transpose(1, 2).contiguous()
83
+ hidden_states = self.act(hidden_states)
84
+ hidden_states = self.linear_2(hidden_states)
85
+ return hidden_states
86
+
87
+
88
+ class MM_LLMs(PreTrainedModel):
89
+ config_class = MM_LLMs_Config
90
+ supports_gradient_checkpointing = True
91
+ _supports_flash_attn_2 = True
92
+
93
+ def __init__(self, config, flash_attention=False, dtype=torch.float32):
94
+ super().__init__(config)
95
+ self.config = config
96
+
97
+ self.audio_encoder = AutoModel.from_config(config.audio_config)
98
+
99
+ self.llm = AutoModelForCausalLM.from_config(
100
+ config.llm_config,
101
+ use_flash_attention_2=flash_attention,
102
+ torch_dtype=dtype,
103
+ )
104
+
105
+ self.audio_projector = LlavaMultiModalProjector(
106
+ config.audio_config.d_model,
107
+ config.llm_config.hidden_size,
108
+ conv_kernel=40,
109
+ conv_stride=3,
110
+ )
111
+
112
+ def forward(self,
113
+ input_ids: torch.LongTensor = None,
114
+ image_index: torch.LongTensor = None,
115
+ audio_index: torch.LongTensor = None,
116
+ image_starts: torch.int = None,
117
+ image_ends: torch.int = None,
118
+ audio_starts: torch.int = None,
119
+ audio_ends: torch.int = None,
120
+ images: torch.FloatTensor = None,
121
+ audios: torch.FloatTensor = None,
122
+ attention_mask: Optional[torch.Tensor] = None,
123
+ position_ids: Optional[torch.LongTensor] = None,
124
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
125
+ inputs_embeds: Optional[torch.FloatTensor] = None,
126
+ labels: Optional[torch.LongTensor] = None,
127
+ output_attentions: Optional[bool] = None,
128
+ output_hidden_states: Optional[bool] = None,
129
+ use_cache: Optional[bool] = None,
130
+ return_dict: Optional[bool] = None, **kwargs):
131
+
132
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
133
+
134
+ audios = audios.type(self.audio_encoder.dtype) if audios is not None else None
135
+
136
+ model_inputs = self.prepare_inputs_for_generation(
137
+ input_ids=input_ids,
138
+ image_index=image_index,
139
+ audio_index=audio_index,
140
+ image_starts=image_starts,
141
+ image_ends=image_ends,
142
+ audio_starts=audio_starts,
143
+ audio_ends=audio_ends,
144
+ images=images,
145
+ audios=audios,
146
+ attention_mask=attention_mask,
147
+ labels=labels)
148
+
149
+ print(input_ids.shape, model_inputs['inputs_embeds'].shape)
150
+ outputs = self.llm(
151
+ inputs_embeds=model_inputs['inputs_embeds'],
152
+ attention_mask=model_inputs['attention_mask'],
153
+ labels=model_inputs['labels'],
154
+ return_dict=return_dict)
155
+
156
+ return outputs
157
+
158
+ def prepare_inputs_for_generation(
159
+ self,
160
+ input_ids,
161
+ past_key_values=None,
162
+ inputs_embeds=None,
163
+ images=None,
164
+ audios=None,
165
+ audio_starts=None,
166
+ audio_ends=None,
167
+ image_starts=None,
168
+ image_ends=None,
169
+ attention_mask=None,
170
+ labels=None,
171
+ audio_index=None,
172
+ image_index=None,
173
+ **kwargs):
174
+
175
+ audio_features = self.encode_audio(
176
+ audios) if audios is not None else None
177
+ embed_tokens = self.llm.model.embed_tokens
178
+ text_embeddings = embed_tokens(input_ids)
179
+ batch_size = text_embeddings.shape[0]
180
+ seq_len = text_embeddings.shape[1]
181
+ embed_dim = text_embeddings.shape[2]
182
+
183
+ if len(audio_index):
184
+ max_count_audio = most_frequent_element(audio_index)
185
+ else:
186
+ max_count_audio = 0
187
+
188
+ if audio_features is not None:
189
+ seq_audio = audio_features.shape[1]
190
+ else:
191
+ seq_audio = 0
192
+
193
+ audio_len = seq_audio * max_count_audio
194
+
195
+ new_len = text_embeddings.shape[1] + audio_len
196
+ final_embedding = torch.zeros(
197
+ batch_size, new_len, embed_dim,
198
+ device=text_embeddings.device,
199
+ dtype=text_embeddings.dtype
200
+ )
201
+ final_embedding[:, :seq_len] = text_embeddings
202
+ final_attention_mask = torch.zeros(
203
+ batch_size, new_len,
204
+ device=attention_mask.device,
205
+ dtype=attention_mask.dtype
206
+ )
207
+ final_attention_mask[:, :seq_len] = attention_mask
208
+ if labels is not None:
209
+ final_labels = torch.full(
210
+ (batch_size, new_len),
211
+ -100,
212
+ device=labels.device,
213
+ dtype=labels.dtype
214
+ )
215
+ final_labels[:, :seq_len] = labels
216
+ else:
217
+ final_labels = None
218
+
219
+ audio_id = int(audio_starts[0])
220
+
221
+ where_is = torch.where(input_ids == audio_id)
222
+ positions = defaultdict(int)
223
+ b_audio = 0
224
+
225
+ for i in range(len(where_is[0])):
226
+ b, k = where_is[0][i], where_is[1][i]
227
+ int_b = int(b)
228
+ int_k = int(k)
229
+ f = audio_features[b_audio]
230
+ b_audio += 1
231
+
232
+ c = torch.cat([final_embedding[b, :int_k + 1 + positions[int_b]],
233
+ f, text_embeddings[b, k + 1:]])
234
+ final_embedding[b, :len(c)] = c
235
+ final_attention_mask[b, :len(c)] = 1.0
236
+
237
+ if labels is not None:
238
+ ignore = torch.tensor([-100] * len(f), device=labels.device)
239
+ c_label = torch.cat(
240
+ [final_labels[b, :int_k + 1 + positions[int_b]], ignore, labels[b, k + 1:]])
241
+ final_labels[b, :len(c)] = c_label
242
+
243
+ positions[int_b] += len(f)
244
+
245
+ model_inputs = {
246
+ "input_ids": input_ids,
247
+ "inputs_embeds": final_embedding,
248
+ "use_cache": kwargs.get("use_cache"),
249
+ "attention_mask": final_attention_mask,
250
+ "labels": final_labels,
251
+ }
252
+ return model_inputs
253
+
254
+ def encode_audio(self, audios):
255
+ encoded = self.audio_encoder.encoder(audios)[0]
256
+ audio_features = self.audio_projector(encoded.transpose(1, 2).contiguous())
257
+ return audio_features