jadechoghari commited on
Commit
7ddba36
1 Parent(s): ee8b7df

Create builder.py

Browse files
Files changed (1) hide show
  1. builder.py +170 -0
builder.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+
13
+
14
+ import os
15
+ import shutil
16
+ import pdb
17
+
18
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
19
+ import torch
20
+
21
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
22
+ WORKER_HEART_BEAT_INTERVAL = 15
23
+
24
+ LOGDIR = "."
25
+
26
+ # Model Constants
27
+ IGNORE_INDEX = -100
28
+ IMAGE_TOKEN_INDEX = -200
29
+ DEFAULT_IMAGE_TOKEN = "<image>"
30
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
31
+ DEFAULT_IM_START_TOKEN = "<im_start>"
32
+ DEFAULT_IM_END_TOKEN = "<im_end>"
33
+ IMAGE_PLACEHOLDER = "<image-placeholder>"
34
+
35
+ # Added by Ferret
36
+ DEFAULT_REGION_FEA_TOKEN = "<region_fea>"
37
+ VOCAB_IMAGE_W = 1000
38
+ VOCAB_IMAGE_H = 1000
39
+
40
+ # GROUNDING PROMPTS
41
+ GROUNDING_TEMPLATES = [
42
+ '\nProvide the bounding boxes of the mentioned objects.',
43
+ '\nInclude the coordinates for each mentioned object.',
44
+ '\nLocate the objects with their coordinates.',
45
+ '\nAnswer in [x1, y1, x2, y2] format.',
46
+ '\nMention the objects and their locations using the format [x1, y1, x2, y2].',
47
+ '\nDraw boxes around the mentioned objects.',
48
+ '\nUse boxes to show where each thing is.',
49
+ '\nTell me where the objects are with coordinates.',
50
+ '\nList where each object is with boxes.',
51
+ '\nShow me the regions with boxes.'
52
+ ]
53
+ DEFAULT_REGION_FEA_TOKEN = "<region_fea>"
54
+
55
+ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto"):
56
+ kwargs = {"device_map": device_map}
57
+
58
+ if load_8bit:
59
+ kwargs['load_in_8bit'] = True
60
+ elif load_4bit:
61
+ kwargs['load_in_4bit'] = True
62
+ kwargs['quantization_config'] = BitsAndBytesConfig(
63
+ load_in_4bit=True,
64
+ bnb_4bit_compute_dtype=torch.float16,
65
+ bnb_4bit_use_double_quant=True,
66
+ bnb_4bit_quant_type='nf4'
67
+ )
68
+ else:
69
+ kwargs['torch_dtype'] = torch.float16
70
+
71
+ if 'llava' in model_name.lower() or 'ferret' in model_name.lower():
72
+ # Load LLaVA/FERRET model
73
+ if 'lora' in model_name.lower() and model_base is not None:
74
+ lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
75
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
76
+ print('Loading LLaVA/FERRET from base model...')
77
+ model = AutoModelForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
78
+ token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
79
+ if model.lm_head.weight.shape[0] != token_num:
80
+ model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
81
+ model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
82
+
83
+ print('Loading additional LLaVA/FERRET weights...')
84
+ if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
85
+ non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
86
+ else:
87
+ # this is probably from HF Hub
88
+ from huggingface_hub import hf_hub_download
89
+ def load_from_hf(repo_id, filename, subfolder=None):
90
+ cache_file = hf_hub_download(
91
+ repo_id=repo_id,
92
+ filename=filename,
93
+ subfolder=subfolder)
94
+ return torch.load(cache_file, map_location='cpu')
95
+ non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
96
+ non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
97
+ if any(k.startswith('model.model.') for k in non_lora_trainables):
98
+ non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
99
+ model.load_state_dict(non_lora_trainables, strict=False)
100
+
101
+ from peft import PeftModel
102
+ print('Loading LoRA weights...')
103
+ model = PeftModel.from_pretrained(model, model_path)
104
+ print('Merging LoRA weights...')
105
+ model = model.merge_and_unload()
106
+ print('Model is loaded...')
107
+ elif model_base is not None:
108
+ # this may be mm projector only
109
+ print('Loading LLaVA/FERRET from base model...')
110
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
111
+ cfg_pretrained = AutoConfig.from_pretrained(model_path)
112
+ model = AutoModelForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
113
+
114
+ mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
115
+ mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
116
+ model.load_state_dict(mm_projector_weights, strict=False)
117
+ else:
118
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
119
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
120
+ else:
121
+ # Load language model
122
+ if model_base is not None:
123
+ # PEFT model
124
+ from peft import PeftModel
125
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
126
+ model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto")
127
+ print(f"Loading LoRA weights from {model_path}")
128
+ model = PeftModel.from_pretrained(model, model_path)
129
+ print(f"Merging weights")
130
+ model = model.merge_and_unload()
131
+ print('Convert to FP16...')
132
+ model.to(torch.float16)
133
+ else:
134
+ use_fast = False
135
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
136
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
137
+
138
+ image_processor = None
139
+
140
+ if 'llava' in model_name.lower() or 'ferret' in model_name.lower():
141
+ mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
142
+ mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
143
+ mm_im_region_fea_token = getattr(model.config, "im_region_fea_token", None)
144
+ if mm_use_im_patch_token:
145
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
146
+ if mm_im_region_fea_token is not None:
147
+ tokenizer.add_tokens([DEFAULT_REGION_FEA_TOKEN], special_tokens=True)
148
+ if mm_use_im_start_end:
149
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
150
+ model.resize_token_embeddings(len(tokenizer))
151
+
152
+ vision_tower = model.get_vision_tower()
153
+ vision_tower_path = os.path.join(model_path, 'vision_tower')
154
+ if not vision_tower.is_loaded or os.path.exists(vision_tower_path):
155
+ if os.path.exists(vision_tower_path):
156
+ print(f'Start Loading vision tower from {vision_tower_path}')
157
+ vision_tower.load_model(vision_tower_path=vision_tower_path)
158
+ print(f'Finish Loading vision tower from {vision_tower_path}')
159
+ else:
160
+ vision_tower.load_model()
161
+
162
+ vision_tower.to(device='cuda', dtype=torch.float16)
163
+ image_processor = vision_tower.image_processor
164
+
165
+ if hasattr(model.config, "max_sequence_length"):
166
+ context_len = model.config.max_sequence_length
167
+ else:
168
+ context_len = 2048
169
+
170
+ return tokenizer, model, image_processor, context_len