huseinzol05 commited on
Commit
56fc297
1 Parent(s): 71b9b87

Upload MM_LLMs

Browse files
Files changed (5) hide show
  1. README.md +201 -0
  2. config.json +306 -0
  3. generation_config.json +4 -0
  4. model.safetensors +3 -0
  5. modeling_vision.py +255 -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,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "vision-tinyllama/checkpoint-1050",
3
+ "architectures": [
4
+ "MM_LLMs"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "modeling_vision.MM_LLMs_Config",
8
+ "AutoModel": "modeling_vision.MM_LLMs"
9
+ },
10
+ "image_config": {
11
+ "_name_or_path": "google/siglip-base-patch16-384",
12
+ "add_cross_attention": false,
13
+ "architectures": [
14
+ "SiglipModel"
15
+ ],
16
+ "bad_words_ids": null,
17
+ "begin_suppress_tokens": null,
18
+ "bos_token_id": null,
19
+ "chunk_size_feed_forward": 0,
20
+ "cross_attention_hidden_size": null,
21
+ "decoder_start_token_id": null,
22
+ "diversity_penalty": 0.0,
23
+ "do_sample": false,
24
+ "early_stopping": false,
25
+ "encoder_no_repeat_ngram_size": 0,
26
+ "eos_token_id": null,
27
+ "exponential_decay_length_penalty": null,
28
+ "finetuning_task": null,
29
+ "forced_bos_token_id": null,
30
+ "forced_eos_token_id": null,
31
+ "id2label": {
32
+ "0": "LABEL_0",
33
+ "1": "LABEL_1"
34
+ },
35
+ "initializer_factor": 1.0,
36
+ "is_decoder": false,
37
+ "is_encoder_decoder": false,
38
+ "label2id": {
39
+ "LABEL_0": 0,
40
+ "LABEL_1": 1
41
+ },
42
+ "length_penalty": 1.0,
43
+ "max_length": 20,
44
+ "min_length": 0,
45
+ "model_type": "siglip",
46
+ "no_repeat_ngram_size": 0,
47
+ "num_beam_groups": 1,
48
+ "num_beams": 1,
49
+ "num_return_sequences": 1,
50
+ "output_attentions": false,
51
+ "output_hidden_states": false,
52
+ "output_scores": false,
53
+ "pad_token_id": null,
54
+ "prefix": null,
55
+ "problem_type": null,
56
+ "pruned_heads": {},
57
+ "remove_invalid_values": false,
58
+ "repetition_penalty": 1.0,
59
+ "return_dict": true,
60
+ "return_dict_in_generate": false,
61
+ "sep_token_id": null,
62
+ "suppress_tokens": null,
63
+ "task_specific_params": null,
64
+ "temperature": 1.0,
65
+ "text_config": {
66
+ "_name_or_path": "",
67
+ "add_cross_attention": false,
68
+ "architectures": null,
69
+ "attention_dropout": 0.0,
70
+ "bad_words_ids": null,
71
+ "begin_suppress_tokens": null,
72
+ "bos_token_id": 49406,
73
+ "chunk_size_feed_forward": 0,
74
+ "cross_attention_hidden_size": null,
75
+ "decoder_start_token_id": null,
76
+ "diversity_penalty": 0.0,
77
+ "do_sample": false,
78
+ "early_stopping": false,
79
+ "encoder_no_repeat_ngram_size": 0,
80
+ "eos_token_id": 49407,
81
+ "exponential_decay_length_penalty": null,
82
+ "finetuning_task": null,
83
+ "forced_bos_token_id": null,
84
+ "forced_eos_token_id": null,
85
+ "hidden_act": "gelu_pytorch_tanh",
86
+ "hidden_size": 768,
87
+ "id2label": {
88
+ "0": "LABEL_0",
89
+ "1": "LABEL_1"
90
+ },
91
+ "intermediate_size": 3072,
92
+ "is_decoder": false,
93
+ "is_encoder_decoder": false,
94
+ "label2id": {
95
+ "LABEL_0": 0,
96
+ "LABEL_1": 1
97
+ },
98
+ "layer_norm_eps": 1e-06,
99
+ "length_penalty": 1.0,
100
+ "max_length": 20,
101
+ "max_position_embeddings": 64,
102
+ "min_length": 0,
103
+ "model_type": "siglip_text_model",
104
+ "no_repeat_ngram_size": 0,
105
+ "num_attention_heads": 12,
106
+ "num_beam_groups": 1,
107
+ "num_beams": 1,
108
+ "num_hidden_layers": 12,
109
+ "num_return_sequences": 1,
110
+ "output_attentions": false,
111
+ "output_hidden_states": false,
112
+ "output_scores": false,
113
+ "pad_token_id": 1,
114
+ "prefix": null,
115
+ "problem_type": null,
116
+ "pruned_heads": {},
117
+ "remove_invalid_values": false,
118
+ "repetition_penalty": 1.0,
119
+ "return_dict": true,
120
+ "return_dict_in_generate": false,
121
+ "sep_token_id": null,
122
+ "suppress_tokens": null,
123
+ "task_specific_params": null,
124
+ "temperature": 1.0,
125
+ "tf_legacy_loss": false,
126
+ "tie_encoder_decoder": false,
127
+ "tie_word_embeddings": true,
128
+ "tokenizer_class": null,
129
+ "top_k": 50,
130
+ "top_p": 1.0,
131
+ "torch_dtype": null,
132
+ "torchscript": false,
133
+ "typical_p": 1.0,
134
+ "use_bfloat16": false,
135
+ "vocab_size": 32000
136
+ },
137
+ "tf_legacy_loss": false,
138
+ "tie_encoder_decoder": false,
139
+ "tie_word_embeddings": true,
140
+ "tokenizer_class": null,
141
+ "top_k": 50,
142
+ "top_p": 1.0,
143
+ "torch_dtype": "float32",
144
+ "torchscript": false,
145
+ "typical_p": 1.0,
146
+ "use_bfloat16": false,
147
+ "vision_config": {
148
+ "_name_or_path": "",
149
+ "add_cross_attention": false,
150
+ "architectures": null,
151
+ "attention_dropout": 0.0,
152
+ "bad_words_ids": null,
153
+ "begin_suppress_tokens": null,
154
+ "bos_token_id": null,
155
+ "chunk_size_feed_forward": 0,
156
+ "cross_attention_hidden_size": null,
157
+ "decoder_start_token_id": null,
158
+ "diversity_penalty": 0.0,
159
+ "do_sample": false,
160
+ "early_stopping": false,
161
+ "encoder_no_repeat_ngram_size": 0,
162
+ "eos_token_id": null,
163
+ "exponential_decay_length_penalty": null,
164
+ "finetuning_task": null,
165
+ "forced_bos_token_id": null,
166
+ "forced_eos_token_id": null,
167
+ "hidden_act": "gelu_pytorch_tanh",
168
+ "hidden_size": 768,
169
+ "id2label": {
170
+ "0": "LABEL_0",
171
+ "1": "LABEL_1"
172
+ },
173
+ "image_size": 384,
174
+ "intermediate_size": 3072,
175
+ "is_decoder": false,
176
+ "is_encoder_decoder": false,
177
+ "label2id": {
178
+ "LABEL_0": 0,
179
+ "LABEL_1": 1
180
+ },
181
+ "layer_norm_eps": 1e-06,
182
+ "length_penalty": 1.0,
183
+ "max_length": 20,
184
+ "min_length": 0,
185
+ "model_type": "siglip_vision_model",
186
+ "no_repeat_ngram_size": 0,
187
+ "num_attention_heads": 12,
188
+ "num_beam_groups": 1,
189
+ "num_beams": 1,
190
+ "num_channels": 3,
191
+ "num_hidden_layers": 12,
192
+ "num_return_sequences": 1,
193
+ "output_attentions": false,
194
+ "output_hidden_states": false,
195
+ "output_scores": false,
196
+ "pad_token_id": null,
197
+ "patch_size": 16,
198
+ "prefix": null,
199
+ "problem_type": null,
200
+ "pruned_heads": {},
201
+ "remove_invalid_values": false,
202
+ "repetition_penalty": 1.0,
203
+ "return_dict": true,
204
+ "return_dict_in_generate": false,
205
+ "sep_token_id": null,
206
+ "suppress_tokens": null,
207
+ "task_specific_params": null,
208
+ "temperature": 1.0,
209
+ "tf_legacy_loss": false,
210
+ "tie_encoder_decoder": false,
211
+ "tie_word_embeddings": true,
212
+ "tokenizer_class": null,
213
+ "top_k": 50,
214
+ "top_p": 1.0,
215
+ "torch_dtype": null,
216
+ "torchscript": false,
217
+ "typical_p": 1.0,
218
+ "use_bfloat16": false
219
+ }
220
+ },
221
+ "llm_config": {
222
+ "_name_or_path": "mesolitica/malaysian-tinyllama-1.1b-16k-instructions-v3",
223
+ "add_cross_attention": false,
224
+ "architectures": [
225
+ "LlamaForCausalLM"
226
+ ],
227
+ "attention_bias": false,
228
+ "attention_dropout": 0.0,
229
+ "bad_words_ids": null,
230
+ "begin_suppress_tokens": null,
231
+ "bos_token_id": 1,
232
+ "chunk_size_feed_forward": 0,
233
+ "cross_attention_hidden_size": null,
234
+ "decoder_start_token_id": null,
235
+ "diversity_penalty": 0.0,
236
+ "do_sample": false,
237
+ "early_stopping": false,
238
+ "encoder_no_repeat_ngram_size": 0,
239
+ "eos_token_id": 2,
240
+ "exponential_decay_length_penalty": null,
241
+ "finetuning_task": null,
242
+ "forced_bos_token_id": null,
243
+ "forced_eos_token_id": null,
244
+ "hidden_act": "silu",
245
+ "hidden_size": 2048,
246
+ "id2label": {
247
+ "0": "LABEL_0",
248
+ "1": "LABEL_1"
249
+ },
250
+ "initializer_range": 0.02,
251
+ "intermediate_size": 5632,
252
+ "is_decoder": false,
253
+ "is_encoder_decoder": false,
254
+ "label2id": {
255
+ "LABEL_0": 0,
256
+ "LABEL_1": 1
257
+ },
258
+ "length_penalty": 1.0,
259
+ "max_length": 20,
260
+ "max_position_embeddings": 32768,
261
+ "min_length": 0,
262
+ "model_type": "llama",
263
+ "no_repeat_ngram_size": 0,
264
+ "num_attention_heads": 32,
265
+ "num_beam_groups": 1,
266
+ "num_beams": 1,
267
+ "num_hidden_layers": 22,
268
+ "num_key_value_heads": 4,
269
+ "num_return_sequences": 1,
270
+ "output_attentions": false,
271
+ "output_hidden_states": false,
272
+ "output_scores": false,
273
+ "pad_token_id": null,
274
+ "prefix": null,
275
+ "pretraining_tp": 1,
276
+ "problem_type": null,
277
+ "pruned_heads": {},
278
+ "remove_invalid_values": false,
279
+ "repetition_penalty": 1.0,
280
+ "return_dict": true,
281
+ "return_dict_in_generate": false,
282
+ "rms_norm_eps": 1e-05,
283
+ "rope_scaling": null,
284
+ "rope_theta": 10000.0,
285
+ "sep_token_id": null,
286
+ "suppress_tokens": null,
287
+ "task_specific_params": null,
288
+ "temperature": 1.0,
289
+ "tf_legacy_loss": false,
290
+ "tie_encoder_decoder": false,
291
+ "tie_word_embeddings": false,
292
+ "tokenizer_class": null,
293
+ "top_k": 50,
294
+ "top_p": 1.0,
295
+ "torch_dtype": "bfloat16",
296
+ "torchscript": false,
297
+ "typical_p": 1.0,
298
+ "use_bfloat16": false,
299
+ "use_cache": true,
300
+ "vocab_size": 32004
301
+ },
302
+ "model_type": "mm_llms",
303
+ "torch_dtype": "bfloat16",
304
+ "transformers_version": "4.37.2",
305
+ "vision_select_layer": -2
306
+ }
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:474b1f2200e952c6aafdf1514c27fd32773ee02d72be0dec9ac1fa0d9d539483
3
+ size 2618646516
modeling_vision.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ image_config=None,
36
+ llm_config=None,
37
+ vision_select_layer=None,
38
+ **kwargs
39
+ ):
40
+
41
+ self.image_config = image_config
42
+ self.llm_config = llm_config
43
+ self.vision_select_layer = vision_select_layer
44
+
45
+ if isinstance(self.image_config, dict):
46
+ image_config["model_type"] = (
47
+ image_config["model_type"] if "model_type" in image_config else "clip"
48
+ )
49
+ self.image_config = CONFIG_MAPPING[image_config["model_type"]](**image_config)
50
+
51
+ if isinstance(self.llm_config, dict):
52
+ llm_config["model_type"] = llm_config["model_type"] if "model_type" in llm_config else "llama"
53
+ self.llm_config = CONFIG_MAPPING[llm_config["model_type"]](**llm_config)
54
+
55
+ super().__init__(**kwargs)
56
+
57
+
58
+ class LlavaMultiModalProjector(nn.Module):
59
+ def __init__(self, in_hidden_size, out_hidden_size, conv_kernel=None, conv_stride=3):
60
+ super().__init__()
61
+
62
+ self.conv_kernel = conv_kernel
63
+
64
+ if conv_kernel:
65
+ self.linear_1 = nn.Conv1d(
66
+ in_hidden_size,
67
+ out_hidden_size,
68
+ kernel_size=conv_kernel,
69
+ stride=conv_stride)
70
+ else:
71
+ self.linear_1 = nn.Linear(
72
+ in_hidden_size,
73
+ out_hidden_size,
74
+ bias=True,
75
+ )
76
+ self.act = gelu
77
+ self.linear_2 = nn.Linear(
78
+ out_hidden_size,
79
+ out_hidden_size,
80
+ bias=True
81
+ )
82
+
83
+ def forward(self, image_features):
84
+ hidden_states = self.linear_1(image_features)
85
+ if self.conv_kernel:
86
+ hidden_states = hidden_states.transpose(1, 2).contiguous()
87
+ hidden_states = self.act(hidden_states)
88
+ hidden_states = self.linear_2(hidden_states)
89
+ return hidden_states
90
+
91
+
92
+ class MM_LLMs(PreTrainedModel):
93
+ config_class = MM_LLMs_Config
94
+ supports_gradient_checkpointing = True
95
+ _supports_flash_attn_2 = True
96
+
97
+ def __init__(self, config, flash_attention=False, dtype=torch.float32):
98
+ super().__init__(config)
99
+ self.config = config
100
+
101
+ self.image_encoder = AutoModel.from_config(config.image_config)
102
+
103
+ self.llm = AutoModelForCausalLM.from_config(
104
+ config.llm_config,
105
+ use_flash_attention_2=flash_attention,
106
+ torch_dtype=dtype,
107
+ )
108
+
109
+ self.image_projector = LlavaMultiModalProjector(
110
+ config.image_config.vision_config.hidden_size,
111
+ config.llm_config.hidden_size
112
+ )
113
+
114
+ def forward(self,
115
+ input_ids: torch.LongTensor = None,
116
+ image_index: torch.LongTensor = None,
117
+ audio_index: torch.LongTensor = None,
118
+ image_starts: torch.int = None,
119
+ image_ends: torch.int = None,
120
+ audio_starts: torch.int = None,
121
+ audio_ends: torch.int = None,
122
+ images: torch.FloatTensor = None,
123
+ audios: torch.FloatTensor = None,
124
+ attention_mask: Optional[torch.Tensor] = None,
125
+ position_ids: Optional[torch.LongTensor] = None,
126
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
127
+ inputs_embeds: Optional[torch.FloatTensor] = None,
128
+ labels: Optional[torch.LongTensor] = None,
129
+ output_attentions: Optional[bool] = None,
130
+ output_hidden_states: Optional[bool] = None,
131
+ use_cache: Optional[bool] = None,
132
+ return_dict: Optional[bool] = None, **kwargs):
133
+
134
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
135
+
136
+ images = images.type(self.image_encoder.dtype) if images is not None else None
137
+ audios = audios.type(self.audio_encoder.dtype) if audios is not None else None
138
+
139
+ model_inputs = self.prepare_inputs_for_generation(
140
+ input_ids=input_ids,
141
+ image_index=image_index,
142
+ audio_index=audio_index,
143
+ image_starts=image_starts,
144
+ image_ends=image_ends,
145
+ audio_starts=audio_starts,
146
+ audio_ends=audio_ends,
147
+ images=images,
148
+ audios=audios,
149
+ attention_mask=attention_mask,
150
+ labels=labels)
151
+
152
+ outputs = self.llm(
153
+ inputs_embeds=model_inputs['inputs_embeds'],
154
+ attention_mask=model_inputs['attention_mask'],
155
+ labels=model_inputs['labels'],
156
+ return_dict=return_dict)
157
+
158
+ return outputs
159
+
160
+ def prepare_inputs_for_generation(
161
+ self,
162
+ input_ids,
163
+ past_key_values=None,
164
+ inputs_embeds=None,
165
+ images=None,
166
+ audios=None,
167
+ audio_starts=None,
168
+ audio_ends=None,
169
+ image_starts=None,
170
+ image_ends=None,
171
+ attention_mask=None,
172
+ labels=None,
173
+ audio_index=None,
174
+ image_index=None,
175
+ **kwargs):
176
+
177
+ image_features = self.encode_image(
178
+ images) if images is not None else None
179
+ embed_tokens = self.llm.model.embed_tokens
180
+ text_embeddings = embed_tokens(input_ids)
181
+ batch_size = text_embeddings.shape[0]
182
+ seq_len = text_embeddings.shape[1]
183
+ embed_dim = text_embeddings.shape[2]
184
+
185
+ max_count_image = most_frequent_element(image_index)
186
+ seq_image = image_features.shape[1]
187
+
188
+ new_len = text_embeddings.shape[1] + seq_image * max_count_image
189
+ final_embedding = torch.zeros(
190
+ batch_size, new_len, embed_dim,
191
+ device=text_embeddings.device,
192
+ dtype=text_embeddings.dtype
193
+ )
194
+ final_embedding[:, :seq_len] = text_embeddings
195
+ final_attention_mask = torch.zeros(
196
+ batch_size, new_len,
197
+ device=attention_mask.device,
198
+ dtype=attention_mask.dtype
199
+ )
200
+ final_attention_mask[:, :seq_len] = attention_mask
201
+ if labels is not None:
202
+ final_labels = torch.full(
203
+ (batch_size, new_len),
204
+ -100,
205
+ device=labels.device,
206
+ dtype=labels.dtype
207
+ )
208
+ final_labels[:, :seq_len] = labels
209
+ else:
210
+ final_labels = None
211
+
212
+ image_id = int(image_starts[0])
213
+
214
+ where_is = torch.where(input_ids == image_id)
215
+ positions = defaultdict(int)
216
+ b_image = 0
217
+
218
+ for i in range(len(where_is[0])):
219
+ b, k = where_is[0][i], where_is[1][i]
220
+ int_b = int(b)
221
+ int_k = int(k)
222
+ l = int(input_ids[b, k])
223
+ f = image_features[b_image]
224
+ b_image += 1
225
+
226
+ c = torch.cat([final_embedding[b, :int_k + 1 + positions[int_b]],
227
+ f, text_embeddings[b, k + 1:]])
228
+ final_embedding[b, :len(c)] = c
229
+ final_attention_mask[b, :len(c)] = 1.0
230
+
231
+ if labels is not None:
232
+ ignore = torch.tensor([-100] * len(f), device=labels.device)
233
+ c_label = torch.cat(
234
+ [final_labels[b, :int_k + 1 + positions[int_b]], ignore, labels[b, k + 1:]])
235
+ final_labels[b, :len(c)] = c_label
236
+
237
+ positions[int_b] += len(f)
238
+
239
+ model_inputs = {
240
+ "input_ids": input_ids,
241
+ "inputs_embeds": final_embedding,
242
+ "use_cache": kwargs.get("use_cache"),
243
+ "attention_mask": final_attention_mask,
244
+ "labels": final_labels,
245
+ }
246
+ return model_inputs
247
+
248
+ def encode_image(self, images):
249
+ if self.config.vision_select_layer is not None:
250
+ encoded = self.image_encoder.vision_model(images, output_hidden_states=True)
251
+ encoded = encoded.hidden_states[self.config.vision_select_layer]
252
+ else:
253
+ encoded = self.image_encoder.vision_model(images)[0]
254
+ image_features = self.image_projector(encoded)
255
+ return image_features