Ligeng-Zhu commited on
Commit
13f83b4
1 Parent(s): 6ec6724

Upload files with huggingface_hub

Browse files

Upload utils.py
Upload configuration_llava.py
Upload llava_llama.py
Upload config.json
Upload trainer_state.json
Upload README.md
Upload builder.py
Upload llava_arch.py
Upload constants.py
Upload llm/tokenizer_config.json
Upload llm/tokenizer.model
Upload llm/config.json
Upload llm/generation_config.json
Upload llm/model-00001-of-00002.safetensors
Upload llm/model.safetensors.index.json
Upload llm/special_tokens_map.json
Upload llm/model-00002-of-00002.safetensors
Upload mm_projector/model.safetensors
Upload mm_projector/config.json
Upload vision_tower/model.safetensors
Upload vision_tower/config.json
Upload vision_tower/preprocessor_config.json

README.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ library_name: transformers
4
+ pipeline_tag: text-generation
5
+ tags:
6
+ - VILA
7
+ - VLM
8
+ ---
9
+
10
+ # VILA Model Card
11
+
12
+ ## Model details
13
+
14
+ **Model type:**
15
+ VILA is a visual language model (VLM) pretrained with interleaved image-text data at scale, enabling multi-image VLM. VILA is deployable on the edge, including Jetson Orin and laptop by AWQ 4bit quantization through TinyChat framework. We find: (1) image-text pairs are not enough, interleaved image-text is essential; (2) unfreezing LLM during interleaved image-text pre-training enables in-context learning; (3)re-blending text-only instruction data is crucial to boost both VLM and text-only performance. VILA unveils appealing capabilities, including: multi-image reasoning, in-context learning, visual chain-of-thought, and better world knowledge.
16
+
17
+ **Model date:**
18
+ VILA1.5-3b was trained in May 2024.
19
+
20
+ **Paper or resources for more information:**
21
+ https://github.com/Efficient-Large-Model/VILA
22
+
23
+ ```
24
+ @misc{lin2023vila,
25
+ title={VILA: On Pre-training for Visual Language Models},
26
+ author={Ji Lin and Hongxu Yin and Wei Ping and Yao Lu and Pavlo Molchanov and Andrew Tao and Huizi Mao and Jan Kautz and Mohammad Shoeybi and Song Han},
27
+ year={2023},
28
+ eprint={2312.07533},
29
+ archivePrefix={arXiv},
30
+ primaryClass={cs.CV}
31
+ }
32
+ ```
33
+
34
+ ## License
35
+ - The code is released under the Apache 2.0 license as found in the [LICENSE](./LICENSE) file.
36
+ - The pretrained weights are released under the [CC-BY-NC-SA-4.0 license](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en).
37
+ - The service is a research preview intended for non-commercial use only, and is subject to the following licenses and terms:
38
+ - [Model License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA
39
+ - [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI
40
+ - [Dataset Licenses](https://github.com/Efficient-Large-Model/VILA/blob/main/data_prepare/LICENSE) for each one used during training.
41
+
42
+ **Where to send questions or comments about the model:**
43
+ https://github.com/Efficient-Large-Model/VILA/issues
44
+
45
+ ## Intended use
46
+ **Primary intended uses:**
47
+ The primary use of VILA is research on large multimodal models and chatbots.
48
+
49
+ **Primary intended users:**
50
+ The primary intended users of the model are researchers and hobbyists in computer vision, natural language processing, machine learning, and artificial intelligence.
51
+
52
+ ## Training dataset
53
+ See [Dataset Preparation](https://github.com/Efficient-Large-Model/VILA/blob/main/data_prepare/README.md) for more details.
54
+
55
+ ## Evaluation dataset
56
+ A collection of 12 benchmarks, including 5 academic VQA benchmarks and 7 recent benchmarks specifically proposed for instruction-following LMMs.
builder.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
2
+ # Copyright 2023 Haotian Liu
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ import os
18
+ import shutil
19
+ import warnings
20
+
21
+ import torch
22
+ from transformers import (AutoConfig, AutoModelForCausalLM, AutoTokenizer,
23
+ BitsAndBytesConfig, PretrainedConfig)
24
+
25
+ from .llava_llama import LlavaLlamaModel
26
+
27
+ # from llava.model import *
28
+ # from llava.model.utils import is_mm_model
29
+
30
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
31
+ WORKER_HEART_BEAT_INTERVAL = 15
32
+
33
+ LOGDIR = "."
34
+
35
+ # Model Constants
36
+ IGNORE_INDEX = -100
37
+ IMAGE_TOKEN_INDEX = -200
38
+ DEFAULT_IMAGE_TOKEN = "<image>"
39
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
40
+ DEFAULT_IM_START_TOKEN = "<im_start>"
41
+ DEFAULT_IM_END_TOKEN = "<im_end>"
42
+ IMAGE_PLACEHOLDER = "<image-placeholder>"
43
+
44
+
45
+ def is_mm_model(model_path):
46
+ """
47
+ Check if the model at the given path is a visual language model.
48
+
49
+ Args:
50
+ model_path (str): The path to the model.
51
+
52
+ Returns:
53
+ bool: True if the model is an MM model, False otherwise.
54
+ """
55
+ config = AutoConfig.from_pretrained(model_path)
56
+ architectures = config.architectures
57
+ for architecture in architectures:
58
+ if "llava" in architecture.lower():
59
+ return True
60
+ return False
61
+
62
+
63
+ def load_pretrained_model(
64
+ model_path,
65
+ model_name,
66
+ model_base=None,
67
+ load_8bit=False,
68
+ load_4bit=False,
69
+ device_map="auto",
70
+ device="cuda",
71
+ **kwargs,
72
+ ):
73
+ kwargs = {"device_map": device_map, **kwargs}
74
+
75
+ if device != "cuda":
76
+ kwargs["device_map"] = {"": device}
77
+
78
+ if load_8bit:
79
+ kwargs["load_in_8bit"] = True
80
+ elif load_4bit:
81
+ kwargs["load_in_4bit"] = True
82
+ kwargs["quantization_config"] = BitsAndBytesConfig(
83
+ load_in_4bit=True,
84
+ bnb_4bit_compute_dtype=torch.float16,
85
+ bnb_4bit_use_double_quant=True,
86
+ bnb_4bit_quant_type="nf4",
87
+ )
88
+ else:
89
+ kwargs["torch_dtype"] = torch.float16
90
+ # kwargs["torch_dtype"] = torch.bfloat16
91
+
92
+ if is_mm_model(model_path):
93
+ # Load LLaVA model
94
+ ## TODO @yunhao: mind fixing lora
95
+ if "lora" in model_name.lower() and model_base is None:
96
+ warnings.warn(
97
+ "There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged."
98
+ )
99
+ if (
100
+ "lora" in model_name.lower() or "dora" in model_name.lower()
101
+ ) and model_base is not None:
102
+ lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
103
+ print(lora_cfg_pretrained)
104
+ print("Loading LLaVA from base model...")
105
+ config = AutoConfig.from_pretrained(model_base)
106
+ prepare_config_for_eval(config, kwargs)
107
+ model = LlavaLlamaModel.from_pretrained(
108
+ model_base, low_cpu_mem_usage=True, config=config, **kwargs
109
+ )
110
+ tokenizer = model.tokenizer
111
+ token_num, tokem_dim = (
112
+ model.llm.lm_head.out_features,
113
+ model.llm.lm_head.in_features,
114
+ )
115
+ if model.llm.lm_head.weight.shape[0] != token_num:
116
+ model.llm.lm_head.weight = torch.nn.Parameter(
117
+ torch.empty(
118
+ token_num, tokem_dim, device=model.device, dtype=model.dtype
119
+ )
120
+ )
121
+ model.llm.embed_tokens.weight = torch.nn.Parameter(
122
+ torch.empty(
123
+ token_num, tokem_dim, device=model.device, dtype=model.dtype
124
+ )
125
+ )
126
+
127
+ print("Loading additional LLaVA weights...")
128
+ if os.path.exists(os.path.join(model_path, "non_lora_trainables.bin")):
129
+ non_lora_trainables = torch.load(
130
+ os.path.join(model_path, "non_lora_trainables.bin"),
131
+ map_location="cpu",
132
+ )
133
+ else:
134
+ # this is probably from HF Hub
135
+ from huggingface_hub import hf_hub_download
136
+
137
+ def load_from_hf(repo_id, filename, subfolder=None):
138
+ cache_file = hf_hub_download(
139
+ repo_id=repo_id, filename=filename, subfolder=subfolder
140
+ )
141
+ return torch.load(cache_file, map_location="cpu")
142
+
143
+ non_lora_trainables = load_from_hf(
144
+ model_path, "non_lora_trainables.bin"
145
+ )
146
+ non_lora_trainables = {
147
+ (k[11:] if k.startswith("base_model.") else k): v
148
+ for k, v in non_lora_trainables.items()
149
+ }
150
+ if any(k.startswith("model.model.") for k in non_lora_trainables):
151
+ non_lora_trainables = {
152
+ (k[6:] if k.startswith("model.") else k): v
153
+ for k, v in non_lora_trainables.items()
154
+ }
155
+ model.load_state_dict(non_lora_trainables, strict=False)
156
+
157
+ from peft import PeftModel
158
+
159
+ print("Loading LoRA weights...")
160
+ model = PeftModel.from_pretrained(model, model_path)
161
+ print("Merging LoRA weights...")
162
+ model = model.merge_and_unload()
163
+ print("Model is loaded...")
164
+ ## TODO @yunhao: mind fixing this
165
+ elif model_base is not None:
166
+ # this may be mm projector only
167
+ print("Loading LLaVA from base model...")
168
+ cfg_pretrained = AutoConfig.from_pretrained(
169
+ model_path, trust_remote_code=True
170
+ )
171
+ mm_config_wrapper(config, kwargs)
172
+ if "mpt" in model_name.lower():
173
+ if not os.path.isfile(os.path.join(model_path, "configuration_mpt.py")):
174
+ shutil.copyfile(
175
+ os.path.join(model_base, "configuration_mpt.py"),
176
+ os.path.join(model_path, "configuration_mpt.py"),
177
+ )
178
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
179
+ model = LlavaMPTForCausalLM.from_pretrained(
180
+ model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs
181
+ )
182
+ else:
183
+ tokenizer = AutoTokenizer.from_pretrained(
184
+ model_base, use_fast=False, legacy=False
185
+ )
186
+ model = LlavaLlamaForCausalLM.from_pretrained(
187
+ model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs
188
+ )
189
+ else:
190
+ config = AutoConfig.from_pretrained(model_path)
191
+ config.resume_path = model_path
192
+ prepare_config_for_eval(config, kwargs)
193
+ if "mpt" in model_name.lower():
194
+ model = LlavaMPTForCausalLM.from_pretrained(
195
+ model_path, config=config, low_cpu_mem_usage=True, **kwargs
196
+ )
197
+ elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
198
+ model = LlavaMistralForCausalLM.from_pretrained(
199
+ model_path, config=config, low_cpu_mem_usage=True, **kwargs
200
+ )
201
+ elif "gemma" in model_name.lower():
202
+ model = LlavaGemmaForCausalLM.from_pretrained(
203
+ model_path, config=config, low_cpu_mem_usage=True, **kwargs
204
+ )
205
+ else:
206
+ # kentang-mit@: llama-2 model
207
+ # config._attn_implementation = "flash_attention_2"
208
+ model = LlavaLlamaModel(config=config, low_cpu_mem_usage=True, **kwargs)
209
+ tokenizer = model.tokenizer
210
+ else:
211
+ # Load language model
212
+ if model_base is not None:
213
+ # PEFT model
214
+ from peft import PeftModel
215
+
216
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
217
+ model = AutoModelForCausalLM.from_pretrained(
218
+ model_base, low_cpu_mem_usage=True, **kwargs
219
+ )
220
+ print(f"Loading LoRA weights from {model_path}")
221
+ model = PeftModel.from_pretrained(model, model_path)
222
+ print(f"Merging weights")
223
+ model = model.merge_and_unload()
224
+ print("Convert to FP16...")
225
+ model.to(torch.float16)
226
+ else:
227
+ if "mpt" in model_name.lower():
228
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
229
+ model = AutoModelForCausalLM.from_pretrained(
230
+ model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs
231
+ )
232
+ else:
233
+ tokenizer = AutoTokenizer.from_pretrained(
234
+ model_path, use_fast=False, legacy=False
235
+ )
236
+ model = AutoModelForCausalLM.from_pretrained(
237
+ model_path, low_cpu_mem_usage=True, **kwargs
238
+ )
239
+ model.eval()
240
+ image_processor = None
241
+ if is_mm_model(model_path):
242
+ mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
243
+ mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
244
+ if mm_use_im_patch_token:
245
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
246
+ if mm_use_im_start_end:
247
+ tokenizer.add_tokens(
248
+ [DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True
249
+ )
250
+ model.resize_token_embeddings(len(tokenizer))
251
+ vision_tower = model.get_vision_tower()
252
+ vision_tower.to(device=device, dtype=torch.float16)
253
+ # vision_tower.to(device=device, dtype=torch.bfloat16)
254
+ mm_projector = model.get_mm_projector()
255
+ mm_projector.to(device=device, dtype=torch.float16)
256
+ # mm_projector.to(device=device, dtype=torch.bfloat16)
257
+ image_processor = vision_tower.image_processor
258
+
259
+ if hasattr(model.llm.config, "max_sequence_length"):
260
+ context_len = model.config.max_sequence_length
261
+ else:
262
+ context_len = 2048
263
+
264
+ return tokenizer, model, image_processor, context_len
265
+
266
+
267
+ def parse_model_name_or_path(config: PretrainedConfig, model_name="llm", suffix="_cfg"):
268
+ target_model = f"{model_name}{suffix}"
269
+ target_cfg = getattr(config, target_model, None)
270
+
271
+ if isinstance(target_cfg, str):
272
+ return target_cfg
273
+ elif isinstance(target_cfg, dict):
274
+ return target_cfg["architectures"][0]
275
+ else:
276
+ raise ValueError(f"Invalid {target_model} configuration!")
277
+
278
+
279
+ def prepare_config_for_eval(config: PretrainedConfig, kwargs: dict):
280
+ try:
281
+ # compatible with deprecated config convention
282
+ if getattr(config, "vision_tower_cfg", None) is None:
283
+ config.vision_tower_cfg = config.mm_vision_tower
284
+ except AttributeError:
285
+ raise ValueError(
286
+ f"Invalid configuration! Cannot find vision_tower in config:\n{config}"
287
+ )
288
+
289
+ config.model_dtype = kwargs.pop("torch_dtype").__str__()
290
+ # siglip does not support device_map = "auto"
291
+ vision_tower_name = parse_model_name_or_path(config, "vision_tower")
292
+ if "siglip" in vision_tower_name.lower():
293
+ kwargs["device_map"] = "cuda"
config.json ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./vlm",
3
+ "architectures": [
4
+ "LlavaLlamaModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "llava_llama.LlavaLlamaConfig",
8
+ "AutoModel": "llava_llama.LlavaLlamaModel"
9
+ },
10
+ "drop_path_rate": 0.0,
11
+ "hidden_size": 2560,
12
+ "image_aspect_ratio": "resize",
13
+ "interpolate_mode": "linear",
14
+ "llm_cfg": {
15
+ "_name_or_path": "./llm",
16
+ "add_cross_attention": false,
17
+ "architectures": [
18
+ "LlamaForCausalLM"
19
+ ],
20
+ "attention_bias": false,
21
+ "attention_dropout": 0.0,
22
+ "bad_words_ids": null,
23
+ "begin_suppress_tokens": null,
24
+ "bos_token_id": 1,
25
+ "chunk_size_feed_forward": 0,
26
+ "cross_attention_hidden_size": null,
27
+ "decoder_start_token_id": null,
28
+ "diversity_penalty": 0.0,
29
+ "do_sample": false,
30
+ "early_stopping": false,
31
+ "encoder_no_repeat_ngram_size": 0,
32
+ "eos_token_id": 2,
33
+ "exponential_decay_length_penalty": null,
34
+ "finetuning_task": null,
35
+ "forced_bos_token_id": null,
36
+ "forced_eos_token_id": null,
37
+ "hidden_act": "silu",
38
+ "hidden_size": 2560,
39
+ "id2label": {
40
+ "0": "LABEL_0",
41
+ "1": "LABEL_1"
42
+ },
43
+ "initializer_range": 0.02,
44
+ "intermediate_size": 6912,
45
+ "is_decoder": false,
46
+ "is_encoder_decoder": false,
47
+ "label2id": {
48
+ "LABEL_0": 0,
49
+ "LABEL_1": 1
50
+ },
51
+ "length_penalty": 1.0,
52
+ "max_length": 20,
53
+ "max_position_embeddings": 4096,
54
+ "min_length": 0,
55
+ "model_max_length": 4096,
56
+ "model_type": "llama",
57
+ "no_repeat_ngram_size": 0,
58
+ "num_attention_heads": 20,
59
+ "num_beam_groups": 1,
60
+ "num_beams": 1,
61
+ "num_hidden_layers": 32,
62
+ "num_key_value_heads": 20,
63
+ "num_return_sequences": 1,
64
+ "output_attentions": false,
65
+ "output_hidden_states": false,
66
+ "output_scores": false,
67
+ "pad_token_id": 0,
68
+ "prefix": null,
69
+ "pretraining_tp": 1,
70
+ "problem_type": null,
71
+ "pruned_heads": {},
72
+ "remove_invalid_values": false,
73
+ "repetition_penalty": 1.0,
74
+ "return_dict": true,
75
+ "return_dict_in_generate": false,
76
+ "rms_norm_eps": 1e-05,
77
+ "rope_scaling": null,
78
+ "rope_theta": 10000.0,
79
+ "sep_token_id": null,
80
+ "suppress_tokens": null,
81
+ "task_specific_params": null,
82
+ "temperature": 1.0,
83
+ "tf_legacy_loss": false,
84
+ "tie_encoder_decoder": false,
85
+ "tie_word_embeddings": false,
86
+ "tokenizer_class": null,
87
+ "tokenizer_model_max_length": 4096,
88
+ "tokenizer_padding_side": "right",
89
+ "top_k": 50,
90
+ "top_p": 1.0,
91
+ "torch_dtype": "bfloat16",
92
+ "torchscript": false,
93
+ "typical_p": 1.0,
94
+ "use_bfloat16": false,
95
+ "use_cache": true,
96
+ "vocab_size": 32000
97
+ },
98
+ "mm_hidden_size": 1152,
99
+ "mm_projector_cfg": {
100
+ "_name_or_path": "./mm_projector",
101
+ "add_cross_attention": false,
102
+ "architectures": [
103
+ "MultimodalProjector"
104
+ ],
105
+ "bad_words_ids": null,
106
+ "begin_suppress_tokens": null,
107
+ "bos_token_id": null,
108
+ "chunk_size_feed_forward": 0,
109
+ "cross_attention_hidden_size": null,
110
+ "decoder_start_token_id": null,
111
+ "diversity_penalty": 0.0,
112
+ "do_sample": false,
113
+ "early_stopping": false,
114
+ "encoder_no_repeat_ngram_size": 0,
115
+ "eos_token_id": null,
116
+ "exponential_decay_length_penalty": null,
117
+ "finetuning_task": null,
118
+ "forced_bos_token_id": null,
119
+ "forced_eos_token_id": null,
120
+ "id2label": {
121
+ "0": "LABEL_0",
122
+ "1": "LABEL_1"
123
+ },
124
+ "is_decoder": false,
125
+ "is_encoder_decoder": false,
126
+ "label2id": {
127
+ "LABEL_0": 0,
128
+ "LABEL_1": 1
129
+ },
130
+ "length_penalty": 1.0,
131
+ "max_length": 20,
132
+ "min_length": 0,
133
+ "mm_projector_type": "mlp_downsample",
134
+ "model_type": "v2l_projector",
135
+ "no_repeat_ngram_size": 0,
136
+ "num_beam_groups": 1,
137
+ "num_beams": 1,
138
+ "num_return_sequences": 1,
139
+ "output_attentions": false,
140
+ "output_hidden_states": false,
141
+ "output_scores": false,
142
+ "pad_token_id": null,
143
+ "prefix": null,
144
+ "problem_type": null,
145
+ "pruned_heads": {},
146
+ "remove_invalid_values": false,
147
+ "repetition_penalty": 1.0,
148
+ "return_dict": true,
149
+ "return_dict_in_generate": false,
150
+ "sep_token_id": null,
151
+ "suppress_tokens": null,
152
+ "task_specific_params": null,
153
+ "temperature": 1.0,
154
+ "tf_legacy_loss": false,
155
+ "tie_encoder_decoder": false,
156
+ "tie_word_embeddings": true,
157
+ "tokenizer_class": null,
158
+ "top_k": 50,
159
+ "top_p": 1.0,
160
+ "torch_dtype": "bfloat16",
161
+ "torchscript": false,
162
+ "typical_p": 1.0,
163
+ "use_bfloat16": false
164
+ },
165
+ "mm_projector_lr": null,
166
+ "mm_use_im_patch_token": false,
167
+ "mm_use_im_start_end": false,
168
+ "mm_vision_select_feature": "cls_patch",
169
+ "mm_vision_select_layer": -2,
170
+ "model_dtype": "torch.bfloat16",
171
+ "model_type": "llava_llama",
172
+ "num_video_frames": 8,
173
+ "resume_path": "./vlm",
174
+ "s2": false,
175
+ "s2_max_split_size": 336,
176
+ "s2_scales": "336,672,1008",
177
+ "transformers_version": "4.36.2",
178
+ "tune_language_model": true,
179
+ "tune_mm_projector": true,
180
+ "tune_vision_tower": true,
181
+ "vision_resolution": -1,
182
+ "vision_tower_cfg": {
183
+ "_name_or_path": "./vision_tower",
184
+ "add_cross_attention": false,
185
+ "architectures": [
186
+ "SiglipVisionModel"
187
+ ],
188
+ "attention_dropout": 0.0,
189
+ "bad_words_ids": null,
190
+ "begin_suppress_tokens": null,
191
+ "bos_token_id": null,
192
+ "chunk_size_feed_forward": 0,
193
+ "cross_attention_hidden_size": null,
194
+ "decoder_start_token_id": null,
195
+ "diversity_penalty": 0.0,
196
+ "do_sample": false,
197
+ "early_stopping": false,
198
+ "encoder_no_repeat_ngram_size": 0,
199
+ "eos_token_id": null,
200
+ "exponential_decay_length_penalty": null,
201
+ "finetuning_task": null,
202
+ "forced_bos_token_id": null,
203
+ "forced_eos_token_id": null,
204
+ "hidden_act": "gelu_pytorch_tanh",
205
+ "hidden_size": 1152,
206
+ "id2label": {
207
+ "0": "LABEL_0",
208
+ "1": "LABEL_1"
209
+ },
210
+ "image_size": 384,
211
+ "intermediate_size": 4304,
212
+ "is_decoder": false,
213
+ "is_encoder_decoder": false,
214
+ "label2id": {
215
+ "LABEL_0": 0,
216
+ "LABEL_1": 1
217
+ },
218
+ "layer_norm_eps": 1e-06,
219
+ "length_penalty": 1.0,
220
+ "max_length": 20,
221
+ "min_length": 0,
222
+ "model_type": "siglip_vision_model",
223
+ "no_repeat_ngram_size": 0,
224
+ "num_attention_heads": 16,
225
+ "num_beam_groups": 1,
226
+ "num_beams": 1,
227
+ "num_channels": 3,
228
+ "num_hidden_layers": 27,
229
+ "num_return_sequences": 1,
230
+ "output_attentions": false,
231
+ "output_hidden_states": false,
232
+ "output_scores": false,
233
+ "pad_token_id": null,
234
+ "patch_size": 14,
235
+ "prefix": null,
236
+ "problem_type": null,
237
+ "pruned_heads": {},
238
+ "remove_invalid_values": false,
239
+ "repetition_penalty": 1.0,
240
+ "return_dict": true,
241
+ "return_dict_in_generate": false,
242
+ "sep_token_id": null,
243
+ "suppress_tokens": null,
244
+ "task_specific_params": null,
245
+ "temperature": 1.0,
246
+ "tf_legacy_loss": false,
247
+ "tie_encoder_decoder": false,
248
+ "tie_word_embeddings": true,
249
+ "tokenizer_class": null,
250
+ "top_k": 50,
251
+ "top_p": 1.0,
252
+ "torch_dtype": "bfloat16",
253
+ "torchscript": false,
254
+ "typical_p": 1.0,
255
+ "use_bfloat16": false
256
+ }
257
+ }
configuration_llava.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class LlavaConfig(PretrainedConfig):
5
+ model_type = "llava"
6
+
7
+ def __init__(
8
+ self,
9
+ llm_cfg=None,
10
+ vision_tower_cfg=None,
11
+ mm_projector_cfg=None,
12
+ architectures=None,
13
+ resume_path=None,
14
+ hidden_size=None,
15
+ mm_hidden_size=None,
16
+ image_aspect_ratio=None,
17
+ num_video_frames=None,
18
+ fps=None,
19
+ mm_vision_select_layer=None,
20
+ mm_vision_select_feature=None,
21
+ mm_use_im_start_end=False,
22
+ mm_use_im_patch_token=True,
23
+ mm_projector_lr=None,
24
+ vision_resolution=None,
25
+ interpolate_mode=None,
26
+ s2=None,
27
+ s2_scales=None,
28
+ s2_max_split_size=None,
29
+ **kwargs
30
+ ):
31
+ super().__init__(**kwargs)
32
+ self.architectures = architectures
33
+ self.llm_cfg = llm_cfg
34
+ self.vision_tower_cfg = vision_tower_cfg
35
+ self.mm_projector_cfg = mm_projector_cfg
36
+ self.resume_path = resume_path
37
+
38
+ self.hidden_size = hidden_size
39
+ self.mm_hidden_size = mm_hidden_size
40
+ self.image_aspect_ratio = image_aspect_ratio
41
+ self.num_video_frames = num_video_frames
42
+ self.fps = fps
43
+ self.mm_vision_select_layer = mm_vision_select_layer
44
+ self.mm_vision_select_feature = mm_vision_select_feature
45
+ self.mm_use_im_start_end = mm_use_im_start_end
46
+ self.mm_use_im_start_end = mm_use_im_start_end
47
+ self.mm_use_im_patch_token = mm_use_im_patch_token
48
+ self.mm_projector_lr = mm_projector_lr
49
+ self.vision_resolution = vision_resolution
50
+ self.interpolate_mode = interpolate_mode
51
+ self.s2 = s2
52
+ self.s2_scales = s2_scales
53
+ self.s2_max_split_size = s2_max_split_size
constants.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
18
+
19
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
20
+ WORKER_HEART_BEAT_INTERVAL = 15
21
+
22
+ LOGDIR = "."
23
+
24
+ # Model Constants
25
+ IGNORE_INDEX = -100
26
+ IMAGE_TOKEN_INDEX = -200
27
+ DEFAULT_IMAGE_TOKEN = "<image>"
28
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
29
+ DEFAULT_IM_START_TOKEN = "<im_start>"
30
+ DEFAULT_IM_END_TOKEN = "<im_end>"
31
+ IMAGE_PLACEHOLDER = "<image-placeholder>"
llava_arch.py ADDED
@@ -0,0 +1,1552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ import math
17
+ import os
18
+ import os.path as osp
19
+ import sys
20
+ import warnings
21
+ from abc import ABC, abstractmethod
22
+ from collections import OrderedDict
23
+ from typing import Tuple
24
+
25
+ import torch
26
+ import torch.distributed as dist
27
+ import torch.nn as nn
28
+ from huggingface_hub import file_exists, repo_exists, snapshot_download
29
+ from huggingface_hub.utils import HFValidationError, validate_repo_id
30
+ from transformers import (AutoConfig, AutoModel, AutoModelForCausalLM,
31
+ AutoTokenizer, BitsAndBytesConfig, PretrainedConfig,
32
+ PreTrainedModel, PreTrainedTokenizer)
33
+ from transformers.modeling_utils import ContextManagers, no_init_weights
34
+
35
+ from .configuration_llava import LlavaConfig
36
+
37
+ # from .constants import DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IMAGE_PATCH_TOKEN
38
+
39
+
40
+ # from .model.language_model.builder import build_llm_and_tokenizer
41
+ # from .model.multimodal_encoder.builder import build_vision_tower
42
+ # from .model.multimodal_projector.builder import build_mm_projector
43
+
44
+ DEFAULT_IMAGE_TOKEN = "<image>"
45
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
46
+ DEFAULT_IM_START_TOKEN = "<im_start>"
47
+ DEFAULT_IM_END_TOKEN = "<im_end>"
48
+ IMAGE_PLACEHOLDER = "<image-placeholder>"
49
+
50
+
51
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
52
+ import torch
53
+ # from llava.model.multimodal_encoder.vision_encoder import (VisionTower, VisionTowerS2)
54
+ from transformers import CLIPImageProcessor, CLIPVisionModel, PretrainedConfig
55
+
56
+
57
+ class VisionTower(nn.Module):
58
+ def __init__(self, vision_tower, args, delay_load=False):
59
+ super().__init__()
60
+
61
+ self.is_loaded = False
62
+
63
+ self.vision_tower_name = vision_tower
64
+ self.select_layer = getattr(args, "mm_vision_select_layer", -2)
65
+ self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
66
+
67
+ self.cfg_only = None
68
+
69
+ def feature_select(self, image_forward_outs):
70
+ image_features = image_forward_outs.hidden_states[self.select_layer]
71
+ if self.select_feature == "patch":
72
+ image_features = image_features[:, 1:]
73
+ elif self.select_feature == "cls_patch":
74
+ image_features = image_features
75
+ else:
76
+ raise ValueError(f"Unexpected select feature: {self.select_feature}")
77
+ return image_features
78
+
79
+ def _maybe_resize_pos_embeds(
80
+ self,
81
+ model: PreTrainedModel,
82
+ image_processor,
83
+ resolution: int = -1,
84
+ interpolate_mode: str = "linear",
85
+ ):
86
+ if resolution in [model.config.image_size, -1]:
87
+ return
88
+ print(
89
+ f"Resizing vision model's position embeddings to support higher vision resolution: from {model.config.image_size} to {resolution} ..."
90
+ )
91
+ embeddings = model.vision_model.embeddings
92
+ patch_size = embeddings.patch_size
93
+ num_new_tokens = int((resolution // patch_size) ** 2)
94
+
95
+ old_embeddings = embeddings.position_embedding
96
+ match interpolate_mode:
97
+ case "linear":
98
+ ## Step 1: Calculate the corresponding patch ID (pid) in the current resolution (M patches) based on the target resolution (N patches). Formula: pid = pid / N * M
99
+ ## Step 2: Obtain new embeddings by interpolating between the embeddings of the two nearest calculated patch IDs. Formula: new_embeds = (pid - floor(pid)) * embeds[ceil(pid)] + (ceil(pid) - pid) * embeds[floor(pid)]
100
+ import torch
101
+ import torch.nn as nn
102
+
103
+ if is_deepspeed_zero3_enabled():
104
+ import deepspeed
105
+
106
+ with deepspeed.zero.GatheredParameters(
107
+ [old_embeddings.weight], modifier_rank=None
108
+ ):
109
+ old_num_tokens, old_embedding_dim = old_embeddings.weight.size()
110
+ else:
111
+ old_num_tokens, old_embedding_dim = old_embeddings.weight.size()
112
+ new_embeddings = nn.Embedding(
113
+ num_new_tokens,
114
+ old_embedding_dim,
115
+ dtype=old_embeddings.weight.dtype,
116
+ device=old_embeddings.weight.device,
117
+ )
118
+ mapped_indices = (
119
+ torch.arange(num_new_tokens).to(old_embeddings.weight.device)
120
+ / (num_new_tokens - 1)
121
+ * (old_num_tokens - 1)
122
+ )
123
+ floor_indices = torch.clamp(
124
+ mapped_indices.floor().long(), min=0, max=old_num_tokens - 1
125
+ )
126
+ ceil_indices = torch.clamp(
127
+ mapped_indices.ceil().long(), min=0, max=old_num_tokens - 1
128
+ )
129
+ if is_deepspeed_zero3_enabled():
130
+ params = [old_embeddings.weight, new_embeddings.weight]
131
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
132
+ interpolated_embeds = (mapped_indices - floor_indices)[
133
+ :, None
134
+ ] * old_embeddings.weight.data[ceil_indices, :] + (
135
+ ceil_indices - mapped_indices
136
+ )[
137
+ :, None
138
+ ] * old_embeddings.weight.data[
139
+ floor_indices, :
140
+ ]
141
+ else:
142
+ interpolated_embeds = (mapped_indices - floor_indices)[
143
+ :, None
144
+ ] * old_embeddings.weight.data[ceil_indices, :] + (
145
+ ceil_indices - mapped_indices
146
+ )[
147
+ :, None
148
+ ] * old_embeddings.weight.data[
149
+ floor_indices, :
150
+ ]
151
+ new_embeddings.weight.data = interpolated_embeds
152
+ case _:
153
+ raise NotImplementedError
154
+
155
+ if hasattr(old_embeddings, "_hf_hook"):
156
+ hook = old_embeddings._hf_hook
157
+ add_hook_to_module(new_embeddings, hook)
158
+ new_embeddings.requires_grad_(old_embeddings.weight.requires_grad)
159
+ ## update vision encoder's configurations
160
+ model.config.image_size = resolution
161
+ if hasattr(image_processor, "crop_size"):
162
+ # CLIP vision tower
163
+ image_processor.crop_size = resolution
164
+ else:
165
+ # SIGLIP vision tower
166
+ assert hasattr(image_processor, "size")
167
+ image_processor.size = {"height": resolution, "width": resolution}
168
+ ## TODO define a '_reinitialize' method for VisionTower
169
+ embeddings.position_embedding = new_embeddings
170
+ embeddings.image_size = resolution
171
+ embeddings.num_patches = embeddings.num_positions = num_new_tokens
172
+ embeddings.position_ids = (
173
+ torch.arange(embeddings.num_positions)
174
+ .expand((1, -1))
175
+ .to(old_embeddings.weight.device)
176
+ )
177
+
178
+ def forward(self, images):
179
+ if type(images) is list:
180
+ image_features = []
181
+ for image in images:
182
+ image_forward_out = self.vision_tower(
183
+ image.to(device=self.device, dtype=self.dtype).unsqueeze(0),
184
+ output_hidden_states=True,
185
+ )
186
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
187
+ image_features.append(image_feature)
188
+ else:
189
+ image_forward_outs = self.vision_tower(
190
+ images.to(device=self.device, dtype=self.dtype),
191
+ output_hidden_states=True,
192
+ )
193
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
194
+
195
+ return image_features
196
+
197
+ @property
198
+ def dummy_feature(self):
199
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
200
+
201
+ @property
202
+ def dtype(self):
203
+ return self.vision_tower.dtype
204
+
205
+ @property
206
+ def device(self):
207
+ return self.vision_tower.device
208
+
209
+ @property
210
+ def config(self):
211
+ if self.is_loaded:
212
+ return self.vision_tower.config
213
+ else:
214
+ return self.cfg_only
215
+
216
+ @property
217
+ def hidden_size(self):
218
+ return self.config.hidden_size
219
+
220
+ @property
221
+ def num_patches(self):
222
+ return (self.config.image_size // self.config.patch_size) ** 2
223
+
224
+
225
+ class VisionTowerS2(VisionTower):
226
+ def __init__(self, vision_tower, args, delay_load=False):
227
+ super().__init__(vision_tower, args, delay_load)
228
+
229
+ self.scales = list(map(int, args.s2_scales.split(",")))
230
+ self.scales.sort()
231
+ self.max_split_size = args.s2_max_split_size
232
+
233
+ @torch.no_grad()
234
+ def forward_feature(self, images):
235
+ image_forward_outs = self.vision_tower(
236
+ images.to(device=self.device, dtype=self.dtype), output_hidden_states=True
237
+ )
238
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
239
+ return image_features
240
+
241
+ @torch.no_grad()
242
+ def forward(self, images):
243
+ if type(images) is list:
244
+ image_features = []
245
+ for image in images:
246
+ image_feature = multiscale_forward(
247
+ self.forward_feature,
248
+ image.unsqueeze(0),
249
+ img_sizes=self.scales,
250
+ max_split_size=self.max_split_size,
251
+ )
252
+ image_features.append(image_feature)
253
+ else:
254
+ image_features = multiscale_forward(
255
+ self.forward_feature,
256
+ images,
257
+ img_sizes=self.scales,
258
+ max_split_size=self.max_split_size,
259
+ )
260
+
261
+ return image_features
262
+
263
+ @property
264
+ def hidden_size(self):
265
+ return self.config.hidden_size * len(self.scales)
266
+
267
+
268
+ class CLIPVisionTower(VisionTower):
269
+ def __init__(self, model_name_or_path: str, config: PretrainedConfig):
270
+ super().__init__(model_name_or_path, config)
271
+ self.image_processor = CLIPImageProcessor.from_pretrained(model_name_or_path)
272
+ self.vision_tower = CLIPVisionModel.from_pretrained(
273
+ model_name_or_path, torch_dtype=eval(config.model_dtype)
274
+ )
275
+ self.is_loaded = True
276
+
277
+
278
+ class CLIPVisionTowerS2(VisionTowerS2):
279
+ def __init__(self, model_name_or_path: str, config: PretrainedConfig):
280
+ super().__init__(model_name_or_path, config)
281
+ self.image_processor = CLIPImageProcessor.from_pretrained(model_name_or_path)
282
+ self.vision_tower = CLIPVisionModel.from_pretrained(
283
+ model_name_or_path, torch_dtype=eval(config.model_dtype)
284
+ )
285
+
286
+ # Make sure it crops/resizes the image to the largest scale in self.scales to maintain high-res information
287
+ self.image_processor.size["shortest_edge"] = self.scales[-1]
288
+ self.image_processor.crop_size["height"] = self.image_processor.crop_size[
289
+ "width"
290
+ ] = self.scales[-1]
291
+
292
+ self.is_loaded = True
293
+
294
+
295
+ class IdentityMap(nn.Module):
296
+ def __init__(self):
297
+ super().__init__()
298
+
299
+ def forward(self, x, *args, **kwargs):
300
+ return x
301
+
302
+ @property
303
+ def config(self):
304
+ return {"mm_projector_type": "identity"}
305
+
306
+
307
+ class SimpleResBlock(nn.Module):
308
+ def __init__(self, channels):
309
+ super().__init__()
310
+ self.pre_norm = nn.LayerNorm(channels)
311
+
312
+ self.proj = nn.Sequential(
313
+ nn.Linear(channels, channels), nn.GELU(), nn.Linear(channels, channels)
314
+ )
315
+
316
+ def forward(self, x):
317
+ x = self.pre_norm(x)
318
+ return x + self.proj(x)
319
+
320
+
321
+ class DownSampleBlock(nn.Module):
322
+ def forward(self, x):
323
+ vit_embeds = x
324
+ h = w = int(vit_embeds.shape[1] ** 0.5)
325
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
326
+ vit_embeds = self.flat_square(vit_embeds)
327
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
328
+ return vit_embeds
329
+
330
+ def flat_square(self, x):
331
+ n, w, h, c = x.size()
332
+ if w % 2 == 1:
333
+ x = torch.concat(
334
+ [x, torch.zeros((n, 1, h, c), dtype=x.dtype).to(x.device)], dim=1
335
+ ).contiguous()
336
+ n, w, h, c = x.size()
337
+ if h % 2 == 1:
338
+ x = torch.concat(
339
+ [x, torch.zeros((n, w, 1, c), dtype=x.dtype).to(x.device)], dim=2
340
+ ).contiguous()
341
+ n, w, h, c = x.size()
342
+ x = x.view(n, w, int(h / 2), int(c * 2))
343
+ x = x.permute(0, 2, 1, 3).contiguous()
344
+ x = x.view(n, int(h / 2), int(w / 2), int(c * 4))
345
+ return x
346
+
347
+
348
+ class MultimodalProjectorConfig(PretrainedConfig):
349
+ model_type = "v2l_projector"
350
+
351
+ def __init__(self, mm_projector_type: str = None, **kwargs):
352
+ super().__init__()
353
+ self.mm_projector_type = mm_projector_type
354
+
355
+
356
+ class MultimodalProjector(PreTrainedModel):
357
+ config_class = MultimodalProjectorConfig
358
+
359
+ def __init__(
360
+ self, mm_projector_cfg: MultimodalProjectorConfig, config: PretrainedConfig
361
+ ):
362
+ super().__init__(mm_projector_cfg)
363
+ mm_projector_type = mm_projector_cfg.mm_projector_type
364
+ if mm_projector_type == "identity":
365
+ self.layers = IdentityMap()
366
+ elif mm_projector_type == "linear":
367
+ self.layers = nn.Linear(config.mm_hidden_size, config.hidden_size)
368
+ elif mm_projector_type == "mlp_downsample":
369
+ self.layers = nn.Sequential(
370
+ DownSampleBlock(),
371
+ nn.LayerNorm(config.mm_hidden_size * 4),
372
+ nn.Linear(config.mm_hidden_size * 4, config.hidden_size),
373
+ nn.GELU(),
374
+ nn.Linear(config.hidden_size, config.hidden_size),
375
+ )
376
+ else:
377
+ mlp_gelu_match = re.match(r"^mlp(\d+)x_gelu$", mm_projector_type)
378
+ if mlp_gelu_match:
379
+ mlp_depth = int(mlp_gelu_match.group(1))
380
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
381
+ for _ in range(1, mlp_depth):
382
+ modules.append(nn.GELU())
383
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
384
+ self.layers = nn.Sequential(*modules)
385
+ else:
386
+ raise ValueError(f"Unknown projector type: {mm_projector_type}")
387
+
388
+ def forward(self, x, *args, **kwargs):
389
+ return self.layers(x)
390
+
391
+
392
+ def build_mm_projector(
393
+ model_type_or_path: str, config: PretrainedConfig
394
+ ) -> PreTrainedModel:
395
+ if model_type_or_path is None:
396
+ return None
397
+
398
+ ## load from pretrained model
399
+ if config.resume_path:
400
+ assert os.path.exists(
401
+ model_type_or_path
402
+ ), f"Resume mm projector path {model_type_or_path} does not exist!"
403
+ return MultimodalProjector.from_pretrained(
404
+ model_type_or_path, config, torch_dtype=eval(config.model_dtype)
405
+ )
406
+ ## build from scratch
407
+ else:
408
+ mm_projector_cfg = MultimodalProjectorConfig(model_type_or_path)
409
+ mm_projector = MultimodalProjector(mm_projector_cfg, config).to(
410
+ eval(config.model_dtype)
411
+ )
412
+ return mm_projector
413
+
414
+
415
+ def build_vision_tower(
416
+ model_name_or_path: str, config: PretrainedConfig
417
+ ) -> PreTrainedModel:
418
+ ## skip vision tower instantiation
419
+ if model_name_or_path is None:
420
+ return None
421
+
422
+ vision_tower_arch = None
423
+ if config.resume_path and "radio" not in model_name_or_path:
424
+ assert os.path.exists(
425
+ model_name_or_path
426
+ ), f"Resume vision tower path {model_name_or_path} does not exist!"
427
+ vision_tower_cfg = AutoConfig.from_pretrained(
428
+ model_name_or_path, trust_remote_code=True
429
+ )
430
+ vision_tower_arch = vision_tower_cfg.architectures[0].lower()
431
+ vision_tower_name = (
432
+ vision_tower_arch if vision_tower_arch is not None else model_name_or_path
433
+ )
434
+
435
+ use_s2 = getattr(config, "s2", False)
436
+
437
+ if "intern" in vision_tower_name.lower():
438
+ if hasattr(config, "drop_path_rate"):
439
+ vision_tower = InternVisionTower(
440
+ model_name_or_path, config=config, drop_path_rate=config.drop_path_rate
441
+ )
442
+ else:
443
+ vision_tower = InternVisionTower(
444
+ model_name_or_path, config=config, drop_path_rate=0.0
445
+ )
446
+ elif "clip" in vision_tower_name:
447
+ if use_s2:
448
+ vision_tower = CLIPVisionTowerS2(model_name_or_path, config)
449
+ else:
450
+ vision_tower = CLIPVisionTower(model_name_or_path, config)
451
+ elif "siglip" in vision_tower_name:
452
+ if use_s2:
453
+ vision_tower = SiglipVisionTowerS2(model_name_or_path, config)
454
+ else:
455
+ vision_tower = SiglipVisionTower(model_name_or_path, config)
456
+ else:
457
+ raise ValueError(f"Unknown vision tower: {model_name_or_path}")
458
+
459
+ config.mm_hidden_size = (
460
+ vision_tower.config.hidden_size if not use_s2 else vision_tower.hidden_size
461
+ )
462
+ return vision_tower
463
+
464
+
465
+ def has_tokenizer(repo_id_or_path: str) -> bool:
466
+ # Check if the tokenizer is in a local directory
467
+ if osp.exists(osp.join(repo_id_or_path, "tokenizer_config.json")):
468
+ return True
469
+
470
+ # Check if the tokenizer is in a Hugging Face Hub repo
471
+ try:
472
+ return repo_exists(repo_id_or_path) and file_exists(
473
+ repo_id_or_path, "tokenizer_config.json"
474
+ )
475
+ except HFValidationError:
476
+ return False
477
+
478
+
479
+ def context_length_extension(config):
480
+ orig_ctx_len = getattr(config, "max_position_embeddings", None)
481
+ model_max_length = getattr(config, "model_max_length", None)
482
+ if orig_ctx_len and model_max_length > orig_ctx_len:
483
+ print(f"Scaling RoPE from {orig_ctx_len} to {model_max_length}")
484
+ scaling_factor = float(math.ceil(model_max_length / orig_ctx_len))
485
+ config.rope_scaling = {"type": "linear", "factor": scaling_factor}
486
+ return config
487
+
488
+
489
+ def build_llm_and_tokenizer(
490
+ model_name_or_path: str,
491
+ config: PretrainedConfig,
492
+ attn_implementation=None,
493
+ model_max_length=None,
494
+ *args,
495
+ **kwargs,
496
+ ) -> Tuple[PreTrainedModel, PreTrainedTokenizer]:
497
+ llm_cfg = AutoConfig.from_pretrained(model_name_or_path)
498
+ llm_cfg._attn_implementation = attn_implementation
499
+ llm_cfg.model_max_length = model_max_length
500
+ if model_max_length is not None:
501
+ context_length_extension(llm_cfg)
502
+
503
+ llm = AutoModelForCausalLM.from_pretrained(
504
+ model_name_or_path,
505
+ config=llm_cfg,
506
+ torch_dtype=eval(config.model_dtype),
507
+ *args,
508
+ **kwargs,
509
+ )
510
+
511
+ # Locate the tokenizer.
512
+ llm_path = model_name_or_path
513
+ if not has_tokenizer(llm_path):
514
+ llm_path = osp.join(llm_path, "llm")
515
+ if not has_tokenizer(llm_path):
516
+ raise ValueError(f"Cannot find tokenizer in {llm_path}.")
517
+
518
+ # TODO(ligeng): use LLM class to judge to better compability.
519
+ try:
520
+ llm_arch = getattr(llm_cfg, "architectures")[0].lower()
521
+ except BaseException:
522
+ warnings.warn(
523
+ f'Cannot find LLM architecture, please check the "config.json" under "{llm_path}".'
524
+ )
525
+
526
+ if "mpt" in llm_arch:
527
+ tokenizer = AutoTokenizer.from_pretrained(
528
+ llm_path,
529
+ model_max_length=llm_cfg.model_max_length,
530
+ padding_side="right",
531
+ )
532
+ elif "yi" in llm_path or (
533
+ getattr(llm_cfg, "num_hidden_layers", -1) == 60
534
+ and getattr(llm_cfg, "num_attention_heads", -1) == 56
535
+ ):
536
+ tokenizer = AutoTokenizer.from_pretrained(
537
+ llm_path,
538
+ model_max_length=llm_cfg.model_max_length,
539
+ padding_side="right",
540
+ use_fast=False,
541
+ )
542
+ else:
543
+ tokenizer = AutoTokenizer.from_pretrained(
544
+ llm_path,
545
+ model_max_length=llm_cfg.model_max_length,
546
+ padding_side="right",
547
+ use_fast=False,
548
+ legacy=False,
549
+ )
550
+
551
+ # TODO(ligeng): is this necessary for llava?
552
+ config.hidden_size = llm.config.hidden_size
553
+ return llm, tokenizer
554
+
555
+
556
+ def get_model_config(config):
557
+ default_keys = ["llm_cfg", "vision_tower_cfg", "mm_projector_cfg"]
558
+
559
+ if hasattr(config, "_name_or_path") and len(config._name_or_path) >= 2:
560
+ root_path = config._name_or_path
561
+ else:
562
+ root_path = config.resume_path
563
+
564
+ # download from huggingface
565
+ if root_path is not None and not osp.exists(root_path):
566
+ try:
567
+ valid_hf_repo = repo_exists(root_path)
568
+ except HFValidationError as e:
569
+ valid_hf_repo = False
570
+ if valid_hf_repo:
571
+ root_path = snapshot_download(root_path)
572
+
573
+ return_list = []
574
+ for key in default_keys:
575
+ cfg = getattr(config, key, None)
576
+ if isinstance(cfg, dict):
577
+ try:
578
+ return_list.append(os.path.join(root_path, key[:-4]))
579
+ except:
580
+ raise ValueError(f"Cannot find resume path in config for {key}!")
581
+ elif isinstance(cfg, PretrainedConfig):
582
+ return_list.append(os.path.join(root_path, key[:-4]))
583
+ elif isinstance(cfg, str):
584
+ return_list.append(cfg)
585
+
586
+ return return_list
587
+
588
+
589
+ def is_mm_model(model_path):
590
+ """
591
+ Check if the model at the given path is a visual language model.
592
+
593
+ Args:
594
+ model_path (str): The path to the model.
595
+
596
+ Returns:
597
+ bool: True if the model is an MM model, False otherwise.
598
+ """
599
+ config = AutoConfig.from_pretrained(model_path)
600
+ architectures = config.architectures
601
+ for architecture in architectures:
602
+ if "llava" in architecture.lower():
603
+ return True
604
+ return False
605
+
606
+
607
+ def auto_upgrade(config):
608
+ cfg = AutoConfig.from_pretrained(config)
609
+ if "llava" in config and "llava" not in cfg.model_type:
610
+ assert cfg.model_type == "llama"
611
+ print(
612
+ "You are using newer LLaVA code base, while the checkpoint of v0 is from older code base."
613
+ )
614
+ print(
615
+ "You must upgrade the checkpoint to the new code base (this can be done automatically)."
616
+ )
617
+ confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]")
618
+ if confirm.lower() in ["y", "yes"]:
619
+ print("Upgrading checkpoint...")
620
+ assert len(cfg.architectures) == 1
621
+ setattr(cfg.__class__, "model_type", "llava")
622
+ cfg.architectures[0] = "LlavaLlamaForCausalLM"
623
+ cfg.save_pretrained(config)
624
+ print("Checkpoint upgraded.")
625
+ else:
626
+ print("Checkpoint upgrade aborted.")
627
+ exit(1)
628
+
629
+
630
+ def get_pg_manager():
631
+ return None
632
+
633
+
634
+ # TODO decide whether should we use metaclass
635
+ class LlavaMetaModel(ABC):
636
+ def init_vlm(self, config: PreTrainedModel = None, *args, **kwargs):
637
+ # TODO(ligeng): figure out how from_config and from_pretrained works in HF implementation.
638
+ if (
639
+ hasattr(self, "llm")
640
+ or hasattr(self, "vision_tower")
641
+ or hasattr(self, "mm_projector")
642
+ ):
643
+ # already initialized, skipped
644
+ return
645
+
646
+ model_dtype = getattr(config, "model_dtype", "torch.float16")
647
+ if not hasattr(config, "model_dtype"):
648
+ warnings.warn(
649
+ "model_dtype not found in config, defaulting to torch.float16."
650
+ )
651
+ config.model_dtype = model_dtype
652
+
653
+ cfgs = get_model_config(config)
654
+ if len(cfgs) == 3:
655
+ llm_cfg, vision_tower_cfg, mm_projector_cfg = cfgs
656
+ else:
657
+ raise ValueError(
658
+ "`llm_cfg` `mm_projector_cfg` `vision_tower_cfg` not found in the config."
659
+ )
660
+
661
+ # print("Before init in Config")
662
+ # if hasattr(config, "deepspeed") and "mics" in config.deepspeed:
663
+ # print("Using MiCS_Init")
664
+ # import deepspeed
665
+ # with deepspeed.zero.MiCS_Init():
666
+ # self.llm, self.tokenizer = build_llm_and_tokenizer(llm_cfg, config, *args, **kwargs)
667
+ # self.vision_tower = build_vision_tower(vision_tower_cfg, config)
668
+ # self.mm_projector = build_mm_projector(mm_projector_cfg, config)
669
+ # else:
670
+ self.llm, self.tokenizer = build_llm_and_tokenizer(
671
+ llm_cfg, config, *args, **kwargs
672
+ )
673
+ self.vision_tower = build_vision_tower(vision_tower_cfg, config)
674
+ self.mm_projector = build_mm_projector(mm_projector_cfg, config)
675
+
676
+ self.post_config()
677
+ self.is_loaded = True
678
+
679
+ assert (
680
+ self.llm is not None
681
+ or self.vision_tower is not None
682
+ or self.mm_projector is not None
683
+ ), "At least one of the components must be instantiated."
684
+
685
+ @classmethod
686
+ def load_from_config(cls, model_path_or_config, *args, **kwargs):
687
+ pass
688
+
689
+ ## FIXME we will use this function to load model in the future
690
+ @classmethod
691
+ def load_pretrained(cls, model_path_or_config, *args, **kwargs):
692
+ kwargs.pop("config", None)
693
+
694
+ if isinstance(model_path_or_config, str):
695
+ config = AutoConfig.from_pretrained(model_path_or_config)
696
+ elif isinstance(model_path_or_config, LlavaConfig):
697
+ config = model_path_or_config
698
+ else:
699
+ raise NotImplementedError(
700
+ f"wrong type, {type(model_path_or_config)} \
701
+ {isinstance(model_path_or_config, LlavaConfig)}"
702
+ )
703
+
704
+ model_dtype = getattr(config, "model_dtype", "torch.float16")
705
+ if not hasattr(config, "model_dtype"):
706
+ warnings.warn(
707
+ "model_dtype not found in config, defaulting to torch.float16."
708
+ )
709
+ config.model_dtype = model_dtype
710
+
711
+ cfgs = get_model_config(config)
712
+ if len(cfgs) == 3:
713
+ llm_cfg, vision_tower_cfg, mm_projector_cfg = cfgs
714
+ else:
715
+ raise ValueError(
716
+ "`llm_cfg` `mm_projector_cfg` `vision_tower_cfg` not found in the config."
717
+ )
718
+
719
+ # print(llm_cfg, vision_tower_cfg, mm_projector_cfg); input("DEBUG load_pretrained")
720
+ init_context = [
721
+ no_init_weights(_enable=True),
722
+ ]
723
+ # print("Before Init Context")
724
+ # if hasattr(config, "deepspeed") and "mics" in config.deepspeed:
725
+ # print("Using MiCS_Init")
726
+ # import deepspeed
727
+ # init_context.append(deepspeed.zero.MiCS_Init(config_dict_or_path=config.deepspeed))
728
+ with ContextManagers(init_context):
729
+ vlm = cls(config, *args, **kwargs)
730
+ # print(llm_cfg, vision_tower_cfg, mm_projector_cfg); input("DEBUG load_pretrained finish")
731
+
732
+ if (
733
+ hasattr(vlm, "llm")
734
+ or hasattr(vlm, "vision_tower")
735
+ or hasattr(vlm, "mm_projector")
736
+ ):
737
+ if vlm.is_loaded:
738
+ return vlm
739
+
740
+ vlm.llm, vlm.tokenizer = build_llm_and_tokenizer(
741
+ llm_cfg, config, *args, **kwargs
742
+ )
743
+ vlm.vision_tower = build_vision_tower(vision_tower_cfg, config)
744
+ vlm.mm_projector = build_mm_projector(mm_projector_cfg, config)
745
+
746
+ self.post_config()
747
+ self.is_loaded = True
748
+
749
+ # FIXME(ligeng, yunhao): llm should never be none here.
750
+ assert (
751
+ vlm.llm is not None
752
+ or vlm.vision_tower is not None
753
+ or vlm.mm_projector is not None
754
+ ), "At least one of the components must be instantiated."
755
+ return vlm
756
+
757
+ ## FIXME we will use this function to save the model in the future
758
+ def save_pretrained(self, output_dir, state_dict=None):
759
+ if state_dict is None:
760
+ # other wise fetch from deepspeed
761
+ # state_dict = accelerator.get_state_dict(is_deepspeed_enabled)
762
+ state_dict = self.state_dict()
763
+
764
+ if getattr(self, "tokenizer", None):
765
+ self.tokenizer.save_pretrained(osp.join(output_dir, "llm"))
766
+
767
+ if self.get_llm():
768
+ print(f"saving llm to {osp.join(output_dir, 'llm')}")
769
+ self.llm.config._name_or_path = osp.join(output_dir, "llm")
770
+ llm_state_dict = OrderedDict(
771
+ {k.split("llm.")[-1]: v for k, v in state_dict.items() if "llm" in k}
772
+ )
773
+ self.llm.save_pretrained(
774
+ os.path.join(output_dir, "llm"), state_dict=llm_state_dict
775
+ )
776
+ self.config.llm_cfg = self.llm.config
777
+
778
+ if self.get_vision_tower():
779
+ print(f"saving vision_tower to {osp.join(output_dir, 'vision_tower')}")
780
+ self.vision_tower.config._name_or_path = osp.join(
781
+ output_dir, "vision_tower"
782
+ )
783
+ vision_tower_state_dict = OrderedDict(
784
+ {
785
+ k.split("vision_tower.vision_tower.")[-1]: v
786
+ for k, v in state_dict.items()
787
+ if "vision_tower" in k
788
+ }
789
+ )
790
+ self.vision_tower.vision_tower.save_pretrained(
791
+ os.path.join(output_dir, "vision_tower"),
792
+ state_dict=vision_tower_state_dict,
793
+ )
794
+ self.vision_tower.image_processor.save_pretrained(
795
+ os.path.join(output_dir, "vision_tower")
796
+ )
797
+ self.config.vision_tower_cfg = self.vision_tower.config
798
+ if hasattr(self.config.vision_tower_cfg, "auto_map"):
799
+ if "radio" not in self.get_vision_tower().__class__.__name__.lower():
800
+ delattr(self.config.vision_tower_cfg, "auto_map")
801
+
802
+ if self.get_mm_projector():
803
+ print(f"saving mm_projector to {osp.join(output_dir, 'mm_projector')}")
804
+ self.mm_projector.config._name_or_path = osp.join(
805
+ output_dir, "mm_projector"
806
+ )
807
+ mm_projector_state_dict = OrderedDict(
808
+ {
809
+ k.split("mm_projector.")[-1]: v
810
+ for k, v in state_dict.items()
811
+ if "mm_projector" in k
812
+ }
813
+ )
814
+ self.mm_projector.save_pretrained(
815
+ os.path.join(output_dir, "mm_projector"),
816
+ state_dict=mm_projector_state_dict,
817
+ )
818
+ self.config.mm_projector_cfg = self.mm_projector.config
819
+ ## update and save top-level config
820
+ self.config._name_or_path = output_dir
821
+ self.config.architectures = [self.__class__.__name__]
822
+ self.config.save_pretrained(output_dir)
823
+
824
+ def get_llm(self):
825
+ llm = getattr(self, "llm", None)
826
+ if type(llm) is list:
827
+ llm = llm[0]
828
+ return llm
829
+
830
+ def get_lm_head(self):
831
+ lm_head = getattr(self.get_llm(), "lm_head", None)
832
+ return lm_head
833
+
834
+ def get_vision_tower(self):
835
+ vision_tower = getattr(self, "vision_tower", None)
836
+ if type(vision_tower) is list:
837
+ vision_tower = vision_tower[0]
838
+ return vision_tower
839
+
840
+ def get_mm_projector(self):
841
+ mm_projector = getattr(self, "mm_projector", None)
842
+ if type(mm_projector) is list:
843
+ mm_projector = mm_projector[0]
844
+ return mm_projector
845
+
846
+ def post_config(self):
847
+ self.training = self.get_llm().training
848
+ ## configuration
849
+ if getattr(self.config, "llm_cfg", None) is None:
850
+ self.config.llm_cfg = self.llm.config
851
+ if getattr(self.config, "vision_tower_cfg", None) is None:
852
+ self.config.vision_tower_cfg = self.vision_tower.config
853
+ if getattr(self.config, "mm_projector_cfg", None) is None:
854
+ self.config.mm_projector_cfg = self.mm_projector.config
855
+
856
+ def freezed_module_patch(self):
857
+ """
858
+ Huggingface will call model.train() at each training_step. To ensure the expected behaviors for modules like dropout, batchnorm, etc., we need to call model.eval() for the freezed modules.
859
+ """
860
+ if self.training:
861
+ if self.get_llm() and not getattr(
862
+ self.config, "tune_language_model", False
863
+ ):
864
+ pass
865
+ # logging.warning("Caution: Your LLM is currently in training mode, ensuring accurate gradient computation. Please be vigilant, particularly regarding BatchNorm and Dropout operations.")
866
+ if self.get_vision_tower() and not getattr(
867
+ self.config, "tune_vision_tower", False
868
+ ):
869
+ self.get_vision_tower().eval()
870
+ if self.get_mm_projector() and not getattr(
871
+ self.config, "tune_mm_projector", False
872
+ ):
873
+ self.get_mm_projector().eval()
874
+
875
+ def encode_images(self, images):
876
+ image_features = self.get_vision_tower()(images)
877
+ image_features = self.get_mm_projector()(image_features)
878
+ return image_features
879
+
880
+ ## @yunhao: is there a better way to handle function call and attributes for llm?
881
+ ## support beam search
882
+ def _temporary_reorder_cache(self, past_key_values, sorted_idx):
883
+ return self.get_llm()._temporary_reorder_cache(past_key_values, sorted_idx)
884
+
885
+ def get_input_embeddings(self):
886
+ return self.get_llm().get_input_embeddings()
887
+
888
+ def get_output_embeddings(self):
889
+ return self.get_llm().get_output_embeddings()
890
+
891
+ def resize_token_embeddings(self, embed_size):
892
+ self.get_llm().resize_token_embeddings(embed_size)
893
+
894
+
895
+ class LlavaMetaForCausalLM(ABC):
896
+ """This class is originally implemented by the LLaVA team and
897
+ modified by Haotian Tang and Jason Lu based on Ji Lin's implementation
898
+ to support multiple images and input packing."""
899
+
900
+ ## TODO move the forward function here if there is no need to override it
901
+ def prepare_inputs_labels_for_multimodal(
902
+ self, input_ids, position_ids, attention_mask, past_key_values, labels, images
903
+ ):
904
+ # Handle sequence parallelism
905
+ PROCESS_GROUP_MANAGER = get_pg_manager()
906
+ if PROCESS_GROUP_MANAGER is None:
907
+ sp_degree = -1
908
+ sp_rank = -1
909
+ else:
910
+ sp_degree = PROCESS_GROUP_MANAGER.sp_degree
911
+ sp_rank = PROCESS_GROUP_MANAGER.sp_rank
912
+
913
+ vision_tower = self.get_vision_tower()
914
+ if (
915
+ vision_tower is None
916
+ or images is None
917
+ or (input_ids.shape[1] == 1 and PROCESS_GROUP_MANAGER is None)
918
+ ):
919
+ if (
920
+ past_key_values is not None
921
+ and vision_tower is not None
922
+ and images is not None
923
+ and input_ids.shape[1] == 1
924
+ ):
925
+ target_shape = past_key_values[-1][-1].shape[-2] + 1
926
+ attention_mask = torch.cat(
927
+ (
928
+ attention_mask,
929
+ torch.ones(
930
+ (
931
+ attention_mask.shape[0],
932
+ target_shape - attention_mask.shape[1],
933
+ ),
934
+ dtype=attention_mask.dtype,
935
+ device=attention_mask.device,
936
+ ),
937
+ ),
938
+ dim=1,
939
+ )
940
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
941
+ return (
942
+ input_ids,
943
+ position_ids,
944
+ attention_mask,
945
+ past_key_values,
946
+ None,
947
+ labels,
948
+ )
949
+ # handle different image dtypes for packing
950
+ if type(images) is list:
951
+ images = torch.cat(images, dim=0)
952
+ elif images.ndim == 5: # batch_size x seq_len x image_channels
953
+ images = images.flatten(0, 1)
954
+ image_features = self.encode_images(images).to(self.device)
955
+ # Note (kentang-mit@): image start / end is not implemented here to support pretraining.
956
+ if getattr(self.config, "turn_mm_projector", False) and getattr(
957
+ self.config, "mm_use_im_start_end", False
958
+ ):
959
+ raise NotImplementedError
960
+
961
+ # Let's just add dummy tensors if they do not exist,
962
+ # it is a headache to deal with None all the time.
963
+ # But it is not ideal, and if you have a better idea,
964
+ # please open an issue / submit a PR, thanks.
965
+ _labels = labels
966
+ _position_ids = position_ids
967
+ _attention_mask = attention_mask
968
+ if attention_mask is None:
969
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
970
+ else:
971
+ attention_mask = attention_mask.bool()
972
+ if position_ids is None:
973
+ position_ids = torch.arange(
974
+ 0, input_ids.shape[1], dtype=torch.long, device=input_ids.device
975
+ )
976
+ if labels is None:
977
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
978
+
979
+ # remove the padding using attention_mask
980
+ input_ids_copy = input_ids.clone()
981
+ # kentang-mit@: Otherwise tokenizer out of bounds. Embeddings of image tokens will not be used.
982
+ input_ids_copy[input_ids_copy == IMAGE_TOKEN_INDEX] = 0
983
+ input_embeds = self.llm.model.embed_tokens(input_ids_copy)
984
+
985
+ input_ids = [
986
+ cur_input_ids[cur_attention_mask]
987
+ for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)
988
+ ]
989
+ input_embeds_1 = [
990
+ cur_input_embeds[cur_attention_mask]
991
+ for cur_input_embeds, cur_attention_mask in zip(
992
+ input_embeds, attention_mask
993
+ )
994
+ ]
995
+ labels = [
996
+ cur_labels[cur_attention_mask]
997
+ for cur_labels, cur_attention_mask in zip(labels, attention_mask)
998
+ ]
999
+
1000
+ new_input_embeds = []
1001
+ new_labels = []
1002
+ cur_image_idx = 0
1003
+
1004
+ # kentang-mit@: If some part of the model is executed in the loop, the the loop length needs to be a constant.
1005
+ for batch_idx, cur_input_ids in enumerate(input_ids):
1006
+ cur_input_ids = input_ids[batch_idx]
1007
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
1008
+ if num_images == 0:
1009
+ cur_image_features = image_features[0]
1010
+ cur_input_embeds_1 = input_embeds_1[batch_idx]
1011
+ cur_input_embeds = torch.cat(
1012
+ [cur_input_embeds_1, cur_image_features[0:0]], dim=0
1013
+ )
1014
+ new_input_embeds.append(cur_input_embeds)
1015
+ new_labels.append(labels[batch_idx])
1016
+ # kenang-mit@: we do not have placeholdr image for text-only data now.
1017
+ continue
1018
+
1019
+ cur_input_embeds = input_embeds_1[batch_idx]
1020
+ image_token_indices = (
1021
+ [-1]
1022
+ + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist()
1023
+ + [cur_input_ids.shape[0]]
1024
+ )
1025
+ cur_input_ids_noim = []
1026
+ cur_labels = labels[batch_idx]
1027
+ cur_labels_noim = []
1028
+ cur_input_embeds_no_im = []
1029
+ for i in range(len(image_token_indices) - 1):
1030
+ if (
1031
+ sp_degree > 1 and i == 0 and sp_rank != 0
1032
+ ): # Handle sequence parallelism
1033
+ cur_input_ids_noim.append(cur_input_ids[0:0])
1034
+ cur_labels_noim.append(cur_labels[0:0])
1035
+ cur_input_embeds_no_im.append(cur_input_embeds[0:0])
1036
+ continue
1037
+ cur_input_ids_noim.append(
1038
+ cur_input_ids[
1039
+ image_token_indices[i] + 1 : image_token_indices[i + 1]
1040
+ ]
1041
+ )
1042
+ cur_labels_noim.append(
1043
+ cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]]
1044
+ )
1045
+ cur_input_embeds_no_im.append(
1046
+ cur_input_embeds[
1047
+ image_token_indices[i] + 1 : image_token_indices[i + 1]
1048
+ ]
1049
+ )
1050
+
1051
+ cur_new_input_embeds = []
1052
+ cur_new_labels = []
1053
+ for i in range(num_images + 1):
1054
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
1055
+ cur_new_labels.append(cur_labels_noim[i])
1056
+ if i < num_images:
1057
+ cur_image_features = image_features[cur_image_idx]
1058
+ cur_image_idx += 1
1059
+ cur_new_input_embeds.append(cur_image_features)
1060
+ cur_new_labels.append(
1061
+ torch.full(
1062
+ (cur_image_features.shape[0],),
1063
+ IGNORE_INDEX,
1064
+ device=cur_labels.device,
1065
+ dtype=cur_labels.dtype,
1066
+ )
1067
+ )
1068
+
1069
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
1070
+ cur_new_labels = torch.cat(cur_new_labels)
1071
+
1072
+ new_input_embeds.append(cur_new_input_embeds)
1073
+ new_labels.append(cur_new_labels)
1074
+
1075
+ # Truncate sequences to max length as image embeddings can make the sequence longer
1076
+ tokenizer_model_max_length = getattr(
1077
+ self.llm.config, "tokenizer_model_max_length", None
1078
+ )
1079
+ if tokenizer_model_max_length is not None:
1080
+ if any(len(x) > tokenizer_model_max_length for x in new_input_embeds):
1081
+ warnings.warn("Inputs truncated!")
1082
+ new_input_embeds = [
1083
+ x[:tokenizer_model_max_length] for x in new_input_embeds
1084
+ ]
1085
+ new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
1086
+ # Combine them
1087
+ max_len = max(x.shape[0] for x in new_input_embeds)
1088
+ # max_len = tokenizer_model_max_length
1089
+ # print("Warning: using max_len as tokenizer_model_max_length")
1090
+ batch_size = len(new_input_embeds)
1091
+
1092
+ new_input_embeds_padded = []
1093
+ new_labels_padded = torch.full(
1094
+ (batch_size, max_len),
1095
+ IGNORE_INDEX,
1096
+ dtype=new_labels[0].dtype,
1097
+ device=new_labels[0].device,
1098
+ )
1099
+ attention_mask = torch.zeros(
1100
+ (batch_size, max_len),
1101
+ dtype=attention_mask.dtype,
1102
+ device=attention_mask.device,
1103
+ )
1104
+ position_ids = torch.zeros(
1105
+ (batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device
1106
+ )
1107
+
1108
+ for i, (cur_new_embed, cur_new_labels) in enumerate(
1109
+ zip(new_input_embeds, new_labels)
1110
+ ):
1111
+ cur_len = cur_new_embed.shape[0]
1112
+ if getattr(self.llm.config, "tokenizer_padding_side", "right") == "left":
1113
+ new_input_embeds_padded.append(
1114
+ torch.cat(
1115
+ (
1116
+ torch.zeros(
1117
+ (max_len - cur_len, cur_new_embed.shape[1]),
1118
+ dtype=cur_new_embed.dtype,
1119
+ device=cur_new_embed.device,
1120
+ ),
1121
+ cur_new_embed,
1122
+ ),
1123
+ dim=0,
1124
+ )
1125
+ )
1126
+ if cur_len > 0:
1127
+ new_labels_padded[i, -cur_len:] = cur_new_labels
1128
+ attention_mask[i, -cur_len:] = True
1129
+ position_ids[i, -cur_len:] = torch.arange(
1130
+ 0, cur_len, dtype=position_ids.dtype, device=position_ids.device
1131
+ )
1132
+ else:
1133
+ new_input_embeds_padded.append(
1134
+ torch.cat(
1135
+ (
1136
+ cur_new_embed,
1137
+ torch.zeros(
1138
+ (max_len - cur_len, cur_new_embed.shape[1]),
1139
+ dtype=cur_new_embed.dtype,
1140
+ device=cur_new_embed.device,
1141
+ ),
1142
+ ),
1143
+ dim=0,
1144
+ )
1145
+ )
1146
+ if cur_len > 0:
1147
+ new_labels_padded[i, :cur_len] = cur_new_labels
1148
+ attention_mask[i, :cur_len] = True
1149
+ position_ids[i, :cur_len] = torch.arange(
1150
+ 0, cur_len, dtype=position_ids.dtype, device=position_ids.device
1151
+ )
1152
+
1153
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
1154
+
1155
+ # if sp_degree > 1: # Handle sequence parallelism
1156
+ # if sp_rank not in self.global_seq_len:
1157
+ # self.global_seq_len[sp_rank] = position_ids.shape[-1]
1158
+ # else:
1159
+ # assert self.global_seq_len[sp_rank] == position_ids.shape[-1]
1160
+
1161
+ if _labels is None:
1162
+ new_labels = None
1163
+ else:
1164
+ new_labels = new_labels_padded
1165
+
1166
+ if _attention_mask is None:
1167
+ attention_mask = None
1168
+ else:
1169
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
1170
+
1171
+ if _position_ids is None:
1172
+ position_ids = None
1173
+
1174
+ # We will not use packing here when sequence parallelism is enabled.
1175
+ if PROCESS_GROUP_MANAGER is not None:
1176
+ return (
1177
+ None,
1178
+ _position_ids,
1179
+ attention_mask,
1180
+ past_key_values,
1181
+ new_input_embeds,
1182
+ new_labels,
1183
+ )
1184
+
1185
+ return (
1186
+ None,
1187
+ position_ids,
1188
+ attention_mask,
1189
+ past_key_values,
1190
+ new_input_embeds,
1191
+ new_labels,
1192
+ )
1193
+
1194
+ def repack_multimodal_data(
1195
+ self,
1196
+ input_ids,
1197
+ position_ids,
1198
+ attention_mask,
1199
+ past_key_values,
1200
+ inputs_embeds,
1201
+ labels,
1202
+ ):
1203
+ # Handle sequence parallelism
1204
+ PROCESS_GROUP_MANAGER = get_pg_manager()
1205
+ # if PROCESS_GROUP_MANAGER is None:
1206
+ # sp_degree = -1
1207
+ # sp_rank = -1
1208
+ # else:
1209
+ # sp_degree = PROCESS_GROUP_MANAGER.sp_degree
1210
+ # sp_rank = PROCESS_GROUP_MANAGER.sp_rank
1211
+
1212
+ # We will not use packing here when sequence parallelism is enabled.
1213
+ # However, we do resharding here to ensure the sequence length is the same across all ranks.
1214
+ if PROCESS_GROUP_MANAGER is not None:
1215
+ sp_degree = PROCESS_GROUP_MANAGER.sp_degree
1216
+ sp_rank = PROCESS_GROUP_MANAGER.sp_rank
1217
+ sp_group = PROCESS_GROUP_MANAGER.ulysses_pg
1218
+ bs, shard_seqlen = position_ids.shape
1219
+ ulysess_seq_len = [
1220
+ torch.zeros(1, dtype=torch.int64, device=position_ids.device)
1221
+ for _ in range(sp_degree)
1222
+ ]
1223
+ dist.all_gather(
1224
+ ulysess_seq_len,
1225
+ torch.tensor(shard_seqlen, device=position_ids.device),
1226
+ group=sp_group,
1227
+ )
1228
+ # global_seq_len = torch.sum(torch.cat(ulysess_seq_len, dim=0)).item()
1229
+
1230
+ # Gather attention_mask and reshard it evenly
1231
+ attention_mask_list = [
1232
+ torch.zeros(
1233
+ (bs, ulysess_seq_len[i]),
1234
+ dtype=attention_mask.dtype,
1235
+ device=attention_mask.device,
1236
+ )
1237
+ for i in range(sp_degree)
1238
+ ]
1239
+ dist.all_gather(attention_mask_list, attention_mask, group=sp_group)
1240
+ effective_seqlen_list = [
1241
+ attention_mask_list[i].sum(dim=-1) for i in range(sp_degree)
1242
+ ]
1243
+ effective_seqlen = torch.stack(effective_seqlen_list, dim=-1)
1244
+ effective_seqlen_batch_list = torch.unbind(effective_seqlen, dim=0)
1245
+
1246
+ global_attention_mask_list = []
1247
+ for i in range(bs):
1248
+ global_attention_mask_batch_list = []
1249
+ for j in range(sp_degree):
1250
+ global_attention_mask_batch_list.append(
1251
+ attention_mask_list[j][i, : effective_seqlen_batch_list[i][j]]
1252
+ )
1253
+ global_attention_mask_list.append(
1254
+ torch.cat(global_attention_mask_batch_list, dim=0)
1255
+ )
1256
+ global_attention_mask = torch.nn.utils.rnn.pad_sequence(
1257
+ global_attention_mask_list, batch_first=True, padding_value=False
1258
+ )
1259
+
1260
+ # Hyperparameters for sequence parallelism resharding
1261
+ global_seq_len = global_attention_mask.shape[-1]
1262
+ seq_len_sharded = global_seq_len // sp_degree
1263
+ start_idx_reshard = seq_len_sharded * sp_rank
1264
+ end_idx_reshard = (
1265
+ start_idx_reshard + seq_len_sharded
1266
+ if sp_rank < sp_degree - 1
1267
+ else global_seq_len
1268
+ )
1269
+ # if sp_rank == 0:
1270
+ # start_idx = 0
1271
+ # else:
1272
+ # start_idx = torch.sum(torch.cat(ulysess_seq_len[:sp_rank], dim=0)).item()
1273
+
1274
+ new_attention_mask = torch.narrow(
1275
+ global_attention_mask,
1276
+ 1,
1277
+ start_idx_reshard,
1278
+ end_idx_reshard - start_idx_reshard,
1279
+ )
1280
+
1281
+ # Gather position_ids and reshard it evenly
1282
+ position_ids_list = [
1283
+ torch.zeros(
1284
+ (bs, ulysess_seq_len[i]),
1285
+ dtype=position_ids.dtype,
1286
+ device=position_ids.device,
1287
+ )
1288
+ for i in range(sp_degree)
1289
+ ]
1290
+ dist.all_gather(position_ids_list, position_ids, group=sp_group)
1291
+ global_position_ids_list = []
1292
+ for i in range(bs):
1293
+ global_position_ids_batch_list = []
1294
+ for j in range(sp_degree):
1295
+ global_position_ids_batch_list.append(
1296
+ position_ids_list[j][i, : effective_seqlen_batch_list[i][j]]
1297
+ )
1298
+ global_position_ids_list.append(
1299
+ torch.cat(global_position_ids_batch_list, dim=0)
1300
+ )
1301
+ global_position_ids = torch.nn.utils.rnn.pad_sequence(
1302
+ global_position_ids_list, batch_first=True, padding_value=-1
1303
+ )
1304
+ new_position_ids = torch.narrow(
1305
+ global_position_ids,
1306
+ 1,
1307
+ start_idx_reshard,
1308
+ end_idx_reshard - start_idx_reshard,
1309
+ )
1310
+
1311
+ # Gather labels and reshard it evenly
1312
+ labels_list = [
1313
+ torch.zeros(
1314
+ (bs, ulysess_seq_len[i]), dtype=labels.dtype, device=labels.device
1315
+ )
1316
+ for i in range(sp_degree)
1317
+ ]
1318
+ dist.all_gather(labels_list, labels, group=sp_group)
1319
+ global_labels_list = []
1320
+ for i in range(bs):
1321
+ global_labels_batch_list = []
1322
+ for j in range(sp_degree):
1323
+ global_labels_batch_list.append(
1324
+ labels_list[j][i, : effective_seqlen_batch_list[i][j]]
1325
+ )
1326
+ global_labels_list.append(torch.cat(global_labels_batch_list, dim=0))
1327
+ global_labels = torch.nn.utils.rnn.pad_sequence(
1328
+ global_labels_list, batch_first=True, padding_value=IGNORE_INDEX
1329
+ )
1330
+ new_labels = torch.narrow(
1331
+ global_labels, 1, start_idx_reshard, end_idx_reshard - start_idx_reshard
1332
+ )
1333
+
1334
+ # Gather inputs_embeds and reshard it evenly
1335
+ # TODO: Fix the non-enough images.
1336
+ # inputs_embeds_list = [torch.zeros((bs, ulysess_seq_len[i], inputs_embeds.shape[-1]), dtype=inputs_embeds.dtype, device=inputs_embeds.device, requires_grad=True) for i in range(sp_degree)]
1337
+ # dist.all_gather(inputs_embeds_list, inputs_embeds, group=sp_group)
1338
+ # global_inputs_embeds_list = []
1339
+ # for i in range(bs):
1340
+ # global_inputs_embeds_batch_list = []
1341
+ # for j in range(sp_degree):
1342
+ # global_inputs_embeds_batch_list.append(inputs_embeds_list[j][i, :effective_seqlen_batch_list[i][j]])
1343
+ # global_inputs_embeds_list.append(torch.cat(global_inputs_embeds_batch_list, dim=0))
1344
+ # global_inputs_embeds = torch.nn.utils.rnn.pad_sequence(global_inputs_embeds_list, batch_first=True, padding_value=0)
1345
+ # new_inputs_embeds = torch.narrow(global_inputs_embeds, 1, start_idx_reshard, end_idx_reshard - start_idx_reshard)
1346
+
1347
+ # Gather all hidden states and flaten them
1348
+ ulysess_seq_len_cat = torch.cat(ulysess_seq_len, dim=0)
1349
+ global_inputs_embeds_list = []
1350
+ if sp_rank == 0:
1351
+ original_start_id = 0
1352
+ original_end_id = torch.sum(ulysess_seq_len_cat[: sp_rank + 1]).item()
1353
+ elif sp_rank == sp_degree - 1:
1354
+ original_start_id = torch.sum(ulysess_seq_len_cat[:sp_rank]).item()
1355
+ original_end_id = torch.sum(ulysess_seq_len_cat[: sp_rank + 1]).item()
1356
+ else:
1357
+ original_start_id = torch.sum(ulysess_seq_len_cat[:sp_rank]).item()
1358
+ original_end_id = torch.sum(ulysess_seq_len_cat[: sp_rank + 1]).item()
1359
+ all_inputs_embeds = torch.zeros(
1360
+ bs,
1361
+ torch.sum(ulysess_seq_len_cat),
1362
+ inputs_embeds.shape[-1],
1363
+ dtype=inputs_embeds.dtype,
1364
+ device=inputs_embeds.device,
1365
+ ).contiguous()
1366
+ all_inputs_embeds[:, original_start_id:original_end_id, :] += inputs_embeds
1367
+ dist.barrier(group=sp_group)
1368
+ dist.all_reduce(all_inputs_embeds, group=sp_group)
1369
+ dist.barrier(group=sp_group)
1370
+ for i in range(bs):
1371
+ global_inputs_embeds_batch_list = []
1372
+ for j in range(sp_degree):
1373
+ prev_len = torch.sum(ulysess_seq_len_cat[:j]).item() if j > 0 else 0
1374
+ start_id = prev_len
1375
+ end_id = prev_len + effective_seqlen_batch_list[i][j]
1376
+ global_inputs_embeds_batch_list.append(
1377
+ all_inputs_embeds[i, start_id:end_id]
1378
+ )
1379
+ global_inputs_embeds_list.append(
1380
+ torch.cat(global_inputs_embeds_batch_list, dim=0)
1381
+ )
1382
+ global_inputs_embeds = torch.nn.utils.rnn.pad_sequence(
1383
+ global_inputs_embeds_list, batch_first=True, padding_value=0
1384
+ )
1385
+ new_inputs_embeds = torch.narrow(
1386
+ global_inputs_embeds,
1387
+ 1,
1388
+ start_idx_reshard,
1389
+ end_idx_reshard - start_idx_reshard,
1390
+ )
1391
+
1392
+ return (
1393
+ None,
1394
+ new_position_ids,
1395
+ new_attention_mask,
1396
+ past_key_values,
1397
+ new_inputs_embeds,
1398
+ new_labels,
1399
+ None, # sorted_seqlens_in_batch set as None for sequence parallelism
1400
+ )
1401
+
1402
+ # kentang-mit@: reorder and repack (reduce computation overhead)
1403
+ # requires transformers replacement.
1404
+ new_inputs_embeds = []
1405
+ new_position_ids = []
1406
+ new_labels = []
1407
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
1408
+ sorted_seqlens_in_batch, sorted_idx = torch.sort(
1409
+ seqlens_in_batch, descending=True
1410
+ )
1411
+ max_seqlen = inputs_embeds.shape[1]
1412
+
1413
+ cur_inputs_embeds = []
1414
+ cur_position_ids = []
1415
+ cur_labels = []
1416
+ cur_batch_len = 0
1417
+ for i in range(len(sorted_seqlens_in_batch)):
1418
+ cur_seqlen = sorted_seqlens_in_batch[i].item()
1419
+ if cur_seqlen + cur_batch_len <= max_seqlen:
1420
+ cur_batch_len += cur_seqlen
1421
+ # each item: num_tokens x num_channels
1422
+ # remove padding on-the-fly
1423
+ cur_inputs_embeds.append(
1424
+ inputs_embeds[sorted_idx[i]][attention_mask[sorted_idx[i]]]
1425
+ )
1426
+ cur_position_ids.append(
1427
+ torch.arange(
1428
+ cur_inputs_embeds[-1].shape[0],
1429
+ device=cur_inputs_embeds[-1].device,
1430
+ )
1431
+ )
1432
+ # each item: num_tokens
1433
+ # remove padding on-the-fly
1434
+ cur_labels.append(labels[sorted_idx[i]][attention_mask[sorted_idx[i]]])
1435
+ else:
1436
+ new_inputs_embeds.append(torch.cat(cur_inputs_embeds, 0))
1437
+ new_position_ids.append(torch.cat(cur_position_ids, 0))
1438
+ new_labels.append(torch.cat(cur_labels, 0))
1439
+ # The current batch is too long. We will start a new batch.
1440
+ cur_batch_len = cur_seqlen
1441
+ cur_inputs_embeds = [
1442
+ inputs_embeds[sorted_idx[i]][attention_mask[sorted_idx[i]]]
1443
+ ]
1444
+ cur_position_ids = [
1445
+ torch.arange(
1446
+ cur_inputs_embeds[-1].shape[0],
1447
+ device=cur_inputs_embeds[-1].device,
1448
+ )
1449
+ ]
1450
+ cur_labels = [labels[sorted_idx[i]][attention_mask[sorted_idx[i]]]]
1451
+ # Mask the first token in the labels for every sample
1452
+ # cur_labels[-1][0] = IGNORE_INDEX
1453
+
1454
+ if len(cur_inputs_embeds):
1455
+ new_inputs_embeds.append(torch.cat(cur_inputs_embeds, 0))
1456
+ new_position_ids.append(torch.cat(cur_position_ids, 0))
1457
+ new_labels.append(torch.cat(cur_labels, 0))
1458
+
1459
+ new_inputs_embeds = torch.nn.utils.rnn.pad_sequence(
1460
+ new_inputs_embeds, batch_first=True, padding_value=self.llm.pad_token_id
1461
+ )
1462
+
1463
+ new_position_ids = torch.nn.utils.rnn.pad_sequence(
1464
+ new_position_ids, batch_first=True, padding_value=-1
1465
+ )
1466
+
1467
+ new_labels = torch.nn.utils.rnn.pad_sequence(
1468
+ new_labels, batch_first=True, padding_value=IGNORE_INDEX
1469
+ )
1470
+ ## yunhao: it's currently a workaround to avoid errors for seq_len < 100
1471
+ new_attention_mask = new_position_ids.ne(-1)
1472
+ # sanity check
1473
+ assert new_attention_mask.sum() == attention_mask.sum()
1474
+
1475
+ # Handle sequence parallelism: Calculate the position ids for sequence parallelism
1476
+ # NOTE: This implementation only works for [<bos>, <img>, ..., <img>, <caption>] pattern
1477
+ # if sp_degree > 1 and sp_rank > 0:
1478
+ # cur_len = new_position_ids.shape[-1]
1479
+ # if sp_rank < sp_degree - 1: # Intermediate ranks
1480
+ # offset = cur_len * sp_rank + 1
1481
+ # new_position_ids = new_position_ids + offset
1482
+ # elif sp_rank == sp_degree - 1: # The last rank
1483
+ # assert new_labels[0, -1] != IGNORE_INDEX, "The first sequence should be longest one."
1484
+ # last_img_token_index = torch.where(new_labels[0] == IGNORE_INDEX)[0][-1]
1485
+ # # print(f"last_img_token_index, {last_img_token_index}")
1486
+ # # if sp_degree == 2: # Handle SP=2, because of bos_token
1487
+ # # offset = last_img_token_index + 3
1488
+ # # else:
1489
+ # # offset = (last_img_token_index + 2) * sp_rank + 1
1490
+ # offset = (last_img_token_index + 1) * sp_rank + 1
1491
+ # offset_mask = new_position_ids != -1
1492
+ # new_position_ids[offset_mask] += offset
1493
+ # else:
1494
+ # raise ValueError(f"sp_rank {sp_rank} is out of range {sp_degree}")
1495
+
1496
+ return (
1497
+ None,
1498
+ new_position_ids,
1499
+ new_attention_mask,
1500
+ past_key_values,
1501
+ new_inputs_embeds,
1502
+ new_labels,
1503
+ sorted_seqlens_in_batch,
1504
+ )
1505
+
1506
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
1507
+ if model_args.mm_use_im_patch_token:
1508
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
1509
+ self.resize_token_embeddings(len(tokenizer))
1510
+
1511
+ if model_args.mm_use_im_start_end:
1512
+ num_new_tokens = tokenizer.add_tokens(
1513
+ [DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True
1514
+ )
1515
+ self.resize_token_embeddings(len(tokenizer))
1516
+
1517
+ if num_new_tokens > 0:
1518
+ input_embeddings = self.get_input_embeddings().weight.data
1519
+ output_embeddings = self.get_output_embeddings().weight.data
1520
+
1521
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
1522
+ dim=0, keepdim=True
1523
+ )
1524
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
1525
+ dim=0, keepdim=True
1526
+ )
1527
+
1528
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
1529
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
1530
+ ## TODO yunhao: handle cases for <im_st> <im_end>
1531
+ if model_args.pretrain_mm_mlp_adapter:
1532
+ mm_projector_weights = torch.load(
1533
+ model_args.pretrain_mm_mlp_adapter, map_location="cpu"
1534
+ )
1535
+ embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
1536
+ assert num_new_tokens == 2
1537
+ if input_embeddings.shape == embed_tokens_weight.shape:
1538
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[
1539
+ -num_new_tokens:
1540
+ ]
1541
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
1542
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
1543
+ else:
1544
+ raise ValueError(
1545
+ f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}."
1546
+ )
1547
+ elif model_args.mm_use_im_patch_token:
1548
+ if model_args.mm_projector:
1549
+ for p in self.get_input_embeddings().parameters():
1550
+ p.requires_grad = False
1551
+ for p in self.get_output_embeddings().parameters():
1552
+ p.requires_grad = False
llava_llama.py ADDED
@@ -0,0 +1,1193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ # from .builder import build_llm_and_tokenizer, build_mm_projector, build_vision_tower
3
+ import os
4
+ import os.path as osp
5
+ import shutil
6
+ import warnings
7
+ from typing import List, Optional, Tuple, Union
8
+
9
+ # from .llava_llama import LlavaLlamaModel
10
+ # from llava.model import *
11
+ # from llava.model.utils import is_mm_model
12
+ import torch
13
+ import torch.nn as nn
14
+ from huggingface_hub import repo_exists, snapshot_download
15
+ from huggingface_hub.utils import HFValidationError, validate_repo_id
16
+ # from llava.model.multimodal_encoder.vision_encoder import (VisionTower,
17
+ # VisionTowerS2)
18
+ from transformers import (AutoConfig, AutoModel, AutoModelForCausalLM,
19
+ AutoTokenizer, BitsAndBytesConfig, GenerationConfig,
20
+ LlamaConfig, LlamaForCausalLM, PretrainedConfig,
21
+ PreTrainedModel, SiglipImageProcessor,
22
+ SiglipVisionModel)
23
+ from transformers.modeling_outputs import CausalLMOutputWithPast
24
+
25
+ from .configuration_llava import LlavaConfig # , LlavaLlamaConfig
26
+ # from .llava_arch import LlavaMetaForCausalLM, LlavaMetaModel
27
+ from .utils import get_model_config
28
+
29
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
30
+ WORKER_HEART_BEAT_INTERVAL = 15
31
+
32
+ LOGDIR = "."
33
+
34
+ # Model Constants
35
+ IGNORE_INDEX = -100
36
+ IMAGE_TOKEN_INDEX = -200
37
+ DEFAULT_IMAGE_TOKEN = "<image>"
38
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
39
+ DEFAULT_IM_START_TOKEN = "<im_start>"
40
+ DEFAULT_IM_END_TOKEN = "<im_end>"
41
+ IMAGE_PLACEHOLDER = "<image-placeholder>"
42
+
43
+ def is_deepspeed_zero3_enabled():
44
+ return None
45
+
46
+ import torch
47
+ import torch.nn as nn
48
+ from transformers import (AutoConfig, AutoModel, PretrainedConfig,
49
+ PreTrainedModel)
50
+
51
+
52
+ class IdentityMap(nn.Module):
53
+ def __init__(self):
54
+ super().__init__()
55
+
56
+ def forward(self, x, *args, **kwargs):
57
+ return x
58
+
59
+ @property
60
+ def config(self):
61
+ return {"mm_projector_type": "identity"}
62
+
63
+
64
+ class SimpleResBlock(nn.Module):
65
+ def __init__(self, channels):
66
+ super().__init__()
67
+ self.pre_norm = nn.LayerNorm(channels)
68
+
69
+ self.proj = nn.Sequential(
70
+ nn.Linear(channels, channels), nn.GELU(), nn.Linear(channels, channels)
71
+ )
72
+
73
+ def forward(self, x):
74
+ x = self.pre_norm(x)
75
+ return x + self.proj(x)
76
+
77
+
78
+ class DownSampleBlock(nn.Module):
79
+ def forward(self, x):
80
+ vit_embeds = x
81
+ h = w = int(vit_embeds.shape[1] ** 0.5)
82
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
83
+ vit_embeds = self.flat_square(vit_embeds)
84
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
85
+ return vit_embeds
86
+
87
+ def flat_square(self, x):
88
+ n, w, h, c = x.size()
89
+ if w % 2 == 1:
90
+ x = torch.concat(
91
+ [x, torch.zeros((n, 1, h, c), dtype=x.dtype).to(x.device)], dim=1
92
+ ).contiguous()
93
+ n, w, h, c = x.size()
94
+ if h % 2 == 1:
95
+ x = torch.concat(
96
+ [x, torch.zeros((n, w, 1, c), dtype=x.dtype).to(x.device)], dim=2
97
+ ).contiguous()
98
+ n, w, h, c = x.size()
99
+ x = x.view(n, w, int(h / 2), int(c * 2))
100
+ x = x.permute(0, 2, 1, 3).contiguous()
101
+ x = x.view(n, int(h / 2), int(w / 2), int(c * 4))
102
+ return x
103
+
104
+
105
+ class MultimodalProjectorConfig(PretrainedConfig):
106
+ model_type = "v2l_projector"
107
+
108
+ def __init__(self, mm_projector_type: str = None, **kwargs):
109
+ super().__init__()
110
+ self.mm_projector_type = mm_projector_type
111
+
112
+
113
+ class MultimodalProjector(PreTrainedModel):
114
+ config_class = MultimodalProjectorConfig
115
+
116
+ def __init__(
117
+ self, mm_projector_cfg: MultimodalProjectorConfig, config: PretrainedConfig
118
+ ):
119
+ super().__init__(mm_projector_cfg)
120
+ mm_projector_type = mm_projector_cfg.mm_projector_type
121
+ if mm_projector_type == "identity":
122
+ self.layers = IdentityMap()
123
+ elif mm_projector_type == "linear":
124
+ self.layers = nn.Linear(config.mm_hidden_size, config.hidden_size)
125
+ elif mm_projector_type == "mlp_downsample":
126
+ self.layers = nn.Sequential(
127
+ DownSampleBlock(),
128
+ nn.LayerNorm(config.mm_hidden_size * 4),
129
+ nn.Linear(config.mm_hidden_size * 4, config.hidden_size),
130
+ nn.GELU(),
131
+ nn.Linear(config.hidden_size, config.hidden_size),
132
+ )
133
+ else:
134
+ mlp_gelu_match = re.match(r"^mlp(\d+)x_gelu$", mm_projector_type)
135
+ if mlp_gelu_match:
136
+ mlp_depth = int(mlp_gelu_match.group(1))
137
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
138
+ for _ in range(1, mlp_depth):
139
+ modules.append(nn.GELU())
140
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
141
+ self.layers = nn.Sequential(*modules)
142
+ else:
143
+ raise ValueError(f"Unknown projector type: {mm_projector_type}")
144
+
145
+ def forward(self, x, *args, **kwargs):
146
+ return self.layers(x)
147
+
148
+
149
+ def build_mm_projector(
150
+ model_type_or_path: str, config: PretrainedConfig
151
+ ) -> PreTrainedModel:
152
+ if model_type_or_path is None:
153
+ return None
154
+
155
+ ## load from pretrained model
156
+ if config.resume_path:
157
+ assert os.path.exists(
158
+ model_type_or_path
159
+ ), f"Resume mm projector path {model_type_or_path} does not exist!"
160
+ return MultimodalProjector.from_pretrained(
161
+ model_type_or_path, config, torch_dtype=eval(config.model_dtype)
162
+ )
163
+ ## build from scratch
164
+ else:
165
+ mm_projector_cfg = MultimodalProjectorConfig(model_type_or_path)
166
+ mm_projector = MultimodalProjector(mm_projector_cfg, config).to(
167
+ eval(config.model_dtype)
168
+ )
169
+ return mm_projector
170
+
171
+
172
+ class VisionTower(nn.Module):
173
+ def __init__(self, vision_tower, args, delay_load=False):
174
+ super().__init__()
175
+
176
+ self.is_loaded = False
177
+
178
+ self.vision_tower_name = vision_tower
179
+ self.select_layer = getattr(args, "mm_vision_select_layer", -2)
180
+ self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
181
+
182
+ self.cfg_only = None
183
+
184
+ def feature_select(self, image_forward_outs):
185
+ image_features = image_forward_outs.hidden_states[self.select_layer]
186
+ if self.select_feature == "patch":
187
+ image_features = image_features[:, 1:]
188
+ elif self.select_feature == "cls_patch":
189
+ image_features = image_features
190
+ else:
191
+ raise ValueError(f"Unexpected select feature: {self.select_feature}")
192
+ return image_features
193
+
194
+ def _maybe_resize_pos_embeds(
195
+ self,
196
+ model: PreTrainedModel,
197
+ image_processor,
198
+ resolution: int = -1,
199
+ interpolate_mode: str = "linear",
200
+ ):
201
+ if resolution in [model.config.image_size, -1]:
202
+ return
203
+ print(
204
+ f"Resizing vision model's position embeddings to support higher vision resolution: from {model.config.image_size} to {resolution} ..."
205
+ )
206
+ embeddings = model.vision_model.embeddings
207
+ patch_size = embeddings.patch_size
208
+ num_new_tokens = int((resolution // patch_size) ** 2)
209
+
210
+ old_embeddings = embeddings.position_embedding
211
+ match interpolate_mode:
212
+ case "linear":
213
+ ## Step 1: Calculate the corresponding patch ID (pid) in the current resolution (M patches) based on the target resolution (N patches). Formula: pid = pid / N * M
214
+ ## Step 2: Obtain new embeddings by interpolating between the embeddings of the two nearest calculated patch IDs. Formula: new_embeds = (pid - floor(pid)) * embeds[ceil(pid)] + (ceil(pid) - pid) * embeds[floor(pid)]
215
+ import torch
216
+ import torch.nn as nn
217
+
218
+
219
+ old_num_tokens, old_embedding_dim = old_embeddings.weight.size()
220
+ new_embeddings = nn.Embedding(
221
+ num_new_tokens,
222
+ old_embedding_dim,
223
+ dtype=old_embeddings.weight.dtype,
224
+ device=old_embeddings.weight.device,
225
+ )
226
+ mapped_indices = (
227
+ torch.arange(num_new_tokens).to(old_embeddings.weight.device)
228
+ / (num_new_tokens - 1)
229
+ * (old_num_tokens - 1)
230
+ )
231
+ floor_indices = torch.clamp(
232
+ mapped_indices.floor().long(), min=0, max=old_num_tokens - 1
233
+ )
234
+ ceil_indices = torch.clamp(
235
+ mapped_indices.ceil().long(), min=0, max=old_num_tokens - 1
236
+ )
237
+ if is_deepspeed_zero3_enabled():
238
+ params = [old_embeddings.weight, new_embeddings.weight]
239
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
240
+ interpolated_embeds = (mapped_indices - floor_indices)[
241
+ :, None
242
+ ] * old_embeddings.weight.data[ceil_indices, :] + (
243
+ ceil_indices - mapped_indices
244
+ )[
245
+ :, None
246
+ ] * old_embeddings.weight.data[
247
+ floor_indices, :
248
+ ]
249
+ else:
250
+ interpolated_embeds = (mapped_indices - floor_indices)[
251
+ :, None
252
+ ] * old_embeddings.weight.data[ceil_indices, :] + (
253
+ ceil_indices - mapped_indices
254
+ )[
255
+ :, None
256
+ ] * old_embeddings.weight.data[
257
+ floor_indices, :
258
+ ]
259
+ new_embeddings.weight.data = interpolated_embeds
260
+ case _:
261
+ raise NotImplementedError
262
+
263
+ if hasattr(old_embeddings, "_hf_hook"):
264
+ hook = old_embeddings._hf_hook
265
+ # disable to inference
266
+ # add_hook_to_module(new_embeddings, hook)
267
+ new_embeddings.requires_grad_(old_embeddings.weight.requires_grad)
268
+ ## update vision encoder's configurations
269
+ model.config.image_size = resolution
270
+ if hasattr(image_processor, "crop_size"):
271
+ # CLIP vision tower
272
+ image_processor.crop_size = resolution
273
+ else:
274
+ # SIGLIP vision tower
275
+ assert hasattr(image_processor, "size")
276
+ image_processor.size = {"height": resolution, "width": resolution}
277
+ ## TODO define a '_reinitialize' method for VisionTower
278
+ embeddings.position_embedding = new_embeddings
279
+ embeddings.image_size = resolution
280
+ embeddings.num_patches = embeddings.num_positions = num_new_tokens
281
+ embeddings.position_ids = (
282
+ torch.arange(embeddings.num_positions)
283
+ .expand((1, -1))
284
+ .to(old_embeddings.weight.device)
285
+ )
286
+
287
+ def forward(self, images):
288
+ if type(images) is list:
289
+ image_features = []
290
+ for image in images:
291
+ image_forward_out = self.vision_tower(
292
+ image.to(device=self.device, dtype=self.dtype).unsqueeze(0),
293
+ output_hidden_states=True,
294
+ )
295
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
296
+ image_features.append(image_feature)
297
+ else:
298
+ image_forward_outs = self.vision_tower(
299
+ images.to(device=self.device, dtype=self.dtype),
300
+ output_hidden_states=True,
301
+ )
302
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
303
+
304
+ return image_features
305
+
306
+ @property
307
+ def dummy_feature(self):
308
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
309
+
310
+ @property
311
+ def dtype(self):
312
+ return self.vision_tower.dtype
313
+
314
+ @property
315
+ def device(self):
316
+ return self.vision_tower.device
317
+
318
+ @property
319
+ def config(self):
320
+ if self.is_loaded:
321
+ return self.vision_tower.config
322
+ else:
323
+ return self.cfg_only
324
+
325
+ @property
326
+ def hidden_size(self):
327
+ return self.config.hidden_size
328
+
329
+ @property
330
+ def num_patches(self):
331
+ return (self.config.image_size // self.config.patch_size) ** 2
332
+
333
+
334
+ class SiglipVisionTower(VisionTower):
335
+ def __init__(
336
+ self, model_name_or_path: str, config: PretrainedConfig, state_dict=None
337
+ ):
338
+ super().__init__(model_name_or_path, config)
339
+ self.image_processor = SiglipImageProcessor.from_pretrained(model_name_or_path)
340
+ self.vision_tower = SiglipVisionModel.from_pretrained(
341
+ # TODO(ligeng): why pass config here leading to errors?
342
+ model_name_or_path,
343
+ torch_dtype=eval(config.model_dtype),
344
+ state_dict=state_dict,
345
+ )
346
+ self.is_loaded = True
347
+
348
+
349
+
350
+ def build_vision_tower(
351
+ model_name_or_path: str, config: PretrainedConfig
352
+ ) -> PreTrainedModel:
353
+ ## skip vision tower instantiation
354
+ if model_name_or_path is None:
355
+ return None
356
+
357
+ vision_tower_arch = None
358
+ if config.resume_path and "radio" not in model_name_or_path:
359
+ assert os.path.exists(
360
+ model_name_or_path
361
+ ), f"Resume vision tower path {model_name_or_path} does not exist!"
362
+ vision_tower_cfg = AutoConfig.from_pretrained(
363
+ model_name_or_path, trust_remote_code=True
364
+ )
365
+ vision_tower_arch = vision_tower_cfg.architectures[0].lower()
366
+ vision_tower_name = (
367
+ vision_tower_arch if vision_tower_arch is not None else model_name_or_path
368
+ )
369
+
370
+ use_s2 = getattr(config, "s2", False)
371
+
372
+ if "siglip" in vision_tower_name:
373
+ if use_s2:
374
+ vision_tower = SiglipVisionTowerS2(model_name_or_path, config)
375
+ else:
376
+ vision_tower = SiglipVisionTower(model_name_or_path, config)
377
+ else:
378
+ raise ValueError(f"Unknown vision tower: {model_name_or_path}")
379
+
380
+ config.mm_hidden_size = (
381
+ vision_tower.config.hidden_size if not use_s2 else vision_tower.hidden_size
382
+ )
383
+ return vision_tower
384
+
385
+
386
+
387
+ def has_tokenizer(repo_id_or_path: str) -> bool:
388
+ # Check if the tokenizer is in a local directory
389
+ if osp.exists(osp.join(repo_id_or_path, "tokenizer_config.json")):
390
+ return True
391
+
392
+ # Check if the tokenizer is in a Hugging Face Hub repo
393
+ try:
394
+ return repo_exists(repo_id_or_path) and file_exists(
395
+ repo_id_or_path, "tokenizer_config.json"
396
+ )
397
+ except HFValidationError:
398
+ return False
399
+
400
+
401
+ def context_length_extension(config):
402
+ orig_ctx_len = getattr(config, "max_position_embeddings", None)
403
+ model_max_length = getattr(config, "model_max_length", None)
404
+ if orig_ctx_len and model_max_length > orig_ctx_len:
405
+ print(f"Scaling RoPE from {orig_ctx_len} to {model_max_length}")
406
+ scaling_factor = float(math.ceil(model_max_length / orig_ctx_len))
407
+ config.rope_scaling = {"type": "linear", "factor": scaling_factor}
408
+ return config
409
+
410
+
411
+ def build_llm_and_tokenizer(
412
+ model_name_or_path: str,
413
+ config: PretrainedConfig,
414
+ attn_implementation=None,
415
+ model_max_length=None,
416
+ *args,
417
+ **kwargs,
418
+ ):
419
+ llm_cfg = AutoConfig.from_pretrained(model_name_or_path)
420
+ llm_cfg._attn_implementation = attn_implementation
421
+ llm_cfg.model_max_length = model_max_length
422
+ if model_max_length is not None:
423
+ context_length_extension(llm_cfg)
424
+
425
+ llm = AutoModelForCausalLM.from_pretrained(
426
+ model_name_or_path,
427
+ config=llm_cfg,
428
+ torch_dtype=eval(config.model_dtype),
429
+ *args,
430
+ **kwargs,
431
+ )
432
+
433
+ # Locate the tokenizer.
434
+ llm_path = model_name_or_path
435
+ if not has_tokenizer(llm_path):
436
+ llm_path = osp.join(llm_path, "llm")
437
+ if not has_tokenizer(llm_path):
438
+ raise ValueError(f"Cannot find tokenizer in {llm_path}.")
439
+
440
+ # TODO(ligeng): use LLM class to judge to better compability.
441
+ try:
442
+ llm_arch = getattr(llm_cfg, "architectures")[0].lower()
443
+ except BaseException:
444
+ warnings.warn(
445
+ f'Cannot find LLM architecture, please check the "config.json" under "{llm_path}".'
446
+ )
447
+
448
+ if "mpt" in llm_arch:
449
+ tokenizer = AutoTokenizer.from_pretrained(
450
+ llm_path,
451
+ model_max_length=llm_cfg.model_max_length,
452
+ padding_side="right",
453
+ )
454
+ elif "yi" in llm_path or (
455
+ getattr(llm_cfg, "num_hidden_layers", -1) == 60
456
+ and getattr(llm_cfg, "num_attention_heads", -1) == 56
457
+ ):
458
+ tokenizer = AutoTokenizer.from_pretrained(
459
+ llm_path,
460
+ model_max_length=llm_cfg.model_max_length,
461
+ padding_side="right",
462
+ use_fast=False,
463
+ )
464
+ else:
465
+ tokenizer = AutoTokenizer.from_pretrained(
466
+ llm_path,
467
+ model_max_length=llm_cfg.model_max_length,
468
+ padding_side="right",
469
+ use_fast=False,
470
+ legacy=False,
471
+ )
472
+
473
+ # TODO(ligeng): is this necessary for llava?
474
+ config.hidden_size = llm.config.hidden_size
475
+ return llm, tokenizer
476
+
477
+
478
+ def is_mm_model(model_path):
479
+ """
480
+ Check if the model at the given path is a visual language model.
481
+
482
+ Args:
483
+ model_path (str): The path to the model.
484
+
485
+ Returns:
486
+ bool: True if the model is an MM model, False otherwise.
487
+ """
488
+ config = AutoConfig.from_pretrained(model_path)
489
+ architectures = config.architectures
490
+ for architecture in architectures:
491
+ if "llava" in architecture.lower():
492
+ return True
493
+ return False
494
+
495
+
496
+ def load_pretrained_model(
497
+ model_path,
498
+ model_name,
499
+ model_base=None,
500
+ load_8bit=False,
501
+ load_4bit=False,
502
+ device_map="auto",
503
+ device="cuda",
504
+ **kwargs,
505
+ ):
506
+ kwargs = {"device_map": device_map, **kwargs}
507
+
508
+ if device != "cuda":
509
+ kwargs["device_map"] = {"": device}
510
+
511
+ if load_8bit:
512
+ kwargs["load_in_8bit"] = True
513
+ elif load_4bit:
514
+ kwargs["load_in_4bit"] = True
515
+ kwargs["quantization_config"] = BitsAndBytesConfig(
516
+ load_in_4bit=True,
517
+ bnb_4bit_compute_dtype=torch.float16,
518
+ bnb_4bit_use_double_quant=True,
519
+ bnb_4bit_quant_type="nf4",
520
+ )
521
+ else:
522
+ kwargs["torch_dtype"] = torch.float16
523
+ # kwargs["torch_dtype"] = torch.bfloat16
524
+
525
+ if is_mm_model(model_path):
526
+ # Load LLaVA model
527
+ ## TODO @yunhao: mind fixing lora
528
+ if "lora" in model_name.lower() and model_base is None:
529
+ warnings.warn(
530
+ "There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged."
531
+ )
532
+ if (
533
+ "lora" in model_name.lower() or "dora" in model_name.lower()
534
+ ) and model_base is not None:
535
+ lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
536
+ print(lora_cfg_pretrained)
537
+ print("Loading LLaVA from base model...")
538
+ config = AutoConfig.from_pretrained(model_base)
539
+ prepare_config_for_eval(config, kwargs)
540
+ model = LlavaLlamaModel.from_pretrained(
541
+ model_base, low_cpu_mem_usage=True, config=config, **kwargs
542
+ )
543
+ tokenizer = model.tokenizer
544
+ token_num, tokem_dim = (
545
+ model.llm.lm_head.out_features,
546
+ model.llm.lm_head.in_features,
547
+ )
548
+ if model.llm.lm_head.weight.shape[0] != token_num:
549
+ model.llm.lm_head.weight = torch.nn.Parameter(
550
+ torch.empty(
551
+ token_num, tokem_dim, device=model.device, dtype=model.dtype
552
+ )
553
+ )
554
+ model.llm.embed_tokens.weight = torch.nn.Parameter(
555
+ torch.empty(
556
+ token_num, tokem_dim, device=model.device, dtype=model.dtype
557
+ )
558
+ )
559
+
560
+ print("Loading additional LLaVA weights...")
561
+ if os.path.exists(os.path.join(model_path, "non_lora_trainables.bin")):
562
+ non_lora_trainables = torch.load(
563
+ os.path.join(model_path, "non_lora_trainables.bin"),
564
+ map_location="cpu",
565
+ )
566
+ else:
567
+ # this is probably from HF Hub
568
+ from huggingface_hub import hf_hub_download
569
+
570
+ def load_from_hf(repo_id, filename, subfolder=None):
571
+ cache_file = hf_hub_download(
572
+ repo_id=repo_id, filename=filename, subfolder=subfolder
573
+ )
574
+ return torch.load(cache_file, map_location="cpu")
575
+
576
+ non_lora_trainables = load_from_hf(
577
+ model_path, "non_lora_trainables.bin"
578
+ )
579
+ non_lora_trainables = {
580
+ (k[11:] if k.startswith("base_model.") else k): v
581
+ for k, v in non_lora_trainables.items()
582
+ }
583
+ if any(k.startswith("model.model.") for k in non_lora_trainables):
584
+ non_lora_trainables = {
585
+ (k[6:] if k.startswith("model.") else k): v
586
+ for k, v in non_lora_trainables.items()
587
+ }
588
+ model.load_state_dict(non_lora_trainables, strict=False)
589
+
590
+ from peft import PeftModel
591
+
592
+ print("Loading LoRA weights...")
593
+ model = PeftModel.from_pretrained(model, model_path)
594
+ print("Merging LoRA weights...")
595
+ model = model.merge_and_unload()
596
+ print("Model is loaded...")
597
+ ## TODO @yunhao: mind fixing this
598
+ elif model_base is not None:
599
+ # this may be mm projector only
600
+ print("Loading LLaVA from base model...")
601
+ cfg_pretrained = AutoConfig.from_pretrained(
602
+ model_path, trust_remote_code=True
603
+ )
604
+ mm_config_wrapper(config, kwargs)
605
+ if "mpt" in model_name.lower():
606
+ if not os.path.isfile(os.path.join(model_path, "configuration_mpt.py")):
607
+ shutil.copyfile(
608
+ os.path.join(model_base, "configuration_mpt.py"),
609
+ os.path.join(model_path, "configuration_mpt.py"),
610
+ )
611
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
612
+ model = LlavaMPTForCausalLM.from_pretrained(
613
+ model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs
614
+ )
615
+ else:
616
+ tokenizer = AutoTokenizer.from_pretrained(
617
+ model_base, use_fast=False, legacy=False
618
+ )
619
+ model = LlavaLlamaForCausalLM.from_pretrained(
620
+ model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs
621
+ )
622
+ else:
623
+ config = AutoConfig.from_pretrained(model_path)
624
+ config.resume_path = model_path
625
+ prepare_config_for_eval(config, kwargs)
626
+ if "mpt" in model_name.lower():
627
+ model = LlavaMPTForCausalLM.from_pretrained(
628
+ model_path, config=config, low_cpu_mem_usage=True, **kwargs
629
+ )
630
+ elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
631
+ model = LlavaMistralForCausalLM.from_pretrained(
632
+ model_path, config=config, low_cpu_mem_usage=True, **kwargs
633
+ )
634
+ elif "gemma" in model_name.lower():
635
+ model = LlavaGemmaForCausalLM.from_pretrained(
636
+ model_path, config=config, low_cpu_mem_usage=True, **kwargs
637
+ )
638
+ else:
639
+ # kentang-mit@: llama-2 model
640
+ # config._attn_implementation = "flash_attention_2"
641
+ model = LlavaLlamaModel(config=config, low_cpu_mem_usage=True, **kwargs)
642
+ tokenizer = model.tokenizer
643
+ else:
644
+ # Load language model
645
+ if model_base is not None:
646
+ # PEFT model
647
+ from peft import PeftModel
648
+
649
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
650
+ model = AutoModelForCausalLM.from_pretrained(
651
+ model_base, low_cpu_mem_usage=True, **kwargs
652
+ )
653
+ print(f"Loading LoRA weights from {model_path}")
654
+ model = PeftModel.from_pretrained(model, model_path)
655
+ print(f"Merging weights")
656
+ model = model.merge_and_unload()
657
+ print("Convert to FP16...")
658
+ model.to(torch.float16)
659
+ else:
660
+ if "mpt" in model_name.lower():
661
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
662
+ model = AutoModelForCausalLM.from_pretrained(
663
+ model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs
664
+ )
665
+ else:
666
+ tokenizer = AutoTokenizer.from_pretrained(
667
+ model_path, use_fast=False, legacy=False
668
+ )
669
+ model = AutoModelForCausalLM.from_pretrained(
670
+ model_path, low_cpu_mem_usage=True, **kwargs
671
+ )
672
+ model.eval()
673
+ image_processor = None
674
+ if is_mm_model(model_path):
675
+ mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
676
+ mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
677
+ if mm_use_im_patch_token:
678
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
679
+ if mm_use_im_start_end:
680
+ tokenizer.add_tokens(
681
+ [DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True
682
+ )
683
+ model.resize_token_embeddings(len(tokenizer))
684
+ vision_tower = model.get_vision_tower()
685
+ vision_tower.to(device=device, dtype=torch.float16)
686
+ # vision_tower.to(device=device, dtype=torch.bfloat16)
687
+ mm_projector = model.get_mm_projector()
688
+ mm_projector.to(device=device, dtype=torch.float16)
689
+ # mm_projector.to(device=device, dtype=torch.bfloat16)
690
+ image_processor = vision_tower.image_processor
691
+
692
+ if hasattr(model.llm.config, "max_sequence_length"):
693
+ context_len = model.config.max_sequence_length
694
+ else:
695
+ context_len = 2048
696
+
697
+ return tokenizer, model, image_processor, context_len
698
+
699
+
700
+ def parse_model_name_or_path(config: PretrainedConfig, model_name="llm", suffix="_cfg"):
701
+ target_model = f"{model_name}{suffix}"
702
+ target_cfg = getattr(config, target_model, None)
703
+
704
+ if isinstance(target_cfg, str):
705
+ return target_cfg
706
+ elif isinstance(target_cfg, dict):
707
+ return target_cfg["architectures"][0]
708
+ else:
709
+ raise ValueError(f"Invalid {target_model} configuration!")
710
+
711
+
712
+ def prepare_config_for_eval(config: PretrainedConfig, kwargs: dict):
713
+ try:
714
+ # compatible with deprecated config convention
715
+ if getattr(config, "vision_tower_cfg", None) is None:
716
+ config.vision_tower_cfg = config.mm_vision_tower
717
+ except AttributeError:
718
+ raise ValueError(
719
+ f"Invalid configuration! Cannot find vision_tower in config:\n{config}"
720
+ )
721
+
722
+ config.model_dtype = kwargs.pop("torch_dtype").__str__()
723
+ # siglip does not support device_map = "auto"
724
+ vision_tower_name = parse_model_name_or_path(config, "vision_tower")
725
+ if "siglip" in vision_tower_name.lower():
726
+ kwargs["device_map"] = "cuda"
727
+
728
+
729
+ class LlavaLlamaConfig(LlavaConfig):
730
+ model_type = "llava_llama"
731
+
732
+
733
+ # class LlavaLlamaModel(PreTrainedModel):
734
+ # config_class = LlavaLlamaConfig
735
+ # main_input_name = "input_embeds"
736
+ # supports_gradient_checkpointing = True
737
+
738
+ # @classmethod
739
+ # def from_pretrained(
740
+ # cls,
741
+ # pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
742
+ # *model_args,
743
+ # config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
744
+ # cache_dir: Optional[Union[str, os.PathLike]] = None,
745
+ # ignore_mismatched_sizes: bool = False,
746
+ # force_download: bool = False,
747
+ # local_files_only: bool = False,
748
+ # token: Optional[Union[str, bool]] = None,
749
+ # revision: str = "main",
750
+ # use_safetensors: bool = None,
751
+ # **kwargs,
752
+ # ):
753
+ # if hasattr(cls, "load_pretrained"):
754
+ # return cls.load_pretrained(
755
+ # pretrained_model_name_or_path,
756
+ # *model_args,
757
+ # config=config,
758
+ # cache_dir=cache_dir,
759
+ # ignore_mismatched_sizes=ignore_mismatched_sizes,
760
+ # force_download=force_download,
761
+ # local_files_only=local_files_only,
762
+ # token=token,
763
+ # revision=revision,
764
+ # use_safetensors=use_safetensors,
765
+ # **kwargs,
766
+ # )
767
+ # return None
768
+
769
+ from abc import ABC, abstractmethod
770
+ from collections import OrderedDict
771
+
772
+
773
+ class LlavaMetaModel(ABC):
774
+ def init_vlm(self, config: PreTrainedModel = None, *args, **kwargs):
775
+ # TODO(ligeng): figure out how from_config and from_pretrained works in HF implementation.
776
+ if (
777
+ hasattr(self, "llm")
778
+ or hasattr(self, "vision_tower")
779
+ or hasattr(self, "mm_projector")
780
+ ):
781
+ # already initialized, skipped
782
+ return
783
+
784
+ model_dtype = getattr(config, "model_dtype", "torch.float16")
785
+ if not hasattr(config, "model_dtype"):
786
+ warnings.warn(
787
+ "model_dtype not found in config, defaulting to torch.float16."
788
+ )
789
+ config.model_dtype = model_dtype
790
+
791
+ cfgs = get_model_config(config)
792
+ if len(cfgs) == 3:
793
+ llm_cfg, vision_tower_cfg, mm_projector_cfg = cfgs
794
+ else:
795
+ raise ValueError(
796
+ "`llm_cfg` `mm_projector_cfg` `vision_tower_cfg` not found in the config."
797
+ )
798
+
799
+ self.llm, self.tokenizer = build_llm_and_tokenizer(
800
+ llm_cfg, config, *args, **kwargs
801
+ )
802
+ self.vision_tower = build_vision_tower(vision_tower_cfg, config)
803
+ self.mm_projector = build_mm_projector(mm_projector_cfg, config)
804
+
805
+ self.post_config()
806
+ self.is_loaded = True
807
+
808
+ assert (
809
+ self.llm is not None
810
+ or self.vision_tower is not None
811
+ or self.mm_projector is not None
812
+ ), "At least one of the components must be instantiated."
813
+
814
+ @classmethod
815
+ def load_from_config(cls, model_path_or_config, *args, **kwargs):
816
+ pass
817
+
818
+ ## FIXME we will use this function to load model in the future
819
+ @classmethod
820
+ def load_pretrained(cls, model_path_or_config, *args, **kwargs):
821
+ kwargs.pop("config", None)
822
+
823
+ if isinstance(model_path_or_config, str):
824
+ config = AutoConfig.from_pretrained(model_path_or_config)
825
+ elif isinstance(model_path_or_config, LlavaConfig):
826
+ config = model_path_or_config
827
+ else:
828
+ raise NotImplementedError(
829
+ f"wrong type, {type(model_path_or_config)} \
830
+ {isinstance(model_path_or_config, LlavaConfig)}"
831
+ )
832
+
833
+ model_dtype = getattr(config, "model_dtype", "torch.float16")
834
+ if not hasattr(config, "model_dtype"):
835
+ warnings.warn(
836
+ "model_dtype not found in config, defaulting to torch.float16."
837
+ )
838
+ config.model_dtype = model_dtype
839
+
840
+ cfgs = get_model_config(config)
841
+ if len(cfgs) == 3:
842
+ llm_cfg, vision_tower_cfg, mm_projector_cfg = cfgs
843
+ else:
844
+ raise ValueError(
845
+ "`llm_cfg` `mm_projector_cfg` `vision_tower_cfg` not found in the config."
846
+ )
847
+
848
+ vlm = cls(config, *args, **kwargs)
849
+ # print(llm_cfg, vision_tower_cfg, mm_projector_cfg); input("DEBUG load_pretrained finish")
850
+
851
+ if (
852
+ hasattr(vlm, "llm")
853
+ or hasattr(vlm, "vision_tower")
854
+ or hasattr(vlm, "mm_projector")
855
+ ):
856
+ if vlm.is_loaded:
857
+ return vlm
858
+
859
+ vlm.llm, vlm.tokenizer = build_llm_and_tokenizer(
860
+ llm_cfg, config, *args, **kwargs
861
+ )
862
+ vlm.vision_tower = build_vision_tower(vision_tower_cfg, config)
863
+ vlm.mm_projector = build_mm_projector(mm_projector_cfg, config)
864
+
865
+ cls.post_config()
866
+ cls.is_loaded = True
867
+
868
+ # FIXME(ligeng, yunhao): llm should never be none here.
869
+ assert (
870
+ vlm.llm is not None
871
+ or vlm.vision_tower is not None
872
+ or vlm.mm_projector is not None
873
+ ), "At least one of the components must be instantiated."
874
+ return vlm
875
+
876
+ ## FIXME we will use this function to save the model in the future
877
+ def save_pretrained(self, output_dir, state_dict=None):
878
+ if state_dict is None:
879
+ # other wise fetch from deepspeed
880
+ # state_dict = accelerator.get_state_dict(is_deepspeed_enabled)
881
+ state_dict = self.state_dict()
882
+
883
+ if getattr(self, "tokenizer", None):
884
+ self.tokenizer.save_pretrained(osp.join(output_dir, "llm"))
885
+
886
+ if self.get_llm():
887
+ print(f"saving llm to {osp.join(output_dir, 'llm')}")
888
+ self.llm.config._name_or_path = osp.join(output_dir, "llm")
889
+ llm_state_dict = OrderedDict(
890
+ {k.split("llm.")[-1]: v for k, v in state_dict.items() if "llm" in k}
891
+ )
892
+ self.llm.save_pretrained(
893
+ os.path.join(output_dir, "llm"), state_dict=llm_state_dict
894
+ )
895
+ self.config.llm_cfg = self.llm.config
896
+
897
+ if self.get_vision_tower():
898
+ print(f"saving vision_tower to {osp.join(output_dir, 'vision_tower')}")
899
+ self.vision_tower.config._name_or_path = osp.join(
900
+ output_dir, "vision_tower"
901
+ )
902
+ vision_tower_state_dict = OrderedDict(
903
+ {
904
+ k.split("vision_tower.vision_tower.")[-1]: v
905
+ for k, v in state_dict.items()
906
+ if "vision_tower" in k
907
+ }
908
+ )
909
+ self.vision_tower.vision_tower.save_pretrained(
910
+ os.path.join(output_dir, "vision_tower"),
911
+ state_dict=vision_tower_state_dict,
912
+ )
913
+ self.vision_tower.image_processor.save_pretrained(
914
+ os.path.join(output_dir, "vision_tower")
915
+ )
916
+ self.config.vision_tower_cfg = self.vision_tower.config
917
+ if hasattr(self.config.vision_tower_cfg, "auto_map"):
918
+ if "radio" not in self.get_vision_tower().__class__.__name__.lower():
919
+ delattr(self.config.vision_tower_cfg, "auto_map")
920
+
921
+ if self.get_mm_projector():
922
+ print(f"saving mm_projector to {osp.join(output_dir, 'mm_projector')}")
923
+ self.mm_projector.config._name_or_path = osp.join(
924
+ output_dir, "mm_projector"
925
+ )
926
+ mm_projector_state_dict = OrderedDict(
927
+ {
928
+ k.split("mm_projector.")[-1]: v
929
+ for k, v in state_dict.items()
930
+ if "mm_projector" in k
931
+ }
932
+ )
933
+ self.mm_projector.save_pretrained(
934
+ os.path.join(output_dir, "mm_projector"),
935
+ state_dict=mm_projector_state_dict,
936
+ )
937
+ self.config.mm_projector_cfg = self.mm_projector.config
938
+ ## update and save top-level config
939
+ self.config._name_or_path = output_dir
940
+ self.config.architectures = [self.__class__.__name__]
941
+ self.config.save_pretrained(output_dir)
942
+
943
+ def get_llm(self):
944
+ llm = getattr(self, "llm", None)
945
+ if type(llm) is list:
946
+ llm = llm[0]
947
+ return llm
948
+
949
+ def get_lm_head(self):
950
+ lm_head = getattr(self.get_llm(), "lm_head", None)
951
+ return lm_head
952
+
953
+ def get_vision_tower(self):
954
+ vision_tower = getattr(self, "vision_tower", None)
955
+ if type(vision_tower) is list:
956
+ vision_tower = vision_tower[0]
957
+ return vision_tower
958
+
959
+ def get_mm_projector(self):
960
+ mm_projector = getattr(self, "mm_projector", None)
961
+ if type(mm_projector) is list:
962
+ mm_projector = mm_projector[0]
963
+ return mm_projector
964
+
965
+ def post_config(self):
966
+ self.training = self.get_llm().training
967
+ ## configuration
968
+ if getattr(self.config, "llm_cfg", None) is None:
969
+ self.config.llm_cfg = self.llm.config
970
+ if getattr(self.config, "vision_tower_cfg", None) is None:
971
+ self.config.vision_tower_cfg = self.vision_tower.config
972
+ if getattr(self.config, "mm_projector_cfg", None) is None:
973
+ self.config.mm_projector_cfg = self.mm_projector.config
974
+
975
+ def freezed_module_patch(self):
976
+ """
977
+ Huggingface will call model.train() at each training_step. To ensure the expected behaviors for modules like dropout, batchnorm, etc., we need to call model.eval() for the freezed modules.
978
+ """
979
+ if self.training:
980
+ if self.get_llm() and not getattr(
981
+ self.config, "tune_language_model", False
982
+ ):
983
+ pass
984
+ # logging.warning("Caution: Your LLM is currently in training mode, ensuring accurate gradient computation. Please be vigilant, particularly regarding BatchNorm and Dropout operations.")
985
+ if self.get_vision_tower() and not getattr(
986
+ self.config, "tune_vision_tower", False
987
+ ):
988
+ self.get_vision_tower().eval()
989
+ if self.get_mm_projector() and not getattr(
990
+ self.config, "tune_mm_projector", False
991
+ ):
992
+ self.get_mm_projector().eval()
993
+
994
+ def encode_images(self, images):
995
+ image_features = self.get_vision_tower()(images)
996
+ image_features = self.get_mm_projector()(image_features)
997
+ return image_features
998
+
999
+ ## @yunhao: is there a better way to handle function call and attributes for llm?
1000
+ ## support beam search
1001
+ def _temporary_reorder_cache(self, past_key_values, sorted_idx):
1002
+ return self.get_llm()._temporary_reorder_cache(past_key_values, sorted_idx)
1003
+
1004
+ def get_input_embeddings(self):
1005
+ return self.get_llm().get_input_embeddings()
1006
+
1007
+ def get_output_embeddings(self):
1008
+ return self.get_llm().get_output_embeddings()
1009
+
1010
+ def resize_token_embeddings(self, embed_size):
1011
+ self.get_llm().resize_token_embeddings(embed_size)
1012
+
1013
+
1014
+ # ## FIXME we will follow the convention to add a new class for CausalLM in the future
1015
+ class LlavaLlamaModel(LlavaMetaModel, PreTrainedModel):
1016
+ config_class = LlavaLlamaConfig
1017
+ main_input_name = "input_embeds"
1018
+ supports_gradient_checkpointing = True
1019
+
1020
+ def __init__(self, config: LlavaLlamaConfig = None, *args, **kwargs) -> None:
1021
+ super().__init__(config)
1022
+ return self.init_vlm(config=config, *args, **kwargs)
1023
+
1024
+ @classmethod
1025
+ def from_pretrained(
1026
+ cls,
1027
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
1028
+ *model_args,
1029
+ config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
1030
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
1031
+ ignore_mismatched_sizes: bool = False,
1032
+ force_download: bool = False,
1033
+ local_files_only: bool = False,
1034
+ token: Optional[Union[str, bool]] = None,
1035
+ revision: str = "main",
1036
+ use_safetensors: bool = None,
1037
+ **kwargs,
1038
+ ):
1039
+ if hasattr(cls, "load_pretrained"):
1040
+ return cls.load_pretrained(
1041
+ pretrained_model_name_or_path,
1042
+ *model_args,
1043
+ config=config,
1044
+ cache_dir=cache_dir,
1045
+ ignore_mismatched_sizes=ignore_mismatched_sizes,
1046
+ force_download=force_download,
1047
+ local_files_only=local_files_only,
1048
+ token=token,
1049
+ revision=revision,
1050
+ use_safetensors=use_safetensors,
1051
+ **kwargs,
1052
+ )
1053
+ return super(LlavaLlamaModel).from_pretrained(
1054
+ pretrained_model_name_or_path,
1055
+ *model_args,
1056
+ config=config,
1057
+ cache_dir=cache_dir,
1058
+ ignore_mismatched_sizes=ignore_mismatched_sizes,
1059
+ force_download=force_download,
1060
+ local_files_only=local_files_only,
1061
+ token=token,
1062
+ revision=revision,
1063
+ use_safetensors=use_safetensors,
1064
+ **kwargs,
1065
+ )
1066
+
1067
+ def forward(
1068
+ self,
1069
+ input_ids: torch.LongTensor = None,
1070
+ images: Optional[torch.FloatTensor] = None,
1071
+ attention_mask: Optional[torch.Tensor] = None,
1072
+ position_ids: Optional[torch.LongTensor] = None,
1073
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1074
+ seqlens_in_batch: Optional[torch.LongTensor] = None,
1075
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1076
+ labels: Optional[torch.LongTensor] = None,
1077
+ use_cache: Optional[bool] = None,
1078
+ output_attentions: Optional[bool] = None,
1079
+ output_hidden_states: Optional[bool] = None,
1080
+ return_dict: Optional[bool] = None,
1081
+ dpo_forward: bool = False,
1082
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1083
+ self.freezed_module_patch()
1084
+ if inputs_embeds is None:
1085
+ (
1086
+ input_ids,
1087
+ position_ids,
1088
+ attention_mask,
1089
+ past_key_values,
1090
+ inputs_embeds,
1091
+ labels,
1092
+ ) = self.prepare_inputs_labels_for_multimodal(
1093
+ input_ids, position_ids, attention_mask, past_key_values, labels, images
1094
+ )
1095
+
1096
+ support_packing = (
1097
+ "seqlens_in_batch" in inspect.signature(self.llm.forward).parameters
1098
+ )
1099
+
1100
+ if self.training and support_packing and not dpo_forward:
1101
+ (
1102
+ _,
1103
+ new_position_ids,
1104
+ new_attention_mask,
1105
+ _,
1106
+ new_inputs_embeds,
1107
+ new_labels,
1108
+ sorted_seqlens_in_batch,
1109
+ ) = self.repack_multimodal_data(
1110
+ input_ids,
1111
+ position_ids,
1112
+ attention_mask,
1113
+ past_key_values,
1114
+ inputs_embeds,
1115
+ labels,
1116
+ )
1117
+ if sorted_seqlens_in_batch is None:
1118
+ sorted_seqlens_in_batch = seqlens_in_batch
1119
+ new_input_ids = None
1120
+ past_key_values = None
1121
+ else:
1122
+ new_attention_mask = attention_mask
1123
+ new_position_ids = position_ids
1124
+ new_inputs_embeds = inputs_embeds
1125
+ new_labels = labels
1126
+ sorted_seqlens_in_batch = attention_mask.sum(-1).int()
1127
+ new_input_ids = input_ids
1128
+
1129
+ if support_packing:
1130
+ outputs = self.llm.forward(
1131
+ input_ids=new_input_ids,
1132
+ attention_mask=new_attention_mask,
1133
+ position_ids=new_position_ids,
1134
+ past_key_values=past_key_values,
1135
+ inputs_embeds=new_inputs_embeds,
1136
+ labels=new_labels,
1137
+ use_cache=use_cache,
1138
+ output_attentions=output_attentions,
1139
+ output_hidden_states=output_hidden_states,
1140
+ return_dict=return_dict,
1141
+ seqlens_in_batch=sorted_seqlens_in_batch,
1142
+ )
1143
+ else:
1144
+ outputs = self.llm.forward(
1145
+ input_ids=new_input_ids,
1146
+ attention_mask=new_attention_mask,
1147
+ position_ids=new_position_ids,
1148
+ past_key_values=past_key_values,
1149
+ inputs_embeds=new_inputs_embeds,
1150
+ labels=new_labels,
1151
+ use_cache=use_cache,
1152
+ output_attentions=output_attentions,
1153
+ output_hidden_states=output_hidden_states,
1154
+ return_dict=return_dict,
1155
+ )
1156
+
1157
+ if dpo_forward:
1158
+ return outputs.logits, new_labels
1159
+ return outputs
1160
+
1161
+ @torch.no_grad()
1162
+ def generate(
1163
+ self,
1164
+ input_ids: Optional[torch.FloatTensor] = None,
1165
+ images: Optional[torch.FloatTensor] = None,
1166
+ attention_mask: Optional[torch.LongTensor] = None,
1167
+ **generation_kwargs,
1168
+ ):
1169
+ if images is not None:
1170
+ (
1171
+ _,
1172
+ _,
1173
+ attention_mask,
1174
+ _,
1175
+ inputs_embeds,
1176
+ _,
1177
+ ) = self.prepare_inputs_labels_for_multimodal(
1178
+ input_ids, None, attention_mask, None, None, images
1179
+ )
1180
+ else:
1181
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1182
+ inputs_embeds = inputs_embeds.to(self.dtype)
1183
+
1184
+ outputs = self.llm.generate(
1185
+ inputs_embeds=inputs_embeds,
1186
+ attention_mask=attention_mask,
1187
+ **generation_kwargs,
1188
+ )
1189
+ return outputs
1190
+
1191
+
1192
+ # AutoConfig.register("llava_llama", LlavaLlamaConfig)
1193
+ # AutoModel.register(LlavaLlamaConfig, LlavaLlamaModel)
llm/config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./llm",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 2560,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 6912,
14
+ "max_position_embeddings": 4096,
15
+ "model_max_length": 4096,
16
+ "model_type": "llama",
17
+ "num_attention_heads": 20,
18
+ "num_hidden_layers": 32,
19
+ "num_key_value_heads": 20,
20
+ "pad_token_id": 0,
21
+ "pretraining_tp": 1,
22
+ "rms_norm_eps": 1e-05,
23
+ "rope_scaling": null,
24
+ "rope_theta": 10000.0,
25
+ "tie_word_embeddings": false,
26
+ "tokenizer_model_max_length": 4096,
27
+ "tokenizer_padding_side": "right",
28
+ "torch_dtype": "bfloat16",
29
+ "transformers_version": "4.36.2",
30
+ "use_cache": true,
31
+ "vocab_size": 32000
32
+ }
llm/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.36.2"
7
+ }
llm/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4eed552fa9ca41f3d6fb14b59a481bf12137a37e964df0ec60f412b3ac2a8637
3
+ size 4974521464
llm/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b63acc16bd9be4e7f900ba7e66ddc82400c3c12d77cd5c2cfa4bc77761c0732d
3
+ size 428632856
llm/model.safetensors.index.json ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5403120640
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00002-of-00002.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
88
+ "model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
90
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
93
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
94
+ "model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
95
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
96
+ "model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
98
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
99
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
100
+ "model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
101
+ "model.layers.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
102
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
103
+ "model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
104
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
105
+ "model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
106
+ "model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
107
+ "model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
108
+ "model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
109
+ "model.layers.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
110
+ "model.layers.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
111
+ "model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
112
+ "model.layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
113
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
114
+ "model.layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
115
+ "model.layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
116
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
117
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
118
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
119
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
120
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
121
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
122
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
123
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
124
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
125
+ "model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
126
+ "model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
127
+ "model.layers.20.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
128
+ "model.layers.20.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
129
+ "model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
130
+ "model.layers.20.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
131
+ "model.layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
132
+ "model.layers.20.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
133
+ "model.layers.20.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
134
+ "model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors",
135
+ "model.layers.21.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
136
+ "model.layers.21.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
137
+ "model.layers.21.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
138
+ "model.layers.21.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
139
+ "model.layers.21.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
140
+ "model.layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
141
+ "model.layers.21.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
142
+ "model.layers.21.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
143
+ "model.layers.22.input_layernorm.weight": "model-00001-of-00002.safetensors",
144
+ "model.layers.22.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
145
+ "model.layers.22.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
146
+ "model.layers.22.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.22.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.22.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.22.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.22.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.22.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.23.input_layernorm.weight": "model-00001-of-00002.safetensors",
153
+ "model.layers.23.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
154
+ "model.layers.23.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
155
+ "model.layers.23.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
156
+ "model.layers.23.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
157
+ "model.layers.23.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
158
+ "model.layers.23.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
159
+ "model.layers.23.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
160
+ "model.layers.23.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
161
+ "model.layers.24.input_layernorm.weight": "model-00001-of-00002.safetensors",
162
+ "model.layers.24.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
163
+ "model.layers.24.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
164
+ "model.layers.24.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
165
+ "model.layers.24.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
166
+ "model.layers.24.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
167
+ "model.layers.24.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
168
+ "model.layers.24.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
169
+ "model.layers.24.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
170
+ "model.layers.25.input_layernorm.weight": "model-00001-of-00002.safetensors",
171
+ "model.layers.25.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
172
+ "model.layers.25.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
173
+ "model.layers.25.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
174
+ "model.layers.25.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
175
+ "model.layers.25.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
176
+ "model.layers.25.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
177
+ "model.layers.25.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
178
+ "model.layers.25.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
179
+ "model.layers.26.input_layernorm.weight": "model-00001-of-00002.safetensors",
180
+ "model.layers.26.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
181
+ "model.layers.26.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
182
+ "model.layers.26.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
183
+ "model.layers.26.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
184
+ "model.layers.26.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
185
+ "model.layers.26.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
186
+ "model.layers.26.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
187
+ "model.layers.26.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
188
+ "model.layers.27.input_layernorm.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.27.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.27.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.27.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.27.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.27.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.27.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.27.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.27.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.28.input_layernorm.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.28.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
199
+ "model.layers.28.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
200
+ "model.layers.28.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
201
+ "model.layers.28.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
202
+ "model.layers.28.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
203
+ "model.layers.28.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
204
+ "model.layers.28.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
205
+ "model.layers.28.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
206
+ "model.layers.29.input_layernorm.weight": "model-00001-of-00002.safetensors",
207
+ "model.layers.29.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
208
+ "model.layers.29.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
209
+ "model.layers.29.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
210
+ "model.layers.29.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
211
+ "model.layers.29.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
212
+ "model.layers.29.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
213
+ "model.layers.29.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
214
+ "model.layers.29.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
215
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
216
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
217
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
218
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
219
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
220
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
221
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
222
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
223
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
224
+ "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
225
+ "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
226
+ "model.layers.30.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
227
+ "model.layers.30.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
228
+ "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
229
+ "model.layers.30.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
230
+ "model.layers.30.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
231
+ "model.layers.30.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
232
+ "model.layers.30.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
233
+ "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
234
+ "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
235
+ "model.layers.31.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
236
+ "model.layers.31.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
237
+ "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
238
+ "model.layers.31.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
239
+ "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
240
+ "model.layers.31.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
241
+ "model.layers.31.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
242
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
243
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
244
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
245
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
246
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
247
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
248
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
249
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
250
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
251
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
252
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
253
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
254
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
255
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
256
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
257
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
258
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
259
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
260
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
261
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
262
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
263
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
264
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
265
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
266
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
267
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
268
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
269
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
270
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
271
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
272
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
273
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
274
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
275
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
276
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
277
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
278
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
279
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
280
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
281
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
282
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
283
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
284
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
285
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
286
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
287
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
288
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
289
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
290
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
291
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
292
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
293
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
294
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
295
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
296
+ "model.norm.weight": "model-00002-of-00002.safetensors"
297
+ }
298
+ }
llm/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "<unk>",
17
+ "unk_token": {
18
+ "content": "<unk>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
llm/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7aedb3582ecda9fa99ee9242c17a9658f6744db083ee6ebdc8fb14857f84d220
3
+ size 499723
llm/tokenizer_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ }
30
+ },
31
+ "bos_token": "<s>",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "</s>",
34
+ "legacy": false,
35
+ "model_max_length": 4096,
36
+ "pad_token": "<unk>",
37
+ "padding_side": "right",
38
+ "sp_model_kwargs": {},
39
+ "spaces_between_special_tokens": false,
40
+ "tokenizer_class": "LlamaTokenizer",
41
+ "unk_token": "<unk>",
42
+ "use_default_system_prompt": false
43
+ }
mm_projector/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./checkpoints/vila-siglip-shearedllama2.7b-r129/mm_projector",
3
+ "architectures": [
4
+ "MultimodalProjector"
5
+ ],
6
+ "mm_projector_type": "mlp_downsample",
7
+ "model_type": "v2l_projector",
8
+ "torch_dtype": "bfloat16",
9
+ "transformers_version": "4.36.2"
10
+ }
mm_projector/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f912f7e3e83a967ef9f927ac2dd5275d3fe1bb62b2208075e4eff877fcf47ba7
3
+ size 36729360
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
utils.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
17
+ import os
18
+ import os.path as osp
19
+
20
+ from huggingface_hub import repo_exists, snapshot_download
21
+ from huggingface_hub.utils import HFValidationError, validate_repo_id
22
+ from transformers import AutoConfig, PretrainedConfig
23
+
24
+
25
+ def get_model_config(config):
26
+ default_keys = ["llm_cfg", "vision_tower_cfg", "mm_projector_cfg"]
27
+
28
+ if hasattr(config, "_name_or_path") and len(config._name_or_path) >= 2:
29
+ root_path = config._name_or_path
30
+ else:
31
+ root_path = config.resume_path
32
+
33
+ # download from huggingface
34
+ if root_path is not None and not osp.exists(root_path):
35
+ try:
36
+ valid_hf_repo = repo_exists(root_path)
37
+ except HFValidationError as e:
38
+ valid_hf_repo = False
39
+ if valid_hf_repo:
40
+ root_path = snapshot_download(root_path)
41
+
42
+ return_list = []
43
+ for key in default_keys:
44
+ cfg = getattr(config, key, None)
45
+ if isinstance(cfg, dict):
46
+ try:
47
+ return_list.append(os.path.join(root_path, key[:-4]))
48
+ except:
49
+ raise ValueError(f"Cannot find resume path in config for {key}!")
50
+ elif isinstance(cfg, PretrainedConfig):
51
+ return_list.append(os.path.join(root_path, key[:-4]))
52
+ elif isinstance(cfg, str):
53
+ return_list.append(cfg)
54
+
55
+ return return_list
56
+
57
+
58
+ def is_mm_model(model_path):
59
+ """
60
+ Check if the model at the given path is a visual language model.
61
+
62
+ Args:
63
+ model_path (str): The path to the model.
64
+
65
+ Returns:
66
+ bool: True if the model is an MM model, False otherwise.
67
+ """
68
+ config = AutoConfig.from_pretrained(model_path)
69
+ architectures = config.architectures
70
+ for architecture in architectures:
71
+ if "llava" in architecture.lower():
72
+ return True
73
+ return False
74
+
75
+
76
+ def auto_upgrade(config):
77
+ cfg = AutoConfig.from_pretrained(config)
78
+ if "llava" in config and "llava" not in cfg.model_type:
79
+ assert cfg.model_type == "llama"
80
+ print(
81
+ "You are using newer LLaVA code base, while the checkpoint of v0 is from older code base."
82
+ )
83
+ print(
84
+ "You must upgrade the checkpoint to the new code base (this can be done automatically)."
85
+ )
86
+ confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]")
87
+ if confirm.lower() in ["y", "yes"]:
88
+ print("Upgrading checkpoint...")
89
+ assert len(cfg.architectures) == 1
90
+ setattr(cfg.__class__, "model_type", "llava")
91
+ cfg.architectures[0] = "LlavaLlamaForCausalLM"
92
+ cfg.save_pretrained(config)
93
+ print("Checkpoint upgraded.")
94
+ else:
95
+ print("Checkpoint upgrade aborted.")
96
+ exit(1)
vision_tower/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./vision_tower",
3
+ "architectures": [
4
+ "SiglipVisionModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "hidden_act": "gelu_pytorch_tanh",
8
+ "hidden_size": 1152,
9
+ "image_size": 384,
10
+ "intermediate_size": 4304,
11
+ "layer_norm_eps": 1e-06,
12
+ "model_type": "siglip_vision_model",
13
+ "num_attention_heads": 16,
14
+ "num_channels": 3,
15
+ "num_hidden_layers": 27,
16
+ "patch_size": 14,
17
+ "torch_dtype": "bfloat16",
18
+ "transformers_version": "4.36.2"
19
+ }
vision_tower/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e3764125ad000414d381fe7eb6b222be9f0f2b4c14a55b22bf68cb29647d526
3
+ size 856506120
vision_tower/preprocessor_config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_convert_rgb": true,
3
+ "do_normalize": true,
4
+ "do_rescale": true,
5
+ "do_resize": true,
6
+ "image_mean": [
7
+ 0.5,
8
+ 0.5,
9
+ 0.5
10
+ ],
11
+ "image_processor_type": "SiglipImageProcessor",
12
+ "image_std": [
13
+ 0.5,
14
+ 0.5,
15
+ 0.5
16
+ ],
17
+ "processor_class": "SiglipProcessor",
18
+ "resample": 3,
19
+ "rescale_factor": 0.00392156862745098,
20
+ "size": {
21
+ "height": 384,
22
+ "width": 384
23
+ }
24
+ }