GuoruiSong commited on
Commit
867b992
·
verified ·
1 Parent(s): 07af81f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LLaVA-NeXT/llava/eval/evaluate_interleave.py +339 -0
  2. LLaVA-NeXT/llava/eval/model_vqa.py +240 -0
  3. LLaVA-NeXT/llava/model/language_model/llava_gemma.py +122 -0
  4. LLaVA-NeXT/llava/model/language_model/llava_llama.py +261 -0
  5. LLaVA-NeXT/llava/model/language_model/llava_mistral.py +127 -0
  6. LLaVA-NeXT/llava/model/language_model/llava_mixtral.py +143 -0
  7. LLaVA-NeXT/llava/model/language_model/llava_mpt.py +105 -0
  8. LLaVA-NeXT/llava/model/language_model/llava_qwen.py +149 -0
  9. LLaVA-NeXT/llava/model/language_model/llava_qwen_moe.py +149 -0
  10. LLaVA-NeXT/llava/model/language_model/modeling_llama.py +1649 -0
  11. LLaVA-NeXT/llava/model/multimodal_encoder/builder.py +41 -0
  12. LLaVA-NeXT/llava/model/multimodal_encoder/clip_encoder.py +173 -0
  13. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/__init__.py +9 -0
  14. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/constants.py +2 -0
  15. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/eva_vit_model.py +571 -0
  16. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/factory.py +528 -0
  17. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_configs.py +57 -0
  18. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_model.py +240 -0
  19. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/loss.py +123 -0
  20. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model.py +429 -0
  21. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-18B.json +27 -0
  22. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-8B-plus.json +27 -0
  23. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-8B.json +27 -0
  24. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json +19 -0
  25. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json +24 -0
  26. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-g-14.json +24 -0
  27. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-B-16.json +29 -0
  28. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-L-14-336.json +29 -0
  29. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-L-14.json +29 -0
  30. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json +25 -0
  31. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14.json +25 -0
  32. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14-448.json +25 -0
  33. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14.json +25 -0
  34. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/modified_resnet.py +179 -0
  35. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/openai.py +144 -0
  36. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/pretrained.py +314 -0
  37. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/rope.py +131 -0
  38. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/timm_model.py +114 -0
  39. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/tokenizer.py +205 -0
  40. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transform.py +104 -0
  41. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transformer.py +683 -0
  42. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/utils.py +321 -0
  43. LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_vit.py +141 -0
  44. LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_encoder.py +74 -0
  45. LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_processors.py +72 -0
  46. LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_vit.py +856 -0
  47. LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/factory.py +60 -0
  48. LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-18B.json +27 -0
  49. LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B-plus.json +27 -0
  50. LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B.json +27 -0
LLaVA-NeXT/llava/eval/evaluate_interleave.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from rouge import Rouge
3
+ import argparse
4
+ import os
5
+ import json
6
+ import numpy as np
7
+ from sklearn.feature_extraction.text import TfidfVectorizer
8
+ from sklearn.metrics.pairwise import cosine_similarity
9
+
10
+
11
+ spot_the_diff = ["Spot-the-Diff", "Birds-to-Words", "CLEVR-Change"]
12
+ image_edit_instruct = ["IEdit", "HQ-Edit", "MagicBrush"]
13
+ visual_story_telling = ["AESOP", "FlintstonesSV", "PororoSV", "VIST"]
14
+ visual_cloze = ["COMICS_Dialogue", "RecipeQA_VisualCloze"]
15
+ text_rich_vqa = ["WebQA", "TQA", "OCR-VQA", "DocVQA"]
16
+ multi_image_vqa = ["MIT-States_StateCoherence", "MIT-States_PropertyCoherence", "VISION", "RecipeQA_ImageCoherence"]
17
+
18
+ puzzle = ["RAVEN"]
19
+ nlrv2 = ["NLVR2_Mantis"]
20
+ qbench = ["QBench"]
21
+
22
+ class Eval:
23
+ def __init__(self):
24
+ self.periodStrip = re.compile("(?!<=\d)(\.)(?!\d)")
25
+ self.commaStrip = re.compile("(\d)(\,)(\d)")
26
+ self.punct = [
27
+ ";",
28
+ r"/",
29
+ "[",
30
+ "]",
31
+ '"',
32
+ "{",
33
+ "}",
34
+ "(",
35
+ ")",
36
+ "=",
37
+ "+",
38
+ "\\",
39
+ "_",
40
+ "-",
41
+ ">",
42
+ "<",
43
+ "@",
44
+ "`",
45
+ ",",
46
+ "?",
47
+ "!",
48
+ ]
49
+
50
+ def processPunctuation(self, inText):
51
+ outText = inText
52
+ for p in self.punct:
53
+ if (p + " " in inText or " " + p in inText) or (
54
+ re.search(self.commaStrip, inText) != None
55
+ ):
56
+ outText = outText.replace(p, "")
57
+ else:
58
+ outText = outText.replace(p, " ")
59
+ outText = self.periodStrip.sub("", outText, re.UNICODE)
60
+ return outText
61
+
62
+ def process(self, answer):
63
+ answer = answer.replace("\n", " ")
64
+ answer = answer.replace("\t", " ")
65
+ answer = answer.strip()
66
+ answer = self.processPunctuation(answer)
67
+ answer = answer.strip('\'')
68
+ answer = answer.strip('\"')
69
+ answer = answer.strip(')')
70
+ answer = answer.strip('(')
71
+ answer = answer.strip().lower()
72
+ return answer
73
+
74
+ def evaluate_rouge(self,preds):
75
+ rouge = Rouge()
76
+ acc = {'f': []}
77
+ eval_list = []
78
+ for i, res in enumerate(preds):
79
+ sample_id = res['sample_id']
80
+ # print(sample_id)
81
+ gt_ans = self.process(res["gt_response"])
82
+ pred_ans = self.process(res["pred_response"])
83
+ # assert gt_ans != ''
84
+
85
+ if gt_ans == '':
86
+ continue
87
+
88
+ if pred_ans == '':
89
+ s = 0
90
+ else:
91
+ if len(pred_ans) > 512:
92
+ pred_ans = pred_ans[0: 512]
93
+ s = rouge.get_scores(pred_ans, gt_ans)[0]['rouge-l']['f']
94
+ acc['f'].append(s)
95
+ eval_list.append({'id':str(sample_id),'score':str(round(s,3))})
96
+ results = {'Rouge-L f': np.mean(acc['f'])}
97
+ return results,eval_list
98
+
99
+
100
+ def judge_multi_choice(self,sample):
101
+ sample_id = sample['sample_id']
102
+ gt_ans = sample["gt_response"]
103
+ pred_ans = sample["pred_response"]
104
+
105
+ if ":" in pred_ans:
106
+ a_list = pred_ans.split(":")
107
+ a_list = [a.strip() for a in a_list ]
108
+ for a in a_list:
109
+ if len(a) == 1 and a[-1] in ["a", "b", "c", "d", "e", "f", "g", "h"]:
110
+ pred_ans = a
111
+
112
+ if pred_ans == gt_ans:
113
+ return 1
114
+ else:
115
+ return 0
116
+
117
+ def process_sample(self,sample):
118
+ sample["gt_response"] = self.process(sample["gt_response"])
119
+ sample["pred_response"] = self.process(sample["pred_response"])
120
+
121
+ def evaluate_multichoice(self, preditions):
122
+ correct = 0
123
+ eval_list = []
124
+ for i, sample in enumerate(preditions):
125
+ self.process_sample(sample)
126
+ score = self.judge_multi_choice(sample)
127
+ sample_id = sample['sample_id']
128
+ sample['result'] = score
129
+ eval_list.append({'id':str(sample_id),'score':str(score)})
130
+ correct+=score
131
+ return {'Accuracy':correct/len(preditions)},eval_list
132
+
133
+ def evaluate_multi_choice_image(self,preditions):
134
+ correct = 0
135
+ eval_list = []
136
+ for i,sample in enumerate(preditions):
137
+ gt_ans = self.process(sample["gt_response"])
138
+ pred_ans = self.process(sample["pred_response"])
139
+ sample_id = sample['sample_id']
140
+
141
+ if ":" in pred_ans:
142
+ a_list = pred_ans.split(":")
143
+ a_list = [a.strip() for a in a_list ]
144
+ for a in a_list:
145
+ if len(a) == 1 and a[-1] in ["a", "b", "c", "d", "e", "f", "g", "h"]:
146
+ pred_ans = a
147
+
148
+ if gt_ans == pred_ans:
149
+ score = 1
150
+ else:
151
+ score = 0
152
+ sample_id = sample['sample_id']
153
+ sample['result'] = score
154
+ eval_list.append({'id':str(sample_id),'score':str(score)})
155
+ correct+=score
156
+ return {'Accuracy':correct/len(preditions)},eval_list
157
+
158
+
159
+ if __name__ == "__main__":
160
+ parser = argparse.ArgumentParser()
161
+ parser.add_argument('--result-dir', type=str, required=True)
162
+
163
+ args = parser.parse_args()
164
+
165
+ result_file = os.path.join(args.result_dir, "result.jsonl")
166
+
167
+ if not os.path.exists(result_file):
168
+ print('No prediction file found')
169
+ exit(0)
170
+ with open(result_file, 'r') as f:
171
+ preds_all = [json.loads(line) for line in f]
172
+
173
+ preds_all_dict = dict()
174
+ for pred in preds_all:
175
+ if pred["dataset"] not in preds_all_dict:
176
+ preds_all_dict[pred["dataset"]] = list()
177
+ preds_all_dict[pred["dataset"]].append(pred)
178
+
179
+ image_choice_dataset_list = ["recipeqa-RecipeQA_VisualCloze", "RecipeQA_ImageCoherence", "COMICS_Panel"]
180
+ E = Eval()
181
+
182
+ eval_result_list = dict()
183
+ eval_result_list_detail = dict()
184
+
185
+ for dataset in preds_all_dict:
186
+
187
+ preds = preds_all_dict[dataset]
188
+ question_type = preds[0]["question_type"]
189
+
190
+ if question_type == 'open-ended':
191
+ eval_result, eval_list = E.evaluate_rouge(preds)
192
+
193
+ elif question_type == 'multi-choice' or dataset == 'nlrv2':
194
+ if dataset in image_choice_dataset_list:
195
+ eval_result, eval_list = E.evaluate_multi_choice_image(preds)
196
+ else:
197
+ eval_result, eval_list = E.evaluate_multichoice(preds)
198
+
199
+ else:
200
+ eval_result = 'Dataset not supported'
201
+ print('Dataset not supported')
202
+ exit(0)
203
+
204
+ print(dataset, end = ': ')
205
+ print(eval_result)
206
+
207
+ eval_result_list[dataset] = eval_result
208
+ eval_result_list_detail[dataset] = eval_list
209
+
210
+ os.makedirs(args.result_dir, exist_ok=True)
211
+ with open(os.path.join(args.result_dir, 'eval_dataset.json'), 'w') as f:
212
+ json.dump(eval_result_list, f, indent=4)
213
+
214
+ with open(os.path.join(args.result_dir,'eval_dataset_details.json'), 'w') as f:
215
+ json.dump(eval_result_list_detail, f, indent=4)
216
+
217
+
218
+ eval_cat_list = dict()
219
+ print()
220
+
221
+ # spot_the_diff
222
+ score = 0
223
+ count = 0
224
+ for dataset in eval_result_list:
225
+ if dataset in spot_the_diff:
226
+ count += 1
227
+ score += list(eval_result_list[dataset].values())[0]
228
+ if count > 0:
229
+ score /= count
230
+ eval_cat_list["spot_the_diff"] = score
231
+ print("spot_the_diff", end = ': ')
232
+ print('{:.2f}'.format(100 * score))
233
+
234
+ # image_edit_instruct
235
+ score = 0
236
+ count = 0
237
+ for dataset in eval_result_list:
238
+ if dataset in image_edit_instruct:
239
+ count += 1
240
+ score += list(eval_result_list[dataset].values())[0]
241
+ if count > 0:
242
+ score /= count
243
+ eval_cat_list["image_edit_instruct"] = score
244
+ print("image_edit_instruct", end = ': ')
245
+ print('{:.2f}'.format(100 * score))
246
+
247
+ # visual_story_telling
248
+ score = 0
249
+ count = 0
250
+ for dataset in eval_result_list:
251
+ if dataset in visual_story_telling:
252
+ count += 1
253
+ score += list(eval_result_list[dataset].values())[0]
254
+ if count > 0:
255
+ score /= count
256
+ eval_cat_list["visual_story_telling"] = score
257
+ print("visual_story_telling", end = ': ')
258
+ print('{:.2f}'.format(100 * score))
259
+
260
+ # visual_cloze
261
+ score = 0
262
+ count = 0
263
+ for dataset in eval_result_list:
264
+ if dataset in visual_cloze:
265
+ count += 1
266
+ score += list(eval_result_list[dataset].values())[0]
267
+ if count > 0:
268
+ score /= count
269
+ eval_cat_list["visual_cloze"] = score
270
+ print("visual_cloze", end = ': ')
271
+ print('{:.2f}'.format(100 * score))
272
+
273
+ # text_rich_vqa
274
+ score = 0
275
+ count = 0
276
+ for dataset in eval_result_list:
277
+ if dataset in text_rich_vqa:
278
+ count += 1
279
+ score += list(eval_result_list[dataset].values())[0]
280
+ if count > 0:
281
+ score /= count
282
+ eval_cat_list["text_rich_vqa"] = score
283
+ print("text_rich_vqa", end = ': ')
284
+ print('{:.2f}'.format(100 * score))
285
+
286
+ # multi_image_vqa
287
+ score = 0
288
+ count = 0
289
+ for dataset in eval_result_list:
290
+ if dataset in multi_image_vqa:
291
+ count += 1
292
+ score += list(eval_result_list[dataset].values())[0]
293
+ if count > 0:
294
+ score /= count
295
+ eval_cat_list["multi_image_vqa"] = score
296
+ print("multi_image_vqa", end = ': ')
297
+ print('{:.2f}'.format(100 * score))
298
+
299
+ # puzzle
300
+ score = 0
301
+ count = 0
302
+ for dataset in eval_result_list:
303
+ if dataset in puzzle:
304
+ count += 1
305
+ score += list(eval_result_list[dataset].values())[0]
306
+ if count > 0:
307
+ score /= count
308
+ eval_cat_list["puzzle"] = score
309
+ print("puzzle", end = ': ')
310
+ print('{:.2f}'.format(100 * score))
311
+
312
+ # nlrv2
313
+ score = 0
314
+ count = 0
315
+ for dataset in eval_result_list:
316
+ if dataset in nlrv2:
317
+ count += 1
318
+ score += list(eval_result_list[dataset].values())[0]
319
+ if count > 0:
320
+ score /= count
321
+ eval_cat_list["nlrv2"] = score
322
+ print("nlrv2", end = ': ')
323
+ print('{:.2f}'.format(100 * score))
324
+
325
+ # qbench
326
+ score = 0
327
+ count = 0
328
+ for dataset in eval_result_list:
329
+ if dataset in qbench:
330
+ count += 1
331
+ score += list(eval_result_list[dataset].values())[0]
332
+ if count > 0:
333
+ score /= count
334
+ eval_cat_list["qbench"] = score
335
+ print("qbench", end = ': ')
336
+ print('{:.2f}'.format(100 * score))
337
+
338
+ with open(os.path.join(args.result_dir,'eval_cat.json'), 'w') as f:
339
+ json.dump(eval_cat_list, f, indent=4)
LLaVA-NeXT/llava/eval/model_vqa.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ import os
4
+ import json
5
+ from tqdm import tqdm
6
+ import shortuuid
7
+
8
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
9
+ from llava.conversation import conv_templates, SeparatorStyle
10
+ from llava.model.builder import load_pretrained_model
11
+ from llava.utils import disable_torch_init
12
+ from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
13
+
14
+ from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_TOKEN_INDEX
15
+ from typing import Dict, Optional, Sequence, List
16
+ import transformers
17
+ import re
18
+
19
+ from PIL import Image
20
+ import math
21
+
22
+
23
+ def split_list(lst, n):
24
+ """Split a list into n (roughly) equal-sized chunks"""
25
+ chunk_size = math.ceil(len(lst) / n) # integer division
26
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
27
+
28
+
29
+ def get_chunk(lst, n, k):
30
+ chunks = split_list(lst, n)
31
+ return chunks[k]
32
+
33
+ def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful assistant.") -> Dict:
34
+ roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"}
35
+
36
+ im_start, im_end = tokenizer.additional_special_tokens_ids
37
+ nl_tokens = tokenizer("\n").input_ids
38
+ _system = tokenizer("system").input_ids + nl_tokens
39
+ _user = tokenizer("user").input_ids + nl_tokens
40
+ _assistant = tokenizer("assistant").input_ids + nl_tokens
41
+
42
+ # Apply prompt templates
43
+ input_ids, targets = [], []
44
+
45
+ source = sources
46
+ if roles[source[0]["from"]] != roles["human"]:
47
+ source = source[1:]
48
+
49
+ input_id, target = [], []
50
+ system = [im_start] + _system + tokenizer(system_message).input_ids + [im_end] + nl_tokens
51
+ input_id += system
52
+ target += [im_start] + [IGNORE_INDEX] * (len(system) - 3) + [im_end] + nl_tokens
53
+ assert len(input_id) == len(target)
54
+ for j, sentence in enumerate(source):
55
+ role = roles[sentence["from"]]
56
+ if has_image and sentence["value"] is not None and "<image>" in sentence["value"]:
57
+ num_image = len(re.findall(DEFAULT_IMAGE_TOKEN, sentence["value"]))
58
+ texts = sentence["value"].split('<image>')
59
+ _input_id = tokenizer(role).input_ids + nl_tokens
60
+ for i,text in enumerate(texts):
61
+ _input_id += tokenizer(text).input_ids
62
+ if i<len(texts)-1:
63
+ _input_id += [IMAGE_TOKEN_INDEX] + nl_tokens
64
+ _input_id += [im_end] + nl_tokens
65
+ assert sum([i==IMAGE_TOKEN_INDEX for i in _input_id])==num_image
66
+ else:
67
+ if sentence["value"] is None:
68
+ _input_id = tokenizer(role).input_ids + nl_tokens
69
+ else:
70
+ _input_id = tokenizer(role).input_ids + nl_tokens + tokenizer(sentence["value"]).input_ids + [im_end] + nl_tokens
71
+ input_id += _input_id
72
+ if role == "<|im_start|>user":
73
+ _target = [im_start] + [IGNORE_INDEX] * (len(_input_id) - 3) + [im_end] + nl_tokens
74
+ elif role == "<|im_start|>assistant":
75
+ _target = [im_start] + [IGNORE_INDEX] * len(tokenizer(role).input_ids) + _input_id[len(tokenizer(role).input_ids) + 1 : -2] + [im_end] + nl_tokens
76
+ else:
77
+ raise NotImplementedError
78
+ target += _target
79
+
80
+ input_ids.append(input_id)
81
+ targets.append(target)
82
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
83
+ targets = torch.tensor(targets, dtype=torch.long)
84
+ return input_ids
85
+
86
+ def eval_model(args):
87
+
88
+ # Model
89
+ disable_torch_init()
90
+ model_path = os.path.expanduser(args.model_path)
91
+ model_name = get_model_name_from_path(model_path)
92
+ tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
93
+
94
+ # Data
95
+ with open(os.path.expanduser(args.question_file)) as f:
96
+ questions = json.load(f)
97
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
98
+ answers_file = os.path.expanduser(args.answers_file)
99
+ os.makedirs(os.path.dirname(answers_file), exist_ok=True)
100
+ ans_file = open(answers_file, "w")
101
+
102
+ for line in tqdm(questions):
103
+ idx = line["sample_id"]
104
+ question_type = line["metadata"]["question_type"]
105
+ dataset_name = line["metadata"]["dataset"]
106
+ gt = line["conversations"][1]["value"]
107
+
108
+ image_files = line["image"]
109
+ qs = line["conversations"][0]["value"]
110
+ cur_prompt = args.extra_prompt + qs
111
+
112
+ args.conv_mode = "qwen_1_5"
113
+
114
+ conv = conv_templates[args.conv_mode].copy()
115
+ conv.append_message(conv.roles[0], qs)
116
+ conv.append_message(conv.roles[1], None)
117
+ prompt = conv.get_prompt()
118
+
119
+ input_ids = preprocess_qwen([line["conversations"][0],{'from': 'gpt','value': None}], tokenizer, has_image=True).cuda()
120
+ img_num = list(input_ids.squeeze()).count(IMAGE_TOKEN_INDEX)
121
+
122
+ image_tensors = []
123
+ for image_file in image_files:
124
+ image = Image.open(os.path.join(args.image_folder, image_file))
125
+ image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values']
126
+ image_tensors.append(image_tensor.half().cuda())
127
+ # image_tensors = torch.cat(image_tensors, dim=0)
128
+
129
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
130
+ keywords = [stop_str]
131
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
132
+
133
+ with torch.inference_mode():
134
+ output_ids = model.generate(
135
+ input_ids,
136
+ images=image_tensors,
137
+ do_sample=True if args.temperature > 0 else False,
138
+ temperature=args.temperature,
139
+ top_p=args.top_p,
140
+ num_beams=args.num_beams,
141
+ # no_repeat_ngram_size=3,
142
+ max_new_tokens=1024,
143
+ use_cache=True)
144
+
145
+
146
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
147
+ outputs = outputs.strip()
148
+ if outputs.endswith(stop_str):
149
+ outputs = outputs[:-len(stop_str)]
150
+ outputs = outputs.strip()
151
+
152
+ ans_id = shortuuid.uuid()
153
+ ans_file.write(json.dumps({
154
+ "dataset": dataset_name,
155
+ "sample_id": idx,
156
+ "prompt": cur_prompt,
157
+ "pred_response": outputs,
158
+ "gt_response": gt,
159
+ "shortuuid": ans_id,
160
+ "model_id": model_name,
161
+ "question_type": question_type,
162
+ }) + "\n")
163
+ ans_file.flush()
164
+
165
+ if len(line["conversations"]) > 2:
166
+
167
+ for i in range(2, len(line["conversations"]), 2):
168
+ input_ids = torch.cat((input_ids, output_ids), dim=1)
169
+
170
+ gt = line["conversations"][i + 1]["value"]
171
+ qs = line["conversations"][i]["value"]
172
+ cur_prompt = args.extra_prompt + qs
173
+
174
+ args.conv_mode = "qwen_1_5"
175
+
176
+ conv = conv_templates[args.conv_mode].copy()
177
+ conv.append_message(conv.roles[0], qs)
178
+ conv.append_message(conv.roles[1], None)
179
+ prompt = conv.get_prompt()
180
+
181
+ input_ids_new = preprocess_qwen([line["conversations"][i],{'from': 'gpt','value': None}], tokenizer, has_image=True).cuda()
182
+ input_ids = torch.cat((input_ids, input_ids_new), dim=1)
183
+ img_num = list(input_ids_new.squeeze()).count(IMAGE_TOKEN_INDEX)
184
+
185
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
186
+ keywords = [stop_str]
187
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
188
+
189
+ with torch.inference_mode():
190
+ output_ids = model.generate(
191
+ input_ids,
192
+ images=image_tensors,
193
+ do_sample=True if args.temperature > 0 else False,
194
+ temperature=args.temperature,
195
+ top_p=args.top_p,
196
+ num_beams=args.num_beams,
197
+ # no_repeat_ngram_size=3,
198
+ max_new_tokens=1024,
199
+ use_cache=True)
200
+
201
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
202
+ outputs = outputs.strip()
203
+ if outputs.endswith(stop_str):
204
+ outputs = outputs[:-len(stop_str)]
205
+ outputs = outputs.strip()
206
+
207
+ ans_id = shortuuid.uuid()
208
+ ans_file.write(json.dumps({
209
+ "dataset": dataset_name,
210
+ "sample_id": idx,
211
+ "prompt": cur_prompt,
212
+ "pred_response": outputs,
213
+ "gt_response": gt,
214
+ "shortuuid": ans_id,
215
+ "model_id": model_name,
216
+ "question_type": question_type,
217
+ }) + "\n")
218
+ ans_file.flush()
219
+
220
+
221
+ ans_file.close()
222
+
223
+ if __name__ == "__main__":
224
+ parser = argparse.ArgumentParser()
225
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
226
+ parser.add_argument("--model-base", type=str, default=None)
227
+ parser.add_argument("--image-folder", type=str, default="")
228
+ parser.add_argument("--extra-prompt", type=str, default="")
229
+ parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
230
+ parser.add_argument("--answers-file", type=str, default="answer.jsonl")
231
+ parser.add_argument("--conv-mode", type=str, default="llava_v1")
232
+ parser.add_argument("--num-chunks", type=int, default=1)
233
+ parser.add_argument("--chunk-idx", type=int, default=0)
234
+ parser.add_argument("--temperature", type=float, default=0.2)
235
+ parser.add_argument("--top_p", type=float, default=None)
236
+ parser.add_argument("--num_beams", type=int, default=1)
237
+ parser.add_argument("--test_size", type=int, default=10000000)
238
+ args = parser.parse_args()
239
+
240
+ eval_model(args)
LLaVA-NeXT/llava/model/language_model/llava_gemma.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Duc Q. Nguyen, Haotian Liu and Bo Li
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
+
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from torch.nn import CrossEntropyLoss
21
+
22
+ from transformers import AutoConfig, AutoModelForCausalLM, GemmaConfig, GemmaModel, GemmaForCausalLM
23
+
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.generation.utils import GenerateOutput
26
+
27
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
28
+
29
+
30
+ class LlavaGemmaConfig(GemmaConfig):
31
+ model_type = "llava_gemma"
32
+
33
+
34
+ class LlavaGemmaModel(LlavaMetaModel, GemmaModel):
35
+ config_class = LlavaGemmaConfig
36
+
37
+ def __init__(self, config: GemmaConfig):
38
+ super(LlavaGemmaModel, self).__init__(config)
39
+
40
+
41
+ class LlavaGemmaForCausalLM(GemmaForCausalLM, LlavaMetaForCausalLM):
42
+ config_class = LlavaGemmaConfig
43
+
44
+ def __init__(self, config):
45
+ super(GemmaForCausalLM, self).__init__(config)
46
+ self.model = LlavaGemmaModel(config)
47
+
48
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
49
+
50
+ # Initialize weights and apply final processing
51
+ self.post_init()
52
+
53
+ def get_model(self):
54
+ return self.model
55
+
56
+ def forward(
57
+ self,
58
+ input_ids: torch.LongTensor = None,
59
+ attention_mask: Optional[torch.Tensor] = None,
60
+ position_ids: Optional[torch.LongTensor] = None,
61
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
62
+ inputs_embeds: Optional[torch.FloatTensor] = None,
63
+ labels: Optional[torch.LongTensor] = None,
64
+ use_cache: Optional[bool] = None,
65
+ output_attentions: Optional[bool] = None,
66
+ output_hidden_states: Optional[bool] = None,
67
+ images: Optional[torch.FloatTensor] = None,
68
+ image_sizes: Optional[List[List[int]]] = None,
69
+ return_dict: Optional[bool] = None,
70
+ cache_position: Optional[torch.LongTensor] = None,
71
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
72
+
73
+ if inputs_embeds is None:
74
+ (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, image_sizes)
75
+
76
+ return super().forward(
77
+ input_ids=input_ids,
78
+ attention_mask=attention_mask,
79
+ position_ids=position_ids,
80
+ past_key_values=past_key_values,
81
+ inputs_embeds=inputs_embeds,
82
+ labels=labels,
83
+ use_cache=use_cache,
84
+ output_attentions=output_attentions,
85
+ output_hidden_states=output_hidden_states,
86
+ return_dict=return_dict,
87
+ cache_position=cache_position,
88
+ )
89
+
90
+ @torch.no_grad()
91
+ def generate(
92
+ self,
93
+ inputs: Optional[torch.Tensor] = None,
94
+ images: Optional[torch.Tensor] = None,
95
+ image_sizes: Optional[torch.Tensor] = None,
96
+ **kwargs,
97
+ ) -> Union[GenerateOutput, torch.LongTensor]:
98
+ position_ids = kwargs.pop("position_ids", None)
99
+ attention_mask = kwargs.pop("attention_mask", None)
100
+ if "inputs_embeds" in kwargs:
101
+ raise NotImplementedError("`inputs_embeds` is not supported")
102
+
103
+ if images is not None:
104
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, image_sizes=image_sizes)
105
+ else:
106
+ inputs_embeds = self.get_model().embed_tokens(inputs)
107
+
108
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
109
+
110
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
111
+ images = kwargs.pop("images", None)
112
+ image_sizes = kwargs.pop("image_sizes", None)
113
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
114
+ if images is not None:
115
+ inputs["images"] = images
116
+ if image_sizes is not None:
117
+ inputs["image_sizes"] = image_sizes
118
+ return inputs
119
+
120
+
121
+ AutoConfig.register("llava_gemma", LlavaGemmaConfig)
122
+ AutoModelForCausalLM.register(LlavaGemmaConfig, LlavaGemmaForCausalLM)
LLaVA-NeXT/llava/model/language_model/llava_llama.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig
23
+
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+
27
+ # , LlamaModel, LlamaForCausalLM, GenerationConfig
28
+ # from .modeling_llama import LlamaModel, LlamaForCausalLM
29
+ from transformers import LlamaModel, LlamaForCausalLM
30
+ from transformers.modeling_outputs import CausalLMOutputWithPast
31
+ from transformers.generation.utils import GenerateOutput
32
+
33
+ from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
34
+
35
+
36
+ class LlavaConfig(LlamaConfig):
37
+ model_type = "llava_llama"
38
+ temperature: float = 0.0 # reset to 0.0, previously 0.9 for Vicuna
39
+ max_new_tokens: int = 1024
40
+ do_sample: bool = False
41
+ top_p: Optional[float] = None
42
+ # rope_scaling: Optional[dict] = {}
43
+
44
+
45
+ class LlavaLlamaModel(LlavaMetaModel, LlamaModel):
46
+ config_class = LlavaConfig
47
+
48
+ def __init__(self, config: LlamaConfig):
49
+ super(LlavaLlamaModel, self).__init__(config)
50
+
51
+
52
+ class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
53
+ config_class = LlavaConfig
54
+
55
+ def __init__(self, config):
56
+ LlamaForCausalLM.__init__(self, config)
57
+
58
+ # configure default generation settings
59
+ config.model_type = "llava_llama"
60
+ # config.rope_scaling = None
61
+
62
+ self.model = LlavaLlamaModel(config)
63
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
64
+ # Initialize weights and apply final processing
65
+ self.post_init()
66
+
67
+ def get_model(self):
68
+ return self.model
69
+
70
+ def forward(
71
+ self,
72
+ input_ids: torch.LongTensor = None,
73
+ attention_mask: Optional[torch.Tensor] = None,
74
+ position_ids: Optional[torch.LongTensor] = None,
75
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
76
+ inputs_embeds: Optional[torch.FloatTensor] = None,
77
+ labels: Optional[torch.LongTensor] = None,
78
+ use_cache: Optional[bool] = None,
79
+ output_attentions: Optional[bool] = None,
80
+ output_hidden_states: Optional[bool] = None,
81
+ images: Optional[torch.FloatTensor] = None,
82
+ image_sizes: Optional[List[List[int]]] = None,
83
+ return_dict: Optional[bool] = None,
84
+ modalities: Optional[List[str]] = ["image"],
85
+ dpo_forward: Optional[bool] = None,
86
+ cache_position=None,
87
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
88
+
89
+ if inputs_embeds is None:
90
+ (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes)
91
+
92
+ if dpo_forward:
93
+ outputs = self.model(
94
+ input_ids=input_ids,
95
+ attention_mask=attention_mask,
96
+ position_ids=position_ids,
97
+ past_key_values=past_key_values,
98
+ inputs_embeds=inputs_embeds,
99
+ use_cache=use_cache,
100
+ output_attentions=output_attentions,
101
+ output_hidden_states=output_hidden_states,
102
+ return_dict=return_dict,
103
+ )
104
+
105
+ hidden_states = outputs[0]
106
+ logits = self.lm_head(hidden_states)
107
+ return logits, labels
108
+
109
+ else:
110
+ return super().forward(
111
+ input_ids=input_ids,
112
+ attention_mask=attention_mask,
113
+ position_ids=position_ids,
114
+ past_key_values=past_key_values,
115
+ inputs_embeds=inputs_embeds,
116
+ labels=labels,
117
+ use_cache=use_cache,
118
+ output_attentions=output_attentions,
119
+ output_hidden_states=output_hidden_states,
120
+ return_dict=return_dict,
121
+ )
122
+
123
+ @torch.no_grad()
124
+ def _generate_with_cd(
125
+ self,
126
+ raw_inputs: torch.Tensor,
127
+ inputs_embeds: torch.Tensor,
128
+ inputs_embeds_cd: torch.Tensor,
129
+ attention_mask: Optional[torch.Tensor] = None,
130
+ cd_alpha: float = 1.0,
131
+ cd_beta: Optional[float] = None,
132
+ max_new_tokens: int = 12,
133
+ eos_token_id: Optional[Union[int, List[int]]] = None,
134
+ stopping_criteria=None,
135
+ ) -> torch.LongTensor:
136
+ if raw_inputs is None or raw_inputs.size(0) != 1:
137
+ raise ValueError("TVCD generation currently supports batch size 1 with text inputs.")
138
+
139
+ model = self.get_model()
140
+ device = inputs_embeds.device
141
+ generated = []
142
+ text_ids = raw_inputs.clone().to(device)
143
+ attn_orig = attention_mask.clone() if attention_mask is not None else None
144
+ attn_cd = attention_mask.clone() if attention_mask is not None else None
145
+
146
+ outputs_orig = model(inputs_embeds=inputs_embeds, attention_mask=attn_orig, use_cache=True, return_dict=True)
147
+ outputs_cd = model(inputs_embeds=inputs_embeds_cd, attention_mask=attn_cd, use_cache=True, return_dict=True)
148
+ past_orig = outputs_orig.past_key_values
149
+ past_cd = outputs_cd.past_key_values
150
+
151
+ if eos_token_id is None:
152
+ eos_token_ids = []
153
+ elif isinstance(eos_token_id, int):
154
+ eos_token_ids = [eos_token_id]
155
+ else:
156
+ eos_token_ids = list(eos_token_id)
157
+
158
+ stop_list = list(stopping_criteria) if stopping_criteria is not None else []
159
+
160
+ for _ in range(max_new_tokens):
161
+ logits_orig = self.lm_head(outputs_orig[0][:, -1, :]).float()
162
+ logits_cd = self.lm_head(outputs_cd[0][:, -1, :]).float()
163
+ logits = (1.0 + cd_alpha) * logits_orig - cd_alpha * logits_cd
164
+
165
+ if cd_beta is not None and 0.0 < cd_beta < 1.0:
166
+ cutoff = logits_orig.max(dim=-1, keepdim=True).values + torch.log(torch.tensor(cd_beta, device=logits.device))
167
+ logits = logits.masked_fill(logits_orig < cutoff, -float("inf"))
168
+
169
+ next_token = torch.argmax(logits, dim=-1, keepdim=True)
170
+ generated.append(next_token)
171
+ text_ids = torch.cat([text_ids, next_token], dim=1)
172
+
173
+ stop_now = False
174
+ if eos_token_ids and next_token.item() in eos_token_ids:
175
+ stop_now = True
176
+ if not stop_now and stop_list:
177
+ scores = logits.unsqueeze(1)
178
+ for criteria in stop_list:
179
+ if criteria(text_ids, scores):
180
+ stop_now = True
181
+ break
182
+ if stop_now:
183
+ break
184
+
185
+ if attn_orig is not None:
186
+ attn_orig = torch.cat([attn_orig, torch.ones((attn_orig.size(0), 1), dtype=attn_orig.dtype, device=attn_orig.device)], dim=1)
187
+ attn_cd = torch.cat([attn_cd, torch.ones((attn_cd.size(0), 1), dtype=attn_cd.dtype, device=attn_cd.device)], dim=1)
188
+
189
+ outputs_orig = model(input_ids=next_token, attention_mask=attn_orig, past_key_values=past_orig, use_cache=True, return_dict=True)
190
+ outputs_cd = model(input_ids=next_token, attention_mask=attn_cd, past_key_values=past_cd, use_cache=True, return_dict=True)
191
+ past_orig = outputs_orig.past_key_values
192
+ past_cd = outputs_cd.past_key_values
193
+
194
+ if not generated:
195
+ return text_ids[:, :0]
196
+ return torch.cat(generated, dim=1)
197
+
198
+ @torch.no_grad()
199
+ def generate(
200
+ self,
201
+ inputs: Optional[torch.Tensor] = None,
202
+ images: Optional[torch.Tensor] = None,
203
+ images_cd: Optional[torch.Tensor] = None,
204
+ image_sizes: Optional[torch.Tensor] = None,
205
+ image_sizes_cd: Optional[torch.Tensor] = None,
206
+ modalities: Optional[List[str]] = ["image"],
207
+ **kwargs,
208
+ ) -> Union[GenerateOutput, torch.LongTensor]:
209
+ modalities = kwargs.pop("modalities", None) if "modalities" in kwargs and modalities is None else modalities
210
+ position_ids = kwargs.pop("position_ids", None)
211
+ attention_mask = kwargs.pop("attention_mask", None)
212
+ cd_alpha = kwargs.pop("cd_alpha", 1.0)
213
+ cd_beta = kwargs.pop("cd_beta", None)
214
+ raw_inputs = inputs
215
+ raw_attention_mask = attention_mask
216
+ raw_position_ids = position_ids
217
+ if "inputs_embeds" in kwargs:
218
+ raise NotImplementedError("`inputs_embeds` is not supported")
219
+
220
+ inputs_embeds_cd = None
221
+ if images is not None:
222
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
223
+ if images_cd is not None:
224
+ if image_sizes_cd is None:
225
+ image_sizes_cd = image_sizes
226
+ (_, _, _, _, inputs_embeds_cd, _) = self.prepare_inputs_labels_for_multimodal(
227
+ raw_inputs, raw_position_ids, raw_attention_mask,
228
+ None, None, images_cd, modalities, image_sizes=image_sizes_cd
229
+ )
230
+ else:
231
+ inputs_embeds = self.get_model().embed_tokens(inputs)
232
+ if images_cd is not None:
233
+ raise ValueError("`images_cd` requires `images` to be provided as well.")
234
+
235
+ if inputs_embeds_cd is not None:
236
+ return self._generate_with_cd(
237
+ raw_inputs=raw_inputs,
238
+ inputs_embeds=inputs_embeds,
239
+ inputs_embeds_cd=inputs_embeds_cd,
240
+ attention_mask=attention_mask,
241
+ cd_alpha=cd_alpha,
242
+ cd_beta=cd_beta,
243
+ max_new_tokens=kwargs.get("max_new_tokens", self.generation_config.max_new_tokens),
244
+ eos_token_id=kwargs.get("eos_token_id", self.generation_config.eos_token_id),
245
+ stopping_criteria=kwargs.get("stopping_criteria"),
246
+ )
247
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
248
+
249
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
250
+ images = kwargs.pop("images", None)
251
+ image_sizes = kwargs.pop("image_sizes", None)
252
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
253
+ if images is not None:
254
+ inputs["images"] = images
255
+ if image_sizes is not None:
256
+ inputs["image_sizes"] = image_sizes
257
+ return inputs
258
+
259
+
260
+ AutoConfig.register("llava_llama", LlavaConfig)
261
+ AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM)
LLaVA-NeXT/llava/model/language_model/llava_mistral.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from torch.nn import CrossEntropyLoss
21
+
22
+ from transformers import AutoConfig, AutoModelForCausalLM, MistralConfig, MistralModel, MistralForCausalLM, GenerationConfig
23
+
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.generation.utils import GenerateOutput
26
+
27
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
28
+
29
+
30
+ class LlavaMistralConfig(MistralConfig):
31
+ model_type = "llava_mistral"
32
+ temperature: float = 0.0 # reset to 0.0, previously 0.9 for Vicuna
33
+ max_new_tokens: int = 1024
34
+ do_sample: bool = False
35
+ top_p: Optional[float] = None
36
+
37
+
38
+ class LlavaMistralModel(LlavaMetaModel, MistralModel):
39
+ config_class = LlavaMistralConfig
40
+
41
+ def __init__(self, config: MistralConfig):
42
+ super(LlavaMistralModel, self).__init__(config)
43
+
44
+
45
+ class LlavaMistralForCausalLM(MistralForCausalLM, LlavaMetaForCausalLM):
46
+ config_class = LlavaMistralConfig
47
+
48
+ def __init__(self, config):
49
+ super(MistralForCausalLM, self).__init__(config)
50
+
51
+ config.model_type = "llava_mistral"
52
+ config.rope_scaling = None
53
+
54
+ self.model = LlavaMistralModel(config)
55
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
56
+ # Initialize weights and apply final processing
57
+ self.post_init()
58
+
59
+ def get_model(self):
60
+ return self.model
61
+
62
+ def forward(
63
+ self,
64
+ input_ids: torch.LongTensor = None,
65
+ attention_mask: Optional[torch.Tensor] = None,
66
+ position_ids: Optional[torch.LongTensor] = None,
67
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
68
+ inputs_embeds: Optional[torch.FloatTensor] = None,
69
+ labels: Optional[torch.LongTensor] = None,
70
+ use_cache: Optional[bool] = None,
71
+ output_attentions: Optional[bool] = None,
72
+ output_hidden_states: Optional[bool] = None,
73
+ images: Optional[torch.FloatTensor] = None,
74
+ image_sizes: Optional[List[List[int]]] = None,
75
+ return_dict: Optional[bool] = None,
76
+ cache_position=None,
77
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
78
+
79
+ if inputs_embeds is None:
80
+ (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, image_sizes)
81
+
82
+ return super().forward(
83
+ input_ids=input_ids,
84
+ attention_mask=attention_mask,
85
+ position_ids=position_ids,
86
+ past_key_values=past_key_values,
87
+ inputs_embeds=inputs_embeds,
88
+ labels=labels,
89
+ use_cache=use_cache,
90
+ output_attentions=output_attentions,
91
+ output_hidden_states=output_hidden_states,
92
+ return_dict=return_dict,
93
+ )
94
+
95
+ @torch.no_grad()
96
+ def generate(
97
+ self,
98
+ inputs: Optional[torch.Tensor] = None,
99
+ images: Optional[torch.Tensor] = None,
100
+ image_sizes: Optional[torch.Tensor] = None,
101
+ **kwargs,
102
+ ) -> Union[GenerateOutput, torch.LongTensor]:
103
+ position_ids = kwargs.pop("position_ids", None)
104
+ attention_mask = kwargs.pop("attention_mask", None)
105
+ if "inputs_embeds" in kwargs:
106
+ raise NotImplementedError("`inputs_embeds` is not supported")
107
+
108
+ if images is not None:
109
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, image_sizes=image_sizes)
110
+ else:
111
+ inputs_embeds = self.get_model().embed_tokens(inputs)
112
+
113
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
114
+
115
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
116
+ images = kwargs.pop("images", None)
117
+ image_sizes = kwargs.pop("image_sizes", None)
118
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
119
+ if images is not None:
120
+ inputs["images"] = images
121
+ if image_sizes is not None:
122
+ inputs["image_sizes"] = image_sizes
123
+ return inputs
124
+
125
+
126
+ AutoConfig.register("llava_mistral", LlavaMistralConfig)
127
+ AutoModelForCausalLM.register(LlavaMistralConfig, LlavaMistralForCausalLM)
LLaVA-NeXT/llava/model/language_model/llava_mixtral.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from torch.nn import CrossEntropyLoss
21
+
22
+ from transformers import AutoConfig, AutoModelForCausalLM, MixtralConfig, MixtralModel, MixtralForCausalLM, GenerationConfig
23
+
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.generation.utils import GenerateOutput
26
+
27
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
28
+
29
+
30
+ class LlavaMixtralConfig(MixtralConfig):
31
+ model_type = "llava_mixtral"
32
+
33
+
34
+ class LlavaMixtralModel(LlavaMetaModel, MixtralModel):
35
+ config_class = LlavaMixtralConfig
36
+
37
+ def __init__(self, config: MixtralConfig):
38
+ super(LlavaMixtralModel, self).__init__(config)
39
+
40
+
41
+ class LlavaMixtralForCausalLM(MixtralForCausalLM, LlavaMetaForCausalLM):
42
+ config_class = LlavaMixtralConfig
43
+
44
+ def __init__(self, config):
45
+ super(MixtralForCausalLM, self).__init__(config)
46
+
47
+ config.model_type = "llava_mixtral"
48
+ config.rope_scaling = None
49
+ self.model = LlavaMixtralModel(config)
50
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
51
+ # Initialize weights and apply final processing
52
+ self.post_init()
53
+
54
+ def get_model(self):
55
+ return self.model
56
+
57
+ def forward(
58
+ self,
59
+ input_ids: torch.LongTensor = None,
60
+ attention_mask: Optional[torch.Tensor] = None,
61
+ position_ids: Optional[torch.LongTensor] = None,
62
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
63
+ inputs_embeds: Optional[torch.FloatTensor] = None,
64
+ labels: Optional[torch.LongTensor] = None,
65
+ use_cache: Optional[bool] = None,
66
+ output_attentions: Optional[bool] = None,
67
+ output_hidden_states: Optional[bool] = None,
68
+ images: Optional[torch.FloatTensor] = None,
69
+ image_sizes: Optional[List[List[int]]] = None,
70
+ return_dict: Optional[bool] = None,
71
+ modalities: Optional[List[str]] = ["image"],
72
+ dpo_forward: Optional[bool] = None,
73
+ cache_position=None,
74
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
75
+
76
+ if inputs_embeds is None:
77
+ (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes)
78
+
79
+ if dpo_forward:
80
+ outputs = self.model(
81
+ input_ids=input_ids,
82
+ attention_mask=attention_mask,
83
+ position_ids=position_ids,
84
+ past_key_values=past_key_values,
85
+ inputs_embeds=inputs_embeds,
86
+ use_cache=use_cache,
87
+ output_attentions=output_attentions,
88
+ output_hidden_states=output_hidden_states,
89
+ return_dict=return_dict,
90
+ )
91
+
92
+ hidden_states = outputs[0]
93
+ logits = self.lm_head(hidden_states)
94
+ return logits, labels
95
+
96
+ else:
97
+ return super().forward(
98
+ input_ids=input_ids,
99
+ attention_mask=attention_mask,
100
+ position_ids=position_ids,
101
+ past_key_values=past_key_values,
102
+ inputs_embeds=inputs_embeds,
103
+ labels=labels,
104
+ use_cache=use_cache,
105
+ output_attentions=output_attentions,
106
+ output_hidden_states=output_hidden_states,
107
+ return_dict=return_dict,
108
+ )
109
+
110
+ @torch.no_grad()
111
+ def generate(
112
+ self,
113
+ inputs: Optional[torch.Tensor] = None,
114
+ images: Optional[torch.Tensor] = None,
115
+ image_sizes: Optional[torch.Tensor] = None,
116
+ modalities: Optional[List[str]] = ["image"],
117
+ **kwargs,
118
+ ) -> Union[GenerateOutput, torch.LongTensor]:
119
+ position_ids = kwargs.pop("position_ids", None)
120
+ attention_mask = kwargs.pop("attention_mask", None)
121
+ if "inputs_embeds" in kwargs:
122
+ raise NotImplementedError("`inputs_embeds` is not supported")
123
+
124
+ if images is not None:
125
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
126
+ else:
127
+ inputs_embeds = self.get_model().embed_tokens(inputs)
128
+
129
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
130
+
131
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
132
+ images = kwargs.pop("images", None)
133
+ image_sizes = kwargs.pop("image_sizes", None)
134
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
135
+ if images is not None:
136
+ inputs["images"] = images
137
+ if image_sizes is not None:
138
+ inputs["image_sizes"] = image_sizes
139
+ return inputs
140
+
141
+
142
+ AutoConfig.register("llava_mixtral", LlavaMixtralConfig)
143
+ AutoModelForCausalLM.register(LlavaMixtralConfig, LlavaMixtralForCausalLM)
LLaVA-NeXT/llava/model/language_model/llava_mpt.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ from typing import Optional, Tuple
17
+
18
+ import torch
19
+
20
+ from transformers import AutoConfig, AutoModelForCausalLM, MptConfig, MptForCausalLM, MptModel, GenerationConfig
21
+ from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
22
+
23
+
24
+ class LlavaMptConfig(MptConfig):
25
+ model_type = "llava_mpt"
26
+
27
+
28
+ class LlavaMptModel(LlavaMetaModel, MptModel):
29
+ config_class = LlavaMptConfig
30
+
31
+ def __init__(self, config: MptConfig):
32
+ config.hidden_size = config.d_model
33
+ super(LlavaMptModel, self).__init__(config)
34
+
35
+ def embed_tokens(self, x):
36
+ return self.wte(x)
37
+
38
+
39
+ class LlavaMptForCausalLM(MptForCausalLM, LlavaMetaForCausalLM):
40
+ config_class = LlavaMptConfig
41
+ supports_gradient_checkpointing = True
42
+
43
+ def __init__(self, config):
44
+ super(MptForCausalLM, self).__init__(config)
45
+
46
+ config.model_type = "llava_mpt"
47
+ config.rope_scaling = None
48
+ self.generation_config = GenerationConfig(
49
+ temperature=0.0,
50
+ max_new_tokens=1024,
51
+ do_sample=False,
52
+ top_p=None,
53
+ )
54
+
55
+ self.transformer = LlavaMptModel(config)
56
+ self.lm_head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias=False)
57
+
58
+ # Initialize weights and apply final processing
59
+ self.post_init()
60
+
61
+ def get_model(self):
62
+ return self.transformer
63
+
64
+ def _set_gradient_checkpointing(self, module, value=False):
65
+ if isinstance(module, LlavaMptModel):
66
+ module.gradient_checkpointing = value
67
+
68
+ def forward(
69
+ self,
70
+ input_ids: Optional[torch.LongTensor] = None,
71
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
72
+ attention_mask: Optional[torch.Tensor] = None,
73
+ inputs_embeds: Optional[torch.Tensor] = None,
74
+ labels: Optional[torch.Tensor] = None,
75
+ use_cache: Optional[bool] = None,
76
+ output_attentions: Optional[bool] = None,
77
+ output_hidden_states: Optional[bool] = None,
78
+ return_dict: Optional[bool] = None,
79
+ cache_position=None,
80
+ images=None,
81
+ ):
82
+
83
+ input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images)
84
+
85
+ return super().forward(
86
+ input_ids,
87
+ past_key_values=past_key_values,
88
+ attention_mask=attention_mask,
89
+ inputs_embeds=inputs_embeds,
90
+ labels=labels,
91
+ use_cache=use_cache,
92
+ output_attentions=output_attentions,
93
+ output_hidden_states=output_hidden_states,
94
+ return_dict=return_dict,
95
+ )
96
+
97
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
98
+ images = kwargs.pop("images", None)
99
+ _inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
100
+ _inputs["images"] = images
101
+ return _inputs
102
+
103
+
104
+ AutoConfig.register("llava_mpt", LlavaMptConfig)
105
+ AutoModelForCausalLM.register(LlavaMptConfig, LlavaMptForCausalLM)
LLaVA-NeXT/llava/model/language_model/llava_qwen.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Hao Zhang
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
+
16
+ from typing import List, Optional, Tuple, Union, Dict
17
+ import torch
18
+ import torch.nn as nn
19
+ from torch.nn import CrossEntropyLoss
20
+
21
+ import transformers
22
+ from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig, LlamaModel, LlamaForCausalLM
23
+
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.generation.utils import GenerateOutput
26
+
27
+ # from ...constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
28
+ from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
29
+ from transformers import Qwen2Config, Qwen2Model, Qwen2ForCausalLM
30
+
31
+ # from .qwen.modeling_qwen import QWenLMHeadModel, QWenModel
32
+ # from .qwen.configuration_qwen import QWenConfig
33
+
34
+
35
+ class LlavaQwenConfig(Qwen2Config):
36
+ model_type = "llava_qwen"
37
+
38
+
39
+ class LlavaQwenModel(LlavaMetaModel, Qwen2Model):
40
+ config_class = LlavaQwenConfig
41
+
42
+ def __init__(self, config: Qwen2Config):
43
+ super(LlavaQwenModel, self).__init__(config)
44
+
45
+
46
+ class LlavaQwenForCausalLM(Qwen2ForCausalLM, LlavaMetaForCausalLM):
47
+ config_class = LlavaQwenConfig
48
+
49
+ def __init__(self, config):
50
+ # super(Qwen2ForCausalLM, self).__init__(config)
51
+ Qwen2ForCausalLM.__init__(self, config)
52
+ config.model_type = "llava_qwen"
53
+ config.rope_scaling = None
54
+
55
+ self.model = LlavaQwenModel(config)
56
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
57
+ # Initialize weights and apply final processing
58
+ self.post_init()
59
+
60
+ def get_model(self):
61
+ return self.model
62
+
63
+ def forward(
64
+ self,
65
+ input_ids: torch.LongTensor = None,
66
+ attention_mask: Optional[torch.Tensor] = None,
67
+ position_ids: Optional[torch.LongTensor] = None,
68
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
69
+ inputs_embeds: Optional[torch.FloatTensor] = None,
70
+ labels: Optional[torch.LongTensor] = None,
71
+ use_cache: Optional[bool] = None,
72
+ output_attentions: Optional[bool] = None,
73
+ output_hidden_states: Optional[bool] = None,
74
+ images: Optional[torch.FloatTensor] = None,
75
+ image_sizes: Optional[List[List[int]]] = None,
76
+ return_dict: Optional[bool] = None,
77
+ modalities: Optional[List[str]] = ["image"],
78
+ dpo_forward: Optional[bool] = False,
79
+ cache_position=None,
80
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
81
+
82
+ if inputs_embeds is None:
83
+ (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes)
84
+
85
+ if dpo_forward:
86
+ outputs = self.model(
87
+ input_ids=input_ids,
88
+ attention_mask=attention_mask,
89
+ position_ids=position_ids,
90
+ past_key_values=past_key_values,
91
+ inputs_embeds=inputs_embeds,
92
+ use_cache=use_cache,
93
+ output_attentions=output_attentions,
94
+ output_hidden_states=output_hidden_states,
95
+ return_dict=return_dict,
96
+ )
97
+
98
+ hidden_states = outputs[0]
99
+ logits = self.lm_head(hidden_states)
100
+ return logits, labels
101
+
102
+ else:
103
+ return super().forward(
104
+ input_ids=input_ids,
105
+ attention_mask=attention_mask,
106
+ position_ids=position_ids,
107
+ past_key_values=past_key_values,
108
+ inputs_embeds=inputs_embeds,
109
+ labels=labels,
110
+ use_cache=use_cache,
111
+ output_attentions=output_attentions,
112
+ output_hidden_states=output_hidden_states,
113
+ return_dict=return_dict,
114
+ )
115
+
116
+ @torch.no_grad()
117
+ def generate(
118
+ self,
119
+ inputs: Optional[torch.Tensor] = None,
120
+ images: Optional[torch.Tensor] = None,
121
+ image_sizes: Optional[torch.Tensor] = None,
122
+ modalities: Optional[List[str]] = ["image"],
123
+ **kwargs,
124
+ ) -> Union[GenerateOutput, torch.LongTensor]:
125
+ position_ids = kwargs.pop("position_ids", None)
126
+ attention_mask = kwargs.pop("attention_mask", None)
127
+ if "inputs_embeds" in kwargs:
128
+ raise NotImplementedError("`inputs_embeds` is not supported")
129
+
130
+ if images is not None:
131
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
132
+ else:
133
+ inputs_embeds = self.get_model().embed_tokens(inputs)
134
+
135
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
136
+
137
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
138
+ images = kwargs.pop("images", None)
139
+ image_sizes = kwargs.pop("image_sizes", None)
140
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
141
+ if images is not None:
142
+ inputs["images"] = images
143
+ if image_sizes is not None:
144
+ inputs["image_sizes"] = image_sizes
145
+ return inputs
146
+
147
+
148
+ AutoConfig.register("llava_qwen", LlavaQwenConfig)
149
+ AutoModelForCausalLM.register(LlavaQwenConfig, LlavaQwenForCausalLM)
LLaVA-NeXT/llava/model/language_model/llava_qwen_moe.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Hao Zhang
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
+
16
+ from typing import List, Optional, Tuple, Union, Dict
17
+ import torch
18
+ import torch.nn as nn
19
+ from torch.nn import CrossEntropyLoss
20
+
21
+ import transformers
22
+ from transformers import AutoConfig, AutoModelForCausalLM
23
+
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.generation.utils import GenerateOutput
26
+
27
+ # from ...constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
28
+ from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
29
+ from transformers import Qwen2MoeConfig, Qwen2MoeModel, Qwen2MoeForCausalLM
30
+
31
+ # from .qwen.modeling_qwen import QWenLMHeadModel, QWenModel
32
+ # from .qwen.configuration_qwen import QWenConfig
33
+
34
+
35
+ class LlavaQwenMoeConfig(Qwen2MoeConfig):
36
+ model_type = "llava_qwen_moe"
37
+
38
+
39
+ class LlavaQwenMoeModel(LlavaMetaModel, Qwen2MoeModel):
40
+ config_class = LlavaQwenMoeConfig
41
+
42
+ def __init__(self, config: Qwen2MoeConfig):
43
+ super(LlavaQwenMoeModel, self).__init__(config)
44
+
45
+
46
+ class LlavaQwenMoeForCausalLM(Qwen2MoeForCausalLM, LlavaMetaForCausalLM):
47
+ config_class = LlavaQwenMoeConfig
48
+
49
+ def __init__(self, config):
50
+ # super(Qwen2MoeForCausalLM, self).__init__(config)
51
+ Qwen2MoeForCausalLM.__init__(self, config)
52
+ config.model_type = "llava_qwen_moe"
53
+ config.rope_scaling = None
54
+
55
+ self.model = LlavaQwenMoeModel(config)
56
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
57
+ # Initialize weights and apply final processing
58
+ self.post_init()
59
+
60
+ def get_model(self):
61
+ return self.model
62
+
63
+ def forward(
64
+ self,
65
+ input_ids: torch.LongTensor = None,
66
+ attention_mask: Optional[torch.Tensor] = None,
67
+ position_ids: Optional[torch.LongTensor] = None,
68
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
69
+ inputs_embeds: Optional[torch.FloatTensor] = None,
70
+ labels: Optional[torch.LongTensor] = None,
71
+ use_cache: Optional[bool] = None,
72
+ output_attentions: Optional[bool] = None,
73
+ output_hidden_states: Optional[bool] = None,
74
+ images: Optional[torch.FloatTensor] = None,
75
+ image_sizes: Optional[List[List[int]]] = None,
76
+ return_dict: Optional[bool] = None,
77
+ modalities: Optional[List[str]] = ["image"],
78
+ dpo_forward: Optional[bool] = False,
79
+ cache_position=None,
80
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
81
+
82
+ if inputs_embeds is None:
83
+ (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes)
84
+
85
+ if dpo_forward:
86
+ outputs = self.model(
87
+ input_ids=input_ids,
88
+ attention_mask=attention_mask,
89
+ position_ids=position_ids,
90
+ past_key_values=past_key_values,
91
+ inputs_embeds=inputs_embeds,
92
+ use_cache=use_cache,
93
+ output_attentions=output_attentions,
94
+ output_hidden_states=output_hidden_states,
95
+ return_dict=return_dict,
96
+ )
97
+
98
+ hidden_states = outputs[0]
99
+ logits = self.lm_head(hidden_states)
100
+ return logits, labels
101
+
102
+ else:
103
+ return super().forward(
104
+ input_ids=input_ids,
105
+ attention_mask=attention_mask,
106
+ position_ids=position_ids,
107
+ past_key_values=past_key_values,
108
+ inputs_embeds=inputs_embeds,
109
+ labels=labels,
110
+ use_cache=use_cache,
111
+ output_attentions=output_attentions,
112
+ output_hidden_states=output_hidden_states,
113
+ return_dict=return_dict,
114
+ )
115
+
116
+ @torch.no_grad()
117
+ def generate(
118
+ self,
119
+ inputs: Optional[torch.Tensor] = None,
120
+ images: Optional[torch.Tensor] = None,
121
+ image_sizes: Optional[torch.Tensor] = None,
122
+ modalities: Optional[List[str]] = ["image"],
123
+ **kwargs,
124
+ ) -> Union[GenerateOutput, torch.LongTensor]:
125
+ position_ids = kwargs.pop("position_ids", None)
126
+ attention_mask = kwargs.pop("attention_mask", None)
127
+ if "inputs_embeds" in kwargs:
128
+ raise NotImplementedError("`inputs_embeds` is not supported")
129
+
130
+ if images is not None:
131
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
132
+ else:
133
+ inputs_embeds = self.get_model().embed_tokens(inputs)
134
+
135
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
136
+
137
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
138
+ images = kwargs.pop("images", None)
139
+ image_sizes = kwargs.pop("image_sizes", None)
140
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
141
+ if images is not None:
142
+ inputs["images"] = images
143
+ if image_sizes is not None:
144
+ inputs["image_sizes"] = image_sizes
145
+ return inputs
146
+
147
+
148
+ AutoConfig.register("llava_qwen_moe", LlavaQwenMoeConfig)
149
+ AutoModelForCausalLM.register(LlavaQwenMoeConfig, LlavaQwenMoeForCausalLM)
LLaVA-NeXT/llava/model/language_model/modeling_llama.py ADDED
@@ -0,0 +1,1649 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutputWithPast,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
41
+ from transformers.utils import (
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_flash_attn_2_available,
45
+ is_flash_attn_greater_or_equal_2_10,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+ from transformers.models.llama.configuration_llama import LlamaConfig
50
+
51
+ if is_flash_attn_2_available():
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ _CONFIG_FOR_DOC = "LlamaConfig"
59
+
60
+
61
+ def _get_unpad_data(attention_mask):
62
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
63
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
64
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
65
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
66
+ return (
67
+ indices,
68
+ cu_seqlens,
69
+ max_seqlen_in_batch,
70
+ )
71
+
72
+
73
+ class LlamaRMSNorm(nn.Module):
74
+ def __init__(self, hidden_size, eps=1e-6):
75
+ """
76
+ LlamaRMSNorm is equivalent to T5LayerNorm
77
+ """
78
+ super().__init__()
79
+ self.weight = nn.Parameter(torch.ones(hidden_size))
80
+ self.variance_epsilon = eps
81
+
82
+ def forward(self, hidden_states):
83
+ input_dtype = hidden_states.dtype
84
+ hidden_states = hidden_states.to(torch.float32)
85
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
86
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
87
+ return self.weight * hidden_states.to(input_dtype)
88
+
89
+
90
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
91
+
92
+
93
+ class LlamaRotaryEmbedding(nn.Module):
94
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
95
+ super().__init__()
96
+ self.scaling_factor = scaling_factor
97
+ self.dim = dim
98
+ self.max_position_embeddings = max_position_embeddings
99
+ self.base = base
100
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
101
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
102
+ # For BC we register cos and sin cached
103
+ self.max_seq_len_cached = max_position_embeddings
104
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
105
+ t = t / self.scaling_factor
106
+ freqs = torch.outer(t, self.inv_freq)
107
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
108
+ emb = torch.cat((freqs, freqs), dim=-1)
109
+ self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False)
110
+ self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False)
111
+
112
+ @property
113
+ def sin_cached(self):
114
+ logger.warning_once("The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use " "the forward method of RoPE from now on instead. It is not used in the `LlamaAttention` class")
115
+ return self._sin_cached
116
+
117
+ @property
118
+ def cos_cached(self):
119
+ logger.warning_once("The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use " "the forward method of RoPE from now on instead. It is not used in the `LlamaAttention` class")
120
+ return self._cos_cached
121
+
122
+ @torch.no_grad()
123
+ def forward(self, x, position_ids, seq_len=None):
124
+ if seq_len is not None:
125
+ logger.warning_once("The `seq_len` argument is deprecated and unused. It will be removed in v4.39.")
126
+
127
+ # x: [bs, num_attention_heads, seq_len, head_size]
128
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
129
+ position_ids_expanded = position_ids[:, None, :].float()
130
+ # Force float32 since bfloat16 loses precision on long contexts
131
+ # See https://github.com/huggingface/transformers/pull/29285
132
+ device_type = x.device.type
133
+ device_type = device_type if isinstance(device_type, str) else "cpu"
134
+ with torch.autocast(device_type=device_type, enabled=False):
135
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ cos = emb.cos()
138
+ sin = emb.sin()
139
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
140
+
141
+
142
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
143
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
144
+
145
+ def forward(self, x, position_ids, seq_len=None):
146
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
147
+ position_ids = position_ids.float() / self.scaling_factor
148
+ cos, sin = super().forward(x, position_ids, seq_len)
149
+ return cos, sin
150
+
151
+
152
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
153
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
154
+
155
+ def forward(self, x, position_ids, seq_len=None):
156
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
157
+ seq_len = torch.max(position_ids) + 1
158
+ if seq_len > self.max_position_embeddings:
159
+ base = self.base * ((self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)) ** (self.dim / (self.dim - 2))
160
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim))
161
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
162
+
163
+ cos, sin = super().forward(x, position_ids, seq_len)
164
+ return cos, sin
165
+
166
+
167
+ def rotate_half(x):
168
+ """Rotates half the hidden dims of the input."""
169
+ x1 = x[..., : x.shape[-1] // 2]
170
+ x2 = x[..., x.shape[-1] // 2 :]
171
+ return torch.cat((-x2, x1), dim=-1)
172
+
173
+
174
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
175
+ """Applies Rotary Position Embedding to the query and key tensors.
176
+
177
+ Args:
178
+ q (`torch.Tensor`): The query tensor.
179
+ k (`torch.Tensor`): The key tensor.
180
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
181
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
182
+ position_ids (`torch.Tensor`, *optional*):
183
+ Deprecated and unused.
184
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
185
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
186
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
187
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
188
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
189
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
190
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
191
+ Returns:
192
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
193
+ """
194
+ cos = cos.unsqueeze(unsqueeze_dim)
195
+ sin = sin.unsqueeze(unsqueeze_dim)
196
+ q_embed = (q * cos) + (rotate_half(q) * sin)
197
+ k_embed = (k * cos) + (rotate_half(k) * sin)
198
+ return q_embed, k_embed
199
+
200
+
201
+ class LlamaMLP(nn.Module):
202
+ def __init__(self, config):
203
+ super().__init__()
204
+ self.config = config
205
+ self.hidden_size = config.hidden_size
206
+ self.intermediate_size = config.intermediate_size
207
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
208
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
209
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
210
+ self.act_fn = ACT2FN[config.hidden_act]
211
+
212
+ def forward(self, x):
213
+ if self.config.pretraining_tp > 1:
214
+ slice = self.intermediate_size // self.config.pretraining_tp
215
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
216
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
217
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
218
+
219
+ gate_proj = torch.cat([F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
220
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
221
+
222
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
223
+ down_proj = [F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)]
224
+ down_proj = sum(down_proj)
225
+ else:
226
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
227
+
228
+ return down_proj
229
+
230
+
231
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
232
+ """
233
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
234
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
235
+ """
236
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
237
+ if n_rep == 1:
238
+ return hidden_states
239
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
240
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
241
+
242
+
243
+ class LlamaAttention(nn.Module):
244
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
245
+
246
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
247
+ super().__init__()
248
+ self.config = config
249
+ self.layer_idx = layer_idx
250
+ if layer_idx is None:
251
+ logger.warning_once(
252
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
253
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
254
+ "when creating this class."
255
+ )
256
+
257
+ self.attention_dropout = config.attention_dropout
258
+ self.hidden_size = config.hidden_size
259
+ self.num_heads = config.num_attention_heads
260
+ self.head_dim = self.hidden_size // self.num_heads
261
+ self.num_key_value_heads = config.num_key_value_heads
262
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
263
+ self.max_position_embeddings = config.max_position_embeddings
264
+ self.rope_theta = config.rope_theta
265
+ self.is_causal = True
266
+
267
+ if (self.head_dim * self.num_heads) != self.hidden_size:
268
+ raise ValueError(f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" f" and `num_heads`: {self.num_heads}).")
269
+
270
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
271
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
272
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
273
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
274
+ self._init_rope()
275
+
276
+ def _init_rope(self):
277
+ if self.config.rope_scaling is None:
278
+ self.rotary_emb = LlamaRotaryEmbedding(
279
+ self.head_dim,
280
+ max_position_embeddings=self.max_position_embeddings,
281
+ base=self.rope_theta,
282
+ )
283
+ else:
284
+ scaling_type = self.config.rope_scaling["type"]
285
+ scaling_factor = self.config.rope_scaling["factor"]
286
+ if scaling_type == "linear":
287
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
288
+ self.head_dim,
289
+ max_position_embeddings=self.max_position_embeddings,
290
+ scaling_factor=scaling_factor,
291
+ base=self.rope_theta,
292
+ )
293
+ elif scaling_type == "dynamic":
294
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
295
+ self.head_dim,
296
+ max_position_embeddings=self.max_position_embeddings,
297
+ scaling_factor=scaling_factor,
298
+ base=self.rope_theta,
299
+ )
300
+ else:
301
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
302
+
303
+ def forward(
304
+ self,
305
+ hidden_states: torch.Tensor,
306
+ attention_mask: Optional[torch.Tensor] = None,
307
+ position_ids: Optional[torch.LongTensor] = None,
308
+ past_key_value: Optional[Cache] = None,
309
+ output_attentions: bool = False,
310
+ use_cache: bool = False,
311
+ cache_position: Optional[torch.LongTensor] = None,
312
+ **kwargs,
313
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
314
+ bsz, q_len, _ = hidden_states.size()
315
+
316
+ if self.config.pretraining_tp > 1:
317
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
318
+ query_slices = self.q_proj.weight.split((self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0)
319
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
320
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
321
+
322
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
323
+ query_states = torch.cat(query_states, dim=-1)
324
+
325
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
326
+ key_states = torch.cat(key_states, dim=-1)
327
+
328
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
329
+ value_states = torch.cat(value_states, dim=-1)
330
+
331
+ else:
332
+ query_states = self.q_proj(hidden_states)
333
+ key_states = self.k_proj(hidden_states)
334
+ value_states = self.v_proj(hidden_states)
335
+
336
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
337
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
338
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
339
+
340
+ past_key_value = getattr(self, "past_key_value", past_key_value)
341
+ cos, sin = self.rotary_emb(value_states, position_ids)
342
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
343
+
344
+ if past_key_value is not None:
345
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
346
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
347
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
348
+
349
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
350
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
351
+
352
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
353
+
354
+ if attention_mask is not None: # no matter the length, we just slice it
355
+ causal_mask = attention_mask
356
+ if cache_position is not None:
357
+ causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]]
358
+ attn_weights = attn_weights + causal_mask
359
+
360
+ # upcast attention to fp32
361
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
362
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
363
+ attn_output = torch.matmul(attn_weights, value_states)
364
+
365
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
366
+ raise ValueError(f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" f" {attn_output.size()}")
367
+
368
+ attn_output = attn_output.transpose(1, 2).contiguous()
369
+
370
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
371
+
372
+ if self.config.pretraining_tp > 1:
373
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
374
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
375
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
376
+ else:
377
+ attn_output = self.o_proj(attn_output)
378
+
379
+ if not output_attentions:
380
+ attn_weights = None
381
+
382
+ return attn_output, attn_weights, past_key_value
383
+
384
+
385
+ class LlamaRingFlashAttention2(LlamaAttention):
386
+ """
387
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
388
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
389
+ flash attention and deal with padding tokens in case the input contains any of them.
390
+ """
391
+
392
+ def __init__(self, *args, **kwargs):
393
+ super().__init__(*args, **kwargs)
394
+
395
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
396
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
397
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
398
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
399
+
400
+ def forward(
401
+ self,
402
+ hidden_states: torch.Tensor,
403
+ attention_mask: Optional[torch.LongTensor] = None,
404
+ position_ids: Optional[torch.LongTensor] = None,
405
+ past_key_value: Optional[Cache] = None,
406
+ output_attentions: bool = False,
407
+ use_cache: bool = False,
408
+ cache_position: Optional[torch.LongTensor] = None,
409
+ **kwargs,
410
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
411
+ output_attentions = False
412
+
413
+ bsz, q_len, _ = hidden_states.size()
414
+
415
+ query_states = self.q_proj(hidden_states)
416
+ key_states = self.k_proj(hidden_states)
417
+ value_states = self.v_proj(hidden_states)
418
+
419
+ # Flash attention requires the input to have the shape
420
+ # batch_size x seq_length x head_dim x hidden_dim
421
+ # therefore we just need to keep the original shape
422
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
423
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
424
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
425
+
426
+ cos, sin = self.rotary_emb(value_states, position_ids)
427
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
428
+
429
+ past_key_value = getattr(self, "past_key_value", past_key_value)
430
+
431
+ if past_key_value is not None:
432
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
433
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
434
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
435
+
436
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
437
+ # to be able to avoid many of these transpose/reshape/view.
438
+ query_states = query_states.transpose(1, 2)
439
+ key_states = key_states.transpose(1, 2)
440
+ value_states = value_states.transpose(1, 2)
441
+
442
+ dropout_rate = self.attention_dropout if self.training else 0.0
443
+
444
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
445
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
446
+ # cast them back in the correct dtype just to be sure everything works as expected.
447
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
448
+ # in fp32. (LlamaRMSNorm handles it correctly)
449
+
450
+ input_dtype = query_states.dtype
451
+ if input_dtype == torch.float32:
452
+ if torch.is_autocast_enabled():
453
+ target_dtype = torch.get_autocast_gpu_dtype()
454
+ # Handle the case where the model is quantized
455
+ elif hasattr(self.config, "_pre_quantization_dtype"):
456
+ target_dtype = self.config._pre_quantization_dtype
457
+ else:
458
+ target_dtype = self.q_proj.weight.dtype
459
+
460
+ logger.warning_once(
461
+ f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}."
462
+ )
463
+
464
+ query_states = query_states.to(target_dtype)
465
+ key_states = key_states.to(target_dtype)
466
+ value_states = value_states.to(target_dtype)
467
+
468
+ attn_output = self._flash_attention_forward(query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate)
469
+
470
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
471
+ attn_output = self.o_proj(attn_output)
472
+
473
+ if not output_attentions:
474
+ attn_weights = None
475
+
476
+ return attn_output, attn_weights, past_key_value
477
+
478
+ def _flash_attention_forward(self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None):
479
+ """
480
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
481
+ first unpad the input, then computes the attention scores and pad the final attention scores.
482
+
483
+ Args:
484
+ query_states (`torch.Tensor`):
485
+ Input query states to be passed to Flash Attention API
486
+ key_states (`torch.Tensor`):
487
+ Input key states to be passed to Flash Attention API
488
+ value_states (`torch.Tensor`):
489
+ Input value states to be passed to Flash Attention API
490
+ attention_mask (`torch.Tensor`):
491
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
492
+ position of padding tokens and 1 for the position of non-padding tokens.
493
+ dropout (`int`, *optional*):
494
+ Attention dropout
495
+ softmax_scale (`float`, *optional*):
496
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
497
+ """
498
+ if not self._flash_attn_uses_top_left_mask:
499
+ causal = self.is_causal
500
+ else:
501
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
502
+ causal = self.is_causal and query_length != 1
503
+
504
+ # Contains at least one padding token in the sequence
505
+ if attention_mask is not None:
506
+ batch_size = query_states.shape[0]
507
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(query_states, key_states, value_states, attention_mask, query_length)
508
+
509
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
510
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
511
+
512
+ attn_output_unpad = zigzag_ring_flash_attn_varlen_func(
513
+ query_states,
514
+ key_states,
515
+ value_states,
516
+ cu_seqlens_q=cu_seqlens_q,
517
+ cu_seqlens_k=cu_seqlens_k,
518
+ max_seqlen_q=max_seqlen_in_batch_q,
519
+ max_seqlen_k=max_seqlen_in_batch_k,
520
+ dropout_p=dropout,
521
+ softmax_scale=softmax_scale,
522
+ causal=causal,
523
+ )
524
+
525
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
526
+ else:
527
+ # pack qkv
528
+ # query_states: (batch_size, seqlen, nheads, headdim)
529
+ # qkv: (batch_size, seqlen, 3, nheads, headdim)
530
+ qkv = torch.stack([query_states, key_states, value_states], dim=2)
531
+ attn_output = zigzag_ring_flash_attn_qkvpacked_func(qkv, dropout, softmax_scale, causal=causal)
532
+
533
+ return attn_output
534
+
535
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
536
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
537
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
538
+
539
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k)
540
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k)
541
+ if query_length == kv_seq_len:
542
+ query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k)
543
+ cu_seqlens_q = cu_seqlens_k
544
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
545
+ indices_q = indices_k
546
+ elif query_length == 1:
547
+ max_seqlen_in_batch_q = 1
548
+ cu_seqlens_q = torch.arange(batch_size + 1, dtype=torch.int32, device=query_layer.device) # There is a memcpy here, that is very bad.
549
+ indices_q = cu_seqlens_q[:-1]
550
+ query_layer = query_layer.squeeze(1)
551
+ else:
552
+ # The -q_len: slice assumes left padding.
553
+ attention_mask = attention_mask[:, -query_length:]
554
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
555
+
556
+ return (
557
+ query_layer,
558
+ key_layer,
559
+ value_layer,
560
+ indices_q,
561
+ (cu_seqlens_q, cu_seqlens_k),
562
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
563
+ )
564
+
565
+
566
+ class LlamaFlashAttention2(LlamaAttention):
567
+ """
568
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
569
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
570
+ flash attention and deal with padding tokens in case the input contains any of them.
571
+ """
572
+
573
+ def __init__(self, *args, **kwargs):
574
+ super().__init__(*args, **kwargs)
575
+
576
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
577
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
578
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
579
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
580
+
581
+ def forward(
582
+ self,
583
+ hidden_states: torch.Tensor,
584
+ attention_mask: Optional[torch.LongTensor] = None,
585
+ position_ids: Optional[torch.LongTensor] = None,
586
+ past_key_value: Optional[Cache] = None,
587
+ output_attentions: bool = False,
588
+ use_cache: bool = False,
589
+ cache_position: Optional[torch.LongTensor] = None,
590
+ **kwargs,
591
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
592
+ output_attentions = False
593
+
594
+ bsz, q_len, _ = hidden_states.size()
595
+
596
+ query_states = self.q_proj(hidden_states)
597
+ key_states = self.k_proj(hidden_states)
598
+ value_states = self.v_proj(hidden_states)
599
+
600
+ # Flash attention requires the input to have the shape
601
+ # batch_size x seq_length x head_dim x hidden_dim
602
+ # therefore we just need to keep the original shape
603
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
604
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
605
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
606
+
607
+ cos, sin = self.rotary_emb(value_states, position_ids)
608
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
609
+
610
+ past_key_value = getattr(self, "past_key_value", past_key_value)
611
+
612
+ if past_key_value is not None:
613
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
614
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
615
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
616
+
617
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
618
+ # to be able to avoid many of these transpose/reshape/view.
619
+ query_states = query_states.transpose(1, 2)
620
+ key_states = key_states.transpose(1, 2)
621
+ value_states = value_states.transpose(1, 2)
622
+
623
+ dropout_rate = self.attention_dropout if self.training else 0.0
624
+
625
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
626
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
627
+ # cast them back in the correct dtype just to be sure everything works as expected.
628
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
629
+ # in fp32. (LlamaRMSNorm handles it correctly)
630
+
631
+ input_dtype = query_states.dtype
632
+ if input_dtype == torch.float32:
633
+ if torch.is_autocast_enabled():
634
+ target_dtype = torch.get_autocast_gpu_dtype()
635
+ # Handle the case where the model is quantized
636
+ elif hasattr(self.config, "_pre_quantization_dtype"):
637
+ target_dtype = self.config._pre_quantization_dtype
638
+ else:
639
+ target_dtype = self.q_proj.weight.dtype
640
+
641
+ logger.warning_once(
642
+ f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}."
643
+ )
644
+
645
+ query_states = query_states.to(target_dtype)
646
+ key_states = key_states.to(target_dtype)
647
+ value_states = value_states.to(target_dtype)
648
+
649
+ attn_output = self._flash_attention_forward(query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate)
650
+
651
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
652
+ attn_output = self.o_proj(attn_output)
653
+
654
+ if not output_attentions:
655
+ attn_weights = None
656
+
657
+ return attn_output, attn_weights, past_key_value
658
+
659
+ def _flash_attention_forward(self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None):
660
+ """
661
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
662
+ first unpad the input, then computes the attention scores and pad the final attention scores.
663
+
664
+ Args:
665
+ query_states (`torch.Tensor`):
666
+ Input query states to be passed to Flash Attention API
667
+ key_states (`torch.Tensor`):
668
+ Input key states to be passed to Flash Attention API
669
+ value_states (`torch.Tensor`):
670
+ Input value states to be passed to Flash Attention API
671
+ attention_mask (`torch.Tensor`):
672
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
673
+ position of padding tokens and 1 for the position of non-padding tokens.
674
+ dropout (`int`, *optional*):
675
+ Attention dropout
676
+ softmax_scale (`float`, *optional*):
677
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
678
+ """
679
+ if not self._flash_attn_uses_top_left_mask:
680
+ causal = self.is_causal
681
+ else:
682
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
683
+ causal = self.is_causal and query_length != 1
684
+
685
+ # Contains at least one padding token in the sequence
686
+ if attention_mask is not None:
687
+ batch_size = query_states.shape[0]
688
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(query_states, key_states, value_states, attention_mask, query_length)
689
+
690
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
691
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
692
+
693
+ attn_output_unpad = flash_attn_varlen_func(
694
+ query_states,
695
+ key_states,
696
+ value_states,
697
+ cu_seqlens_q=cu_seqlens_q,
698
+ cu_seqlens_k=cu_seqlens_k,
699
+ max_seqlen_q=max_seqlen_in_batch_q,
700
+ max_seqlen_k=max_seqlen_in_batch_k,
701
+ dropout_p=dropout,
702
+ softmax_scale=softmax_scale,
703
+ causal=causal,
704
+ )
705
+
706
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
707
+ else:
708
+ attn_output = flash_attn_func(query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal)
709
+
710
+ return attn_output
711
+
712
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
713
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
714
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
715
+
716
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k)
717
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k)
718
+ if query_length == kv_seq_len:
719
+ query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k)
720
+ cu_seqlens_q = cu_seqlens_k
721
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
722
+ indices_q = indices_k
723
+ elif query_length == 1:
724
+ max_seqlen_in_batch_q = 1
725
+ cu_seqlens_q = torch.arange(batch_size + 1, dtype=torch.int32, device=query_layer.device) # There is a memcpy here, that is very bad.
726
+ indices_q = cu_seqlens_q[:-1]
727
+ query_layer = query_layer.squeeze(1)
728
+ else:
729
+ # The -q_len: slice assumes left padding.
730
+ attention_mask = attention_mask[:, -query_length:]
731
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
732
+
733
+ return (
734
+ query_layer,
735
+ key_layer,
736
+ value_layer,
737
+ indices_q,
738
+ (cu_seqlens_q, cu_seqlens_k),
739
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
740
+ )
741
+
742
+
743
+ class LlamaSdpaAttention(LlamaAttention):
744
+ """
745
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
746
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
747
+ SDPA API.
748
+ """
749
+
750
+ # Adapted from LlamaAttention.forward
751
+ def forward(
752
+ self,
753
+ hidden_states: torch.Tensor,
754
+ attention_mask: Optional[torch.Tensor] = None,
755
+ position_ids: Optional[torch.LongTensor] = None,
756
+ past_key_value: Optional[Cache] = None,
757
+ output_attentions: bool = False,
758
+ use_cache: bool = False,
759
+ cache_position: Optional[torch.LongTensor] = None,
760
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
761
+ if output_attentions:
762
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
763
+ logger.warning_once(
764
+ "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
765
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
766
+ )
767
+ return super().forward(
768
+ hidden_states=hidden_states,
769
+ attention_mask=attention_mask,
770
+ position_ids=position_ids,
771
+ past_key_value=past_key_value,
772
+ output_attentions=output_attentions,
773
+ use_cache=use_cache,
774
+ cache_position=cache_position,
775
+ )
776
+
777
+ bsz, q_len, _ = hidden_states.size()
778
+
779
+ query_states = self.q_proj(hidden_states)
780
+ key_states = self.k_proj(hidden_states)
781
+ value_states = self.v_proj(hidden_states)
782
+
783
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
784
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
785
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
786
+
787
+ cos, sin = self.rotary_emb(value_states, position_ids)
788
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
789
+
790
+ # In case static cache is used, it is an instance attribute.
791
+ past_key_value = getattr(self, "past_key_value", past_key_value)
792
+
793
+ if past_key_value is not None:
794
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
795
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
796
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
797
+
798
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
799
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
800
+
801
+ causal_mask = attention_mask
802
+ if attention_mask is not None and cache_position is not None:
803
+ causal_mask = causal_mask[:, :, cache_position, : key_states.shape[-2]]
804
+
805
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
806
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
807
+ if query_states.device.type == "cuda" and causal_mask is not None:
808
+ query_states = query_states.contiguous()
809
+ key_states = key_states.contiguous()
810
+ value_states = value_states.contiguous()
811
+
812
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
813
+ query_states,
814
+ key_states,
815
+ value_states,
816
+ attn_mask=causal_mask,
817
+ dropout_p=self.attention_dropout if self.training else 0.0,
818
+ )
819
+
820
+ attn_output = attn_output.transpose(1, 2).contiguous()
821
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
822
+
823
+ attn_output = self.o_proj(attn_output)
824
+
825
+ return attn_output, None, past_key_value
826
+
827
+
828
+ try:
829
+ from ring_flash_attn import zigzag_ring_flash_attn_qkvpacked_func, zigzag_ring_flash_attn_varlen_func
830
+ except ImportError:
831
+ print("Please install the ring-flash-attn package")
832
+
833
+ LLAMA_ATTENTION_CLASSES = {
834
+ "eager": LlamaAttention,
835
+ "flash_attention_2": LlamaFlashAttention2,
836
+ "ring_flash_attention_2": LlamaRingFlashAttention2,
837
+ "sdpa": LlamaSdpaAttention,
838
+ }
839
+
840
+
841
+ class LlamaDecoderLayer(nn.Module):
842
+ def __init__(self, config: LlamaConfig, layer_idx: int):
843
+ super().__init__()
844
+ self.hidden_size = config.hidden_size
845
+
846
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
847
+
848
+ self.mlp = LlamaMLP(config)
849
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
850
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
851
+
852
+ def forward(
853
+ self,
854
+ hidden_states: torch.Tensor,
855
+ attention_mask: Optional[torch.Tensor] = None,
856
+ position_ids: Optional[torch.LongTensor] = None,
857
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
858
+ output_attentions: Optional[bool] = False,
859
+ use_cache: Optional[bool] = False,
860
+ cache_position: Optional[torch.LongTensor] = None,
861
+ **kwargs,
862
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
863
+ """
864
+ Args:
865
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
866
+ attention_mask (`torch.FloatTensor`, *optional*):
867
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
868
+ query_sequence_length, key_sequence_length)` if default attention is used.
869
+ output_attentions (`bool`, *optional*):
870
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
871
+ returned tensors for more detail.
872
+ use_cache (`bool`, *optional*):
873
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
874
+ (see `past_key_values`).
875
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
876
+ """
877
+ if "padding_mask" in kwargs:
878
+ warnings.warn("Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`")
879
+
880
+ residual = hidden_states
881
+
882
+ hidden_states = self.input_layernorm(hidden_states)
883
+
884
+ # Self Attention
885
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
886
+ hidden_states=hidden_states,
887
+ attention_mask=attention_mask,
888
+ position_ids=position_ids,
889
+ past_key_value=past_key_value,
890
+ output_attentions=output_attentions,
891
+ use_cache=use_cache,
892
+ cache_position=cache_position,
893
+ **kwargs,
894
+ )
895
+ hidden_states = residual + hidden_states
896
+
897
+ # Fully Connected
898
+ residual = hidden_states
899
+ hidden_states = self.post_attention_layernorm(hidden_states)
900
+ hidden_states = self.mlp(hidden_states)
901
+ hidden_states = residual + hidden_states
902
+
903
+ outputs = (hidden_states,)
904
+
905
+ if output_attentions:
906
+ outputs += (self_attn_weights,)
907
+
908
+ if use_cache:
909
+ outputs += (present_key_value,)
910
+
911
+ return outputs
912
+
913
+
914
+ LLAMA_START_DOCSTRING = r"""
915
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
916
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
917
+ etc.)
918
+
919
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
920
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
921
+ and behavior.
922
+
923
+ Parameters:
924
+ config ([`LlamaConfig`]):
925
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
926
+ load the weights associated with the model, only the configuration. Check out the
927
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
928
+ """
929
+
930
+
931
+ @add_start_docstrings(
932
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
933
+ LLAMA_START_DOCSTRING,
934
+ )
935
+ class LlamaPreTrainedModel(PreTrainedModel):
936
+ config_class = LlamaConfig
937
+ base_model_prefix = "model"
938
+ supports_gradient_checkpointing = True
939
+ _no_split_modules = ["LlamaDecoderLayer"]
940
+ _skip_keys_device_placement = ["past_key_values", "causal_mask"]
941
+ _supports_flash_attn_2 = True
942
+ _supports_sdpa = True
943
+ _supports_cache_class = True
944
+
945
+ def _init_weights(self, module):
946
+ std = self.config.initializer_range
947
+ if isinstance(module, nn.Linear):
948
+ module.weight.data.normal_(mean=0.0, std=std)
949
+ if module.bias is not None:
950
+ module.bias.data.zero_()
951
+ elif isinstance(module, nn.Embedding):
952
+ module.weight.data.normal_(mean=0.0, std=std)
953
+ if module.padding_idx is not None:
954
+ module.weight.data[module.padding_idx].zero_()
955
+
956
+ def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
957
+ if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
958
+ raise ValueError("`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` " "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers")
959
+
960
+ if max_cache_len > self.model.causal_mask.shape[-1] or self.device != self.model.causal_mask.device:
961
+ causal_mask = torch.full((max_cache_len, max_cache_len), fill_value=True, device=self.device, dtype=torch.bool)
962
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
963
+
964
+ for layer in self.model.layers:
965
+ device = layer.input_layernorm.weight.device
966
+ if hasattr(self.config, "_pre_quantization_dtype"):
967
+ dtype = self.config._pre_quantization_dtype
968
+ else:
969
+ dtype = layer.self_attn.o_proj.weight.dtype
970
+ layer.self_attn.past_key_value = cache_cls(self.config, max_batch_size, max_cache_len, device=device, dtype=dtype)
971
+
972
+ def _reset_cache(self):
973
+ for layer in self.model.layers:
974
+ layer.self_attn.past_key_value = None
975
+
976
+
977
+ LLAMA_INPUTS_DOCSTRING = r"""
978
+ Args:
979
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
980
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
981
+ it.
982
+
983
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
984
+ [`PreTrainedTokenizer.__call__`] for details.
985
+
986
+ [What are input IDs?](../glossary#input-ids)
987
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
988
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
989
+
990
+ - 1 for tokens that are **not masked**,
991
+ - 0 for tokens that are **masked**.
992
+
993
+ [What are attention masks?](../glossary#attention-mask)
994
+
995
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
996
+ [`PreTrainedTokenizer.__call__`] for details.
997
+
998
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
999
+ `past_key_values`).
1000
+
1001
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1002
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1003
+ information on the default strategy.
1004
+
1005
+ - 1 indicates the head is **not masked**,
1006
+ - 0 indicates the head is **masked**.
1007
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1008
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1009
+ config.n_positions - 1]`.
1010
+
1011
+ [What are position IDs?](../glossary#position-ids)
1012
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1013
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1014
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1015
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1016
+
1017
+ Two formats are allowed:
1018
+ - a [`~cache_utils.Cache`] instance;
1019
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1020
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1021
+ cache format.
1022
+
1023
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1024
+ legacy cache format will be returned.
1025
+
1026
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1027
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1028
+ of shape `(batch_size, sequence_length)`.
1029
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1030
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1031
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1032
+ model's internal embedding lookup matrix.
1033
+ use_cache (`bool`, *optional*):
1034
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1035
+ `past_key_values`).
1036
+ output_attentions (`bool`, *optional*):
1037
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1038
+ tensors for more detail.
1039
+ output_hidden_states (`bool`, *optional*):
1040
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1041
+ more detail.
1042
+ return_dict (`bool`, *optional*):
1043
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1044
+ """
1045
+
1046
+
1047
+ @add_start_docstrings(
1048
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
1049
+ LLAMA_START_DOCSTRING,
1050
+ )
1051
+ class LlamaModel(LlamaPreTrainedModel):
1052
+ """
1053
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
1054
+
1055
+ Args:
1056
+ config: LlamaConfig
1057
+ """
1058
+
1059
+ def __init__(self, config: LlamaConfig):
1060
+ super().__init__(config)
1061
+ self.padding_idx = config.pad_token_id
1062
+ self.vocab_size = config.vocab_size
1063
+
1064
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1065
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
1066
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1067
+ self.gradient_checkpointing = False
1068
+
1069
+ # Register a causal mask to separate causal and padding mask creation. Merging happens in the attention class.
1070
+ # NOTE: This is not friendly with TorchScript, ONNX, ExportedProgram serialization for very large `max_position_embeddings`.
1071
+ causal_mask = torch.full((config.max_position_embeddings, config.max_position_embeddings), fill_value=True, dtype=torch.bool)
1072
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
1073
+ # Initialize weights and apply final processing
1074
+ self.post_init()
1075
+
1076
+ def get_input_embeddings(self):
1077
+ return self.embed_tokens
1078
+
1079
+ def set_input_embeddings(self, value):
1080
+ self.embed_tokens = value
1081
+
1082
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1083
+ def forward(
1084
+ self,
1085
+ input_ids: torch.LongTensor = None,
1086
+ attention_mask: Optional[torch.Tensor] = None,
1087
+ position_ids: Optional[torch.LongTensor] = None,
1088
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1089
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1090
+ use_cache: Optional[bool] = None,
1091
+ output_attentions: Optional[bool] = None,
1092
+ output_hidden_states: Optional[bool] = None,
1093
+ return_dict: Optional[bool] = None,
1094
+ cache_position: Optional[torch.LongTensor] = None,
1095
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1096
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1097
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1098
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1099
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1100
+
1101
+ if (input_ids is None) ^ (inputs_embeds is not None):
1102
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one")
1103
+
1104
+ if self.gradient_checkpointing and self.training and use_cache:
1105
+ logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.")
1106
+ use_cache = False
1107
+
1108
+ if inputs_embeds is None:
1109
+ inputs_embeds = self.embed_tokens(input_ids)
1110
+
1111
+ past_seen_tokens = 0
1112
+ if use_cache: # kept for BC (cache positions)
1113
+ if not isinstance(past_key_values, StaticCache):
1114
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1115
+ past_seen_tokens = past_key_values.get_seq_length()
1116
+
1117
+ if cache_position is None:
1118
+ if isinstance(past_key_values, StaticCache):
1119
+ raise ValueError("cache_position is a required argument when using StaticCache.")
1120
+ cache_position = torch.arange(past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device)
1121
+
1122
+ if position_ids is None:
1123
+ position_ids = cache_position.unsqueeze(0)
1124
+
1125
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds)
1126
+
1127
+ # embed positions
1128
+ hidden_states = inputs_embeds
1129
+
1130
+ # decoder layers
1131
+ all_hidden_states = () if output_hidden_states else None
1132
+ all_self_attns = () if output_attentions else None
1133
+ next_decoder_cache = None
1134
+
1135
+ for decoder_layer in self.layers:
1136
+ if output_hidden_states:
1137
+ all_hidden_states += (hidden_states,)
1138
+
1139
+ if self.gradient_checkpointing and self.training:
1140
+ layer_outputs = self._gradient_checkpointing_func(
1141
+ decoder_layer.__call__,
1142
+ hidden_states,
1143
+ causal_mask,
1144
+ position_ids,
1145
+ past_key_values,
1146
+ output_attentions,
1147
+ use_cache,
1148
+ cache_position,
1149
+ )
1150
+ else:
1151
+ layer_outputs = decoder_layer(
1152
+ hidden_states,
1153
+ attention_mask=causal_mask,
1154
+ position_ids=position_ids,
1155
+ past_key_value=past_key_values,
1156
+ output_attentions=output_attentions,
1157
+ use_cache=use_cache,
1158
+ cache_position=cache_position,
1159
+ )
1160
+
1161
+ hidden_states = layer_outputs[0]
1162
+
1163
+ if use_cache:
1164
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1165
+
1166
+ if output_attentions:
1167
+ all_self_attns += (layer_outputs[1],)
1168
+
1169
+ hidden_states = self.norm(hidden_states)
1170
+
1171
+ # add hidden states from the last decoder layer
1172
+ if output_hidden_states:
1173
+ all_hidden_states += (hidden_states,)
1174
+
1175
+ next_cache = None
1176
+ if use_cache:
1177
+ next_cache = next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
1178
+ if not return_dict:
1179
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1180
+ return BaseModelOutputWithPast(
1181
+ last_hidden_state=hidden_states,
1182
+ past_key_values=next_cache,
1183
+ hidden_states=all_hidden_states,
1184
+ attentions=all_self_attns,
1185
+ )
1186
+
1187
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1188
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1189
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1190
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1191
+ def _update_causal_mask(self, attention_mask, input_tensor):
1192
+ if self.config._attn_implementation == "flash_attention_2":
1193
+ if attention_mask is not None and 0.0 in attention_mask:
1194
+ return attention_mask
1195
+ return None
1196
+
1197
+ batch_size, seq_length = input_tensor.shape[:2]
1198
+ dtype = input_tensor.dtype
1199
+ device = input_tensor.device
1200
+
1201
+ # support going beyond cached `max_position_embedding`
1202
+ if seq_length > self.causal_mask.shape[-1]:
1203
+ causal_mask = torch.full((2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]), fill_value=1)
1204
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
1205
+
1206
+ # We use the current dtype to avoid any overflows
1207
+ min_dtype = torch.finfo(dtype).min
1208
+ causal_mask = self.causal_mask[None, None, :, :].repeat(batch_size, 1, 1, 1).to(dtype) * min_dtype
1209
+
1210
+ causal_mask = causal_mask.to(dtype=dtype, device=device)
1211
+ if attention_mask is not None and attention_mask.dim() == 2:
1212
+ mask_length = attention_mask.shape[-1]
1213
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1214
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1215
+
1216
+ if self.config._attn_implementation == "sdpa" and attention_mask is not None and attention_mask.device.type == "cuda":
1217
+ # TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
1218
+ is_tracing = torch.jit.is_tracing() or isinstance(input_tensor, torch.fx.Proxy) or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling())
1219
+ if not is_tracing and torch.any(attention_mask != 1):
1220
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1221
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1222
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1223
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1224
+
1225
+ return causal_mask
1226
+
1227
+
1228
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1229
+ _tied_weights_keys = ["lm_head.weight"]
1230
+
1231
+ def __init__(self, config):
1232
+ super().__init__(config)
1233
+ self.model = LlamaModel(config)
1234
+ self.vocab_size = config.vocab_size
1235
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1236
+
1237
+ # Initialize weights and apply final processing
1238
+ self.post_init()
1239
+
1240
+ def get_input_embeddings(self):
1241
+ return self.model.embed_tokens
1242
+
1243
+ def set_input_embeddings(self, value):
1244
+ self.model.embed_tokens = value
1245
+
1246
+ def get_output_embeddings(self):
1247
+ return self.lm_head
1248
+
1249
+ def set_output_embeddings(self, new_embeddings):
1250
+ self.lm_head = new_embeddings
1251
+
1252
+ def set_decoder(self, decoder):
1253
+ self.model = decoder
1254
+
1255
+ def get_decoder(self):
1256
+ return self.model
1257
+
1258
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1259
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1260
+ def forward(
1261
+ self,
1262
+ input_ids: torch.LongTensor = None,
1263
+ attention_mask: Optional[torch.Tensor] = None,
1264
+ position_ids: Optional[torch.LongTensor] = None,
1265
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1266
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1267
+ labels: Optional[torch.LongTensor] = None,
1268
+ use_cache: Optional[bool] = None,
1269
+ output_attentions: Optional[bool] = None,
1270
+ output_hidden_states: Optional[bool] = None,
1271
+ return_dict: Optional[bool] = None,
1272
+ cache_position: Optional[torch.LongTensor] = None,
1273
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1274
+ r"""
1275
+ Args:
1276
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1277
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1278
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1279
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1280
+
1281
+ Returns:
1282
+
1283
+ Example:
1284
+
1285
+ ```python
1286
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1287
+
1288
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1289
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1290
+
1291
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1292
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1293
+
1294
+ >>> # Generate
1295
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1296
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1297
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1298
+ ```"""
1299
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1300
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1301
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1302
+
1303
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1304
+ outputs = self.model(
1305
+ input_ids=input_ids,
1306
+ attention_mask=attention_mask,
1307
+ position_ids=position_ids,
1308
+ past_key_values=past_key_values,
1309
+ inputs_embeds=inputs_embeds,
1310
+ use_cache=use_cache,
1311
+ output_attentions=output_attentions,
1312
+ output_hidden_states=output_hidden_states,
1313
+ return_dict=return_dict,
1314
+ cache_position=cache_position,
1315
+ )
1316
+
1317
+ hidden_states = outputs[0]
1318
+ if self.config.pretraining_tp > 1:
1319
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1320
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1321
+ logits = torch.cat(logits, dim=-1)
1322
+ else:
1323
+ logits = self.lm_head(hidden_states)
1324
+ logits = logits.float()
1325
+
1326
+ loss = None
1327
+ if labels is not None:
1328
+ # Shift so that tokens < n predict n
1329
+ shift_logits = logits[..., :-1, :].contiguous()
1330
+ shift_labels = labels[..., 1:].contiguous()
1331
+ # Flatten the tokens
1332
+ loss_fct = CrossEntropyLoss()
1333
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1334
+ shift_labels = shift_labels.view(-1)
1335
+ # Enable model parallelism
1336
+ shift_labels = shift_labels.to(shift_logits.device)
1337
+ loss = loss_fct(shift_logits, shift_labels)
1338
+
1339
+ if not return_dict:
1340
+ output = (logits,) + outputs[1:]
1341
+ return (loss,) + output if loss is not None else output
1342
+
1343
+ return CausalLMOutputWithPast(
1344
+ loss=loss,
1345
+ logits=logits,
1346
+ past_key_values=outputs.past_key_values,
1347
+ hidden_states=outputs.hidden_states,
1348
+ attentions=outputs.attentions,
1349
+ )
1350
+
1351
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs):
1352
+ past_length = 0
1353
+ if past_key_values is not None:
1354
+ if isinstance(past_key_values, Cache):
1355
+ cache_length = past_key_values.get_seq_length()
1356
+ past_length = past_key_values.seen_tokens
1357
+ max_cache_length = past_key_values.get_max_length()
1358
+ else:
1359
+ cache_length = past_length = past_key_values[0][0].shape[2]
1360
+ max_cache_length = None
1361
+
1362
+ # Keep only the unprocessed tokens:
1363
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1364
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1365
+ # input)
1366
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1367
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1368
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1369
+ # input_ids based on the past_length.
1370
+ elif past_length < input_ids.shape[1]:
1371
+ input_ids = input_ids[:, past_length:]
1372
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1373
+
1374
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1375
+ if max_cache_length is not None and attention_mask is not None and cache_length + input_ids.shape[1] > max_cache_length:
1376
+ attention_mask = attention_mask[:, -max_cache_length:]
1377
+
1378
+ position_ids = kwargs.get("position_ids", None)
1379
+ if attention_mask is not None and position_ids is None:
1380
+ # create position_ids on the fly for batch generation
1381
+ position_ids = attention_mask.long().cumsum(-1) - 1
1382
+ position_ids.masked_fill_(attention_mask == 0, 1)
1383
+ if past_key_values:
1384
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1385
+
1386
+ if self.generation_config.cache_implementation == "static":
1387
+ # generation with static cache
1388
+ cache_position = kwargs.get("cache_position", None)
1389
+ if cache_position is None:
1390
+ past_length = 0
1391
+ else:
1392
+ past_length = cache_position[-1] + 1
1393
+ input_ids = input_ids[:, past_length:]
1394
+ position_ids = position_ids[:, past_length:]
1395
+
1396
+ # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
1397
+ # same goes for position ids. Could also help with continued generation.
1398
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1399
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1400
+ position_ids = position_ids.contiguous() if position_ids is not None else None
1401
+
1402
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1403
+ if inputs_embeds is not None and past_key_values is None:
1404
+ model_inputs = {"inputs_embeds": inputs_embeds}
1405
+ else:
1406
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1407
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1408
+ # TODO: use `next_tokens` directly instead.
1409
+ model_inputs = {"input_ids": input_ids.contiguous()}
1410
+
1411
+ model_inputs.update(
1412
+ {
1413
+ "position_ids": position_ids,
1414
+ "cache_position": cache_position,
1415
+ "past_key_values": past_key_values,
1416
+ "use_cache": kwargs.get("use_cache"),
1417
+ "attention_mask": attention_mask,
1418
+ }
1419
+ )
1420
+ return model_inputs
1421
+
1422
+ @staticmethod
1423
+ def _reorder_cache(past_key_values, beam_idx):
1424
+ reordered_past = ()
1425
+ for layer_past in past_key_values:
1426
+ reordered_past += (tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),)
1427
+ return reordered_past
1428
+
1429
+
1430
+ @add_start_docstrings(
1431
+ """
1432
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1433
+
1434
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1435
+ (e.g. GPT-2) do.
1436
+
1437
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1438
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1439
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1440
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1441
+ each row of the batch).
1442
+ """,
1443
+ LLAMA_START_DOCSTRING,
1444
+ )
1445
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1446
+ def __init__(self, config):
1447
+ super().__init__(config)
1448
+ self.num_labels = config.num_labels
1449
+ self.model = LlamaModel(config)
1450
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1451
+
1452
+ # Initialize weights and apply final processing
1453
+ self.post_init()
1454
+
1455
+ def get_input_embeddings(self):
1456
+ return self.model.embed_tokens
1457
+
1458
+ def set_input_embeddings(self, value):
1459
+ self.model.embed_tokens = value
1460
+
1461
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1462
+ def forward(
1463
+ self,
1464
+ input_ids: torch.LongTensor = None,
1465
+ attention_mask: Optional[torch.Tensor] = None,
1466
+ position_ids: Optional[torch.LongTensor] = None,
1467
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1468
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1469
+ labels: Optional[torch.LongTensor] = None,
1470
+ use_cache: Optional[bool] = None,
1471
+ output_attentions: Optional[bool] = None,
1472
+ output_hidden_states: Optional[bool] = None,
1473
+ return_dict: Optional[bool] = None,
1474
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1475
+ r"""
1476
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1477
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1478
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1479
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1480
+ """
1481
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1482
+
1483
+ transformer_outputs = self.model(
1484
+ input_ids,
1485
+ attention_mask=attention_mask,
1486
+ position_ids=position_ids,
1487
+ past_key_values=past_key_values,
1488
+ inputs_embeds=inputs_embeds,
1489
+ use_cache=use_cache,
1490
+ output_attentions=output_attentions,
1491
+ output_hidden_states=output_hidden_states,
1492
+ return_dict=return_dict,
1493
+ )
1494
+ hidden_states = transformer_outputs[0]
1495
+ logits = self.score(hidden_states)
1496
+
1497
+ if input_ids is not None:
1498
+ batch_size = input_ids.shape[0]
1499
+ else:
1500
+ batch_size = inputs_embeds.shape[0]
1501
+
1502
+ if self.config.pad_token_id is None and batch_size != 1:
1503
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1504
+ if self.config.pad_token_id is None:
1505
+ sequence_lengths = -1
1506
+ else:
1507
+ if input_ids is not None:
1508
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1509
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1510
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1511
+ sequence_lengths = sequence_lengths.to(logits.device)
1512
+ else:
1513
+ sequence_lengths = -1
1514
+
1515
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1516
+
1517
+ loss = None
1518
+ if labels is not None:
1519
+ labels = labels.to(logits.device)
1520
+ if self.config.problem_type is None:
1521
+ if self.num_labels == 1:
1522
+ self.config.problem_type = "regression"
1523
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1524
+ self.config.problem_type = "single_label_classification"
1525
+ else:
1526
+ self.config.problem_type = "multi_label_classification"
1527
+
1528
+ if self.config.problem_type == "regression":
1529
+ loss_fct = MSELoss()
1530
+ if self.num_labels == 1:
1531
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1532
+ else:
1533
+ loss = loss_fct(pooled_logits, labels)
1534
+ elif self.config.problem_type == "single_label_classification":
1535
+ loss_fct = CrossEntropyLoss()
1536
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1537
+ elif self.config.problem_type == "multi_label_classification":
1538
+ loss_fct = BCEWithLogitsLoss()
1539
+ loss = loss_fct(pooled_logits, labels)
1540
+ if not return_dict:
1541
+ output = (pooled_logits,) + transformer_outputs[1:]
1542
+ return ((loss,) + output) if loss is not None else output
1543
+
1544
+ return SequenceClassifierOutputWithPast(
1545
+ loss=loss,
1546
+ logits=pooled_logits,
1547
+ past_key_values=transformer_outputs.past_key_values,
1548
+ hidden_states=transformer_outputs.hidden_states,
1549
+ attentions=transformer_outputs.attentions,
1550
+ )
1551
+
1552
+
1553
+ @add_start_docstrings(
1554
+ """
1555
+ The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
1556
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1557
+ """,
1558
+ LLAMA_START_DOCSTRING,
1559
+ )
1560
+ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1561
+ base_model_prefix = "transformer"
1562
+
1563
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
1564
+ def __init__(self, config):
1565
+ super().__init__(config)
1566
+ self.transformer = LlamaModel(config)
1567
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1568
+
1569
+ # Initialize weights and apply final processing
1570
+ self.post_init()
1571
+
1572
+ def get_input_embeddings(self):
1573
+ return self.transformer.embed_tokens
1574
+
1575
+ def set_input_embeddings(self, value):
1576
+ self.transformer.embed_tokens = value
1577
+
1578
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1579
+ def forward(
1580
+ self,
1581
+ input_ids: Optional[torch.LongTensor] = None,
1582
+ attention_mask: Optional[torch.FloatTensor] = None,
1583
+ position_ids: Optional[torch.LongTensor] = None,
1584
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1585
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1586
+ start_positions: Optional[torch.LongTensor] = None,
1587
+ end_positions: Optional[torch.LongTensor] = None,
1588
+ output_attentions: Optional[bool] = None,
1589
+ output_hidden_states: Optional[bool] = None,
1590
+ return_dict: Optional[bool] = None,
1591
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1592
+ r"""
1593
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1594
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1595
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1596
+ are not taken into account for computing the loss.
1597
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1598
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1599
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1600
+ are not taken into account for computing the loss.
1601
+ """
1602
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1603
+
1604
+ outputs = self.transformer(
1605
+ input_ids,
1606
+ attention_mask=attention_mask,
1607
+ position_ids=position_ids,
1608
+ past_key_values=past_key_values,
1609
+ inputs_embeds=inputs_embeds,
1610
+ output_attentions=output_attentions,
1611
+ output_hidden_states=output_hidden_states,
1612
+ return_dict=return_dict,
1613
+ )
1614
+
1615
+ sequence_output = outputs[0]
1616
+
1617
+ logits = self.qa_outputs(sequence_output)
1618
+ start_logits, end_logits = logits.split(1, dim=-1)
1619
+ start_logits = start_logits.squeeze(-1).contiguous()
1620
+ end_logits = end_logits.squeeze(-1).contiguous()
1621
+
1622
+ total_loss = None
1623
+ if start_positions is not None and end_positions is not None:
1624
+ # If we are on multi-GPU, split add a dimension
1625
+ if len(start_positions.size()) > 1:
1626
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1627
+ if len(end_positions.size()) > 1:
1628
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1629
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1630
+ ignored_index = start_logits.size(1)
1631
+ start_positions = start_positions.clamp(0, ignored_index)
1632
+ end_positions = end_positions.clamp(0, ignored_index)
1633
+
1634
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1635
+ start_loss = loss_fct(start_logits, start_positions)
1636
+ end_loss = loss_fct(end_logits, end_positions)
1637
+ total_loss = (start_loss + end_loss) / 2
1638
+
1639
+ if not return_dict:
1640
+ output = (start_logits, end_logits) + outputs[2:]
1641
+ return ((total_loss,) + output) if total_loss is not None else output
1642
+
1643
+ return QuestionAnsweringModelOutput(
1644
+ loss=total_loss,
1645
+ start_logits=start_logits,
1646
+ end_logits=end_logits,
1647
+ hidden_states=outputs.hidden_states,
1648
+ attentions=outputs.attentions,
1649
+ )
LLaVA-NeXT/llava/model/multimodal_encoder/builder.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .clip_encoder import CLIPVisionTower
3
+ from .imagebind import ImageBindWrapper
4
+ from .open_clip_encoder import OpenCLIPVisionTower
5
+ from .hf_vision import HFVisionTower
6
+ from .siglip_encoder import SigLipVisionTower
7
+ from .clip_encoder import CLIPVisionTower, CLIPVisionTowerS2
8
+ from .mlcd_encoder import MLCDVisionTower, MLCDVisionTowerS2
9
+ # from .eva_clip.eva_clip_encoder import EvaClipVisionTower
10
+ # from .dev_eva_clip.eva_vit import EvaViTWrapper
11
+
12
+
13
+ def build_vision_tower(vision_tower_cfg, **kwargs):
14
+ vision_tower = getattr(vision_tower_cfg, "mm_vision_tower", getattr(vision_tower_cfg, "vision_tower", None))
15
+ is_absolute_path_exists = os.path.exists(vision_tower)
16
+ use_s2 = getattr(vision_tower_cfg, "s2", False)
17
+ if is_absolute_path_exists or vision_tower.startswith("openai") or vision_tower.startswith("laion") or "ShareGPT4V" in vision_tower:
18
+ if use_s2:
19
+ return CLIPVisionTowerS2(vision_tower, args=vision_tower_cfg, **kwargs)
20
+ else:
21
+ return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
22
+ elif "siglip" in vision_tower:
23
+ return SigLipVisionTower(vision_tower, vision_tower_cfg=vision_tower_cfg, **kwargs)
24
+ elif vision_tower.startswith("hf:"):
25
+ return HFVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
26
+ elif vision_tower in ["imagebind_huge"]:
27
+ return ImageBindWrapper(vision_tower, args=vision_tower_cfg, **kwargs)
28
+ elif vision_tower.startswith("open_clip_hub"):
29
+ return OpenCLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
30
+ elif "mlcd-vit-bigG-patch14" in vision_tower:
31
+ if use_s2:
32
+ return MLCDVisionTowerS2(vision_tower, args=vision_tower_cfg, **kwargs)
33
+ else:
34
+ return MLCDVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
35
+
36
+ # elif "internal-eva" in vision_tower.lower() or "eva02" in vision_tower.lower():
37
+ # return EvaClipVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
38
+ # elif vision_tower in ["EVA-CLIP-8B", "EVA-CLIP-8B-plus"]:
39
+ # return EvaViTWrapper(vision_tower, args=vision_tower_cfg, **kwargs)
40
+
41
+ raise ValueError(f"Unknown vision tower: {vision_tower}")
LLaVA-NeXT/llava/model/multimodal_encoder/clip_encoder.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from llava.utils import rank0_print
4
+ from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
5
+
6
+ try:
7
+ from s2wrapper import forward as multiscale_forward
8
+ except:
9
+ pass
10
+
11
+
12
+ class CLIPVisionTower(nn.Module):
13
+ def __init__(self, vision_tower, args, delay_load=False):
14
+ super().__init__()
15
+
16
+ self.is_loaded = False
17
+
18
+ self.vision_tower_name = vision_tower
19
+ self.select_layer = args.mm_vision_select_layer
20
+ self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
21
+
22
+ if not delay_load:
23
+ rank0_print(f"Loading vision tower: {vision_tower}")
24
+ self.load_model()
25
+ elif getattr(args, "unfreeze_mm_vision_tower", False):
26
+ # TODO: better detector is needed.
27
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
28
+ self.load_model()
29
+ elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts:
30
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
31
+ self.load_model()
32
+ else:
33
+ self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
34
+
35
+ def load_model(self, device_map=None):
36
+ if self.is_loaded:
37
+ rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
38
+ return
39
+
40
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
41
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
42
+ self.vision_tower.requires_grad_(False)
43
+
44
+ self.is_loaded = True
45
+
46
+ def feature_select(self, image_forward_outs):
47
+ select_feature_type = self.select_feature
48
+
49
+ if self.select_feature in ["slicefour_patch", "slicefour_cls_patch"]:
50
+ select_every_k_layer = len(image_forward_outs.hidden_states) // 4
51
+ image_features = torch.cat([image_forward_outs.hidden_states[i] for i in range(select_every_k_layer + self.select_layer, len(image_forward_outs.hidden_states), select_every_k_layer)], dim=-1)
52
+ select_feature_type = select_feature_type.replace("slicefour_", "")
53
+ elif self.select_feature in ["slice_m25811_f6_patch", "slice_m25811_f6_cls_patch"]:
54
+ select_layers = [-2, -5, -8, -11, 6]
55
+ image_features = torch.cat([image_forward_outs.hidden_states[i] for i in select_layers], dim=-1)
56
+ select_feature_type = select_feature_type.replace("slice_m25811_f6_", "")
57
+ else:
58
+ image_features = image_forward_outs.hidden_states[self.select_layer]
59
+
60
+ if select_feature_type == "patch":
61
+ image_features = image_features[:, 1:]
62
+ elif select_feature_type == "cls_patch":
63
+ image_features = image_features
64
+ else:
65
+ raise ValueError(f"Unexpected select feature: {select_feature_type}")
66
+ return image_features
67
+
68
+ def forward(self, images):
69
+ if type(images) is list:
70
+ image_features = []
71
+ for image in images:
72
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
73
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
74
+ image_features.append(image_feature)
75
+ else:
76
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
77
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
78
+
79
+ return image_features
80
+
81
+ @property
82
+ def dummy_feature(self):
83
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
84
+
85
+ @property
86
+ def dtype(self):
87
+ return self.vision_tower.dtype
88
+
89
+ @property
90
+ def device(self):
91
+ return self.vision_tower.device
92
+
93
+ @property
94
+ def config(self):
95
+ if self.is_loaded:
96
+ return self.vision_tower.config
97
+ else:
98
+ return self.cfg_only
99
+
100
+ @property
101
+ def hidden_size(self):
102
+ _hidden_size = self.config.hidden_size
103
+ if "slicefour" in self.select_feature:
104
+ _hidden_size *= 4
105
+ if "slice_m25811_f6" in self.select_feature:
106
+ _hidden_size *= 5
107
+ return _hidden_size
108
+
109
+ @property
110
+ def num_patches_per_side(self):
111
+ return self.config.image_size // self.config.patch_size
112
+
113
+ @property
114
+ def num_patches(self):
115
+ _num_patches = (self.config.image_size // self.config.patch_size) ** 2
116
+ if "cls_patch" in self.select_feature:
117
+ _num_patches += 1
118
+ return _num_patches
119
+
120
+ @property
121
+ def image_size(self):
122
+ return self.config.image_size
123
+
124
+
125
+ class CLIPVisionTowerS2(CLIPVisionTower):
126
+ def __init__(self, vision_tower, args, delay_load=False):
127
+
128
+ self.s2_scales = getattr(args, "s2_scales", "336,672,1008")
129
+ self.s2_scales = list(map(int, self.s2_scales.split(",")))
130
+ self.s2_scales.sort()
131
+ self.s2_split_size = self.s2_scales[0]
132
+ self.s2_image_size = self.s2_scales[-1]
133
+
134
+ super().__init__(vision_tower, args, delay_load)
135
+
136
+ # change resize/crop size in preprocessing to the largest image size in s2_scale
137
+ if not delay_load or getattr(args, "unfreeze_mm_vision_tower", False):
138
+ self.image_processor.size["shortest_edge"] = self.s2_image_size
139
+ self.image_processor.crop_size["height"] = self.image_processor.crop_size["width"] = self.s2_image_size
140
+
141
+ def load_model(self, device_map=None):
142
+ if self.is_loaded:
143
+ rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
144
+ return
145
+
146
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
147
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name, device_map=device_map)
148
+ self.vision_tower.requires_grad_(False)
149
+
150
+ self.image_processor.size["shortest_edge"] = self.s2_image_size
151
+ self.image_processor.crop_size["height"] = self.image_processor.crop_size["width"] = self.s2_image_size
152
+
153
+ self.is_loaded = True
154
+
155
+ def forward_feature(self, images):
156
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
157
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
158
+ return image_features
159
+
160
+ def forward(self, images):
161
+ if type(images) is list:
162
+ image_features = []
163
+ for image in images:
164
+ image_feature = multiscale_forward(self.forward_feature, image.unsqueeze(0), img_sizes=self.s2_scales, max_split_size=self.s2_split_size, split_forward=True)
165
+ image_features.append(image_feature)
166
+ else:
167
+ image_features = multiscale_forward(self.forward_feature, images, img_sizes=self.s2_scales, max_split_size=self.s2_split_size, split_forward=True)
168
+
169
+ return image_features
170
+
171
+ @property
172
+ def hidden_size(self):
173
+ return self.config.hidden_size * len(self.s2_scales)
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
2
+ from .factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer
3
+ from .factory import list_models, add_model_config, get_model_config, load_checkpoint
4
+ from .loss import ClipLoss
5
+ from .model import CLIP, CustomCLIP, CLIPTextCfg, CLIPVisionCfg, convert_weights_to_lp, convert_weights_to_fp16, trace_model, get_cast_dtype
6
+ from .openai import load_openai_model, list_openai_models
7
+ from .pretrained import list_pretrained, list_pretrained_models_by_tag, list_pretrained_tags_by_model, get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained
8
+ from .tokenizer import SimpleTokenizer, tokenize
9
+ from .transform import image_transform
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/constants.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)
2
+ OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711)
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/eva_vit_model.py ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Adapted from https://github.com/microsoft/unilm/tree/master/beit
3
+ # --------------------------------------------------------
4
+ import math
5
+ import os
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ try:
11
+ from timm.models.layers import drop_path, to_2tuple, trunc_normal_
12
+ except:
13
+ from timm.layers import drop_path, to_2tuple, trunc_normal_
14
+
15
+ from .transformer import PatchDropout
16
+ from .rope import VisionRotaryEmbedding, VisionRotaryEmbeddingFast
17
+
18
+ if os.getenv("ENV_TYPE") == "deepspeed":
19
+ try:
20
+ from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint
21
+ except:
22
+ from torch.utils.checkpoint import checkpoint
23
+ else:
24
+ from torch.utils.checkpoint import checkpoint
25
+
26
+ try:
27
+ import xformers.ops as xops
28
+ except ImportError:
29
+ xops = None
30
+ # print("Please 'pip install xformers'")
31
+
32
+
33
+ class DropPath(nn.Module):
34
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
35
+
36
+ def __init__(self, drop_prob=None):
37
+ super(DropPath, self).__init__()
38
+ self.drop_prob = drop_prob
39
+
40
+ def forward(self, x):
41
+ return drop_path(x, self.drop_prob, self.training)
42
+
43
+ def extra_repr(self) -> str:
44
+ return "p={}".format(self.drop_prob)
45
+
46
+
47
+ class Mlp(nn.Module):
48
+ def __init__(
49
+ self,
50
+ in_features,
51
+ hidden_features=None,
52
+ out_features=None,
53
+ act_layer=nn.GELU,
54
+ norm_layer=nn.LayerNorm,
55
+ drop=0.0,
56
+ subln=False,
57
+ ):
58
+ super().__init__()
59
+ out_features = out_features or in_features
60
+ hidden_features = hidden_features or in_features
61
+ self.fc1 = nn.Linear(in_features, hidden_features)
62
+ self.act = act_layer()
63
+
64
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
65
+
66
+ self.fc2 = nn.Linear(hidden_features, out_features)
67
+ self.drop = nn.Dropout(drop)
68
+
69
+ def forward(self, x):
70
+ x = self.fc1(x)
71
+ x = self.act(x)
72
+ # x = self.drop(x)
73
+ # commit this for the orignal BERT implement
74
+ x = self.ffn_ln(x)
75
+
76
+ x = self.fc2(x)
77
+ x = self.drop(x)
78
+ return x
79
+
80
+
81
+ class SwiGLU(nn.Module):
82
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0, norm_layer=nn.LayerNorm, subln=False):
83
+ super().__init__()
84
+ out_features = out_features or in_features
85
+ hidden_features = hidden_features or in_features
86
+
87
+ self.w1 = nn.Linear(in_features, hidden_features)
88
+ self.w2 = nn.Linear(in_features, hidden_features)
89
+
90
+ self.act = act_layer()
91
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
92
+ self.w3 = nn.Linear(hidden_features, out_features)
93
+
94
+ self.drop = nn.Dropout(drop)
95
+
96
+ def forward(self, x):
97
+ x1 = self.w1(x)
98
+ x2 = self.w2(x)
99
+ hidden = self.act(x1) * x2
100
+ x = self.ffn_ln(hidden)
101
+ x = self.w3(x)
102
+ x = self.drop(x)
103
+ return x
104
+
105
+
106
+ class Attention(nn.Module):
107
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, window_size=None, attn_head_dim=None, xattn=False, rope=None, subln=False, norm_layer=nn.LayerNorm):
108
+ super().__init__()
109
+ self.num_heads = num_heads
110
+ head_dim = dim // num_heads
111
+ if attn_head_dim is not None:
112
+ head_dim = attn_head_dim
113
+ all_head_dim = head_dim * self.num_heads
114
+ self.scale = qk_scale or head_dim**-0.5
115
+
116
+ self.subln = subln
117
+ if self.subln:
118
+ self.q_proj = nn.Linear(dim, all_head_dim, bias=False)
119
+ self.k_proj = nn.Linear(dim, all_head_dim, bias=False)
120
+ self.v_proj = nn.Linear(dim, all_head_dim, bias=False)
121
+ else:
122
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
123
+
124
+ if qkv_bias:
125
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
126
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
127
+ else:
128
+ self.q_bias = None
129
+ self.v_bias = None
130
+
131
+ if window_size:
132
+ self.window_size = window_size
133
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
134
+ self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
135
+ # cls to token & token 2 cls & cls to cls
136
+
137
+ # get pair-wise relative position index for each token inside the window
138
+ coords_h = torch.arange(window_size[0])
139
+ coords_w = torch.arange(window_size[1])
140
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
141
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
142
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
143
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
144
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
145
+ relative_coords[:, :, 1] += window_size[1] - 1
146
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
147
+ relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
148
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
149
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
150
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
151
+ relative_position_index[0, 0] = self.num_relative_distance - 1
152
+
153
+ self.register_buffer("relative_position_index", relative_position_index)
154
+ else:
155
+ self.window_size = None
156
+ self.relative_position_bias_table = None
157
+ self.relative_position_index = None
158
+
159
+ self.attn_drop = nn.Dropout(attn_drop)
160
+ self.inner_attn_ln = norm_layer(all_head_dim) if subln else nn.Identity()
161
+ # self.proj = nn.Linear(all_head_dim, all_head_dim)
162
+ self.proj = nn.Linear(all_head_dim, dim)
163
+ self.proj_drop = nn.Dropout(proj_drop)
164
+ self.xattn = xattn
165
+ self.xattn_drop = attn_drop
166
+
167
+ self.rope = rope
168
+
169
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
170
+ B, N, C = x.shape
171
+ if self.subln:
172
+ q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
173
+ k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
174
+ v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
175
+
176
+ q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C
177
+ k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
178
+ v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
179
+ else:
180
+
181
+ qkv_bias = None
182
+ if self.q_bias is not None:
183
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
184
+
185
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
186
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C
187
+ q, k, v = qkv[0], qkv[1], qkv[2]
188
+
189
+ if self.rope:
190
+ # slightly fast impl
191
+ q_t = q[:, :, 1:, :]
192
+ ro_q_t = self.rope(q_t)
193
+ q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v)
194
+
195
+ k_t = k[:, :, 1:, :]
196
+ ro_k_t = self.rope(k_t)
197
+ k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v)
198
+
199
+ if self.xattn:
200
+ q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C
201
+ k = k.permute(0, 2, 1, 3)
202
+ v = v.permute(0, 2, 1, 3)
203
+
204
+ x = xops.memory_efficient_attention(
205
+ q,
206
+ k,
207
+ v,
208
+ p=self.xattn_drop,
209
+ scale=self.scale,
210
+ )
211
+ x = x.reshape(B, N, -1)
212
+ x = self.inner_attn_ln(x)
213
+ x = self.proj(x)
214
+ x = self.proj_drop(x)
215
+ else:
216
+ q = q * self.scale
217
+ attn = q @ k.transpose(-2, -1)
218
+
219
+ if self.relative_position_bias_table is not None:
220
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
221
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
222
+ attn = attn + relative_position_bias.unsqueeze(0).type_as(attn)
223
+
224
+ if rel_pos_bias is not None:
225
+ attn = attn + rel_pos_bias.type_as(attn)
226
+
227
+ if attn_mask is not None:
228
+ attn_mask = attn_mask.bool()
229
+ attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf"))
230
+
231
+ attn = attn.softmax(dim=-1)
232
+ attn = self.attn_drop(attn)
233
+
234
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
235
+ x = self.inner_attn_ln(x)
236
+ x = self.proj(x)
237
+ x = self.proj_drop(x)
238
+ return x
239
+
240
+
241
+ class Block(nn.Module):
242
+
243
+ def __init__(
244
+ self,
245
+ dim,
246
+ num_heads,
247
+ mlp_ratio=4.0,
248
+ qkv_bias=False,
249
+ qk_scale=None,
250
+ drop=0.0,
251
+ attn_drop=0.0,
252
+ drop_path=0.0,
253
+ init_values=None,
254
+ act_layer=nn.GELU,
255
+ norm_layer=nn.LayerNorm,
256
+ window_size=None,
257
+ attn_head_dim=None,
258
+ xattn=False,
259
+ rope=None,
260
+ postnorm=False,
261
+ subln=False,
262
+ naiveswiglu=False,
263
+ ):
264
+ super().__init__()
265
+ self.norm1 = norm_layer(dim)
266
+ self.attn = Attention(
267
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim, xattn=xattn, rope=rope, subln=subln, norm_layer=norm_layer
268
+ )
269
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
270
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
271
+ self.norm2 = norm_layer(dim)
272
+ mlp_hidden_dim = int(dim * mlp_ratio)
273
+
274
+ if naiveswiglu:
275
+ self.mlp = SwiGLU(
276
+ in_features=dim,
277
+ hidden_features=mlp_hidden_dim,
278
+ subln=subln,
279
+ norm_layer=norm_layer,
280
+ )
281
+ else:
282
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, subln=subln, drop=drop)
283
+
284
+ if init_values is not None and init_values > 0:
285
+ self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
286
+ self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
287
+ else:
288
+ self.gamma_1, self.gamma_2 = None, None
289
+
290
+ self.postnorm = postnorm
291
+
292
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
293
+ if self.gamma_1 is None:
294
+ if self.postnorm:
295
+ x = x + self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
296
+ x = x + self.drop_path(self.norm2(self.mlp(x)))
297
+ else:
298
+ x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
299
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
300
+ else:
301
+ if self.postnorm:
302
+ x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
303
+ x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x)))
304
+ else:
305
+ x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
306
+ x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
307
+ return x
308
+
309
+
310
+ class PatchEmbed(nn.Module):
311
+ """Image to Patch Embedding"""
312
+
313
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
314
+ super().__init__()
315
+ img_size = to_2tuple(img_size)
316
+ patch_size = to_2tuple(patch_size)
317
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
318
+ self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
319
+ self.img_size = img_size
320
+ self.patch_size = patch_size
321
+ self.num_patches = num_patches
322
+
323
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
324
+
325
+ def forward(self, x, **kwargs):
326
+ B, C, H, W = x.shape
327
+ # FIXME look at relaxing size constraints
328
+ assert H == self.img_size[0] and W == self.img_size[1], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
329
+ x = self.proj(x).flatten(2).transpose(1, 2)
330
+ return x
331
+
332
+
333
+ class RelativePositionBias(nn.Module):
334
+
335
+ def __init__(self, window_size, num_heads):
336
+ super().__init__()
337
+ self.window_size = window_size
338
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
339
+ self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
340
+ # cls to token & token 2 cls & cls to cls
341
+
342
+ # get pair-wise relative position index for each token inside the window
343
+ coords_h = torch.arange(window_size[0])
344
+ coords_w = torch.arange(window_size[1])
345
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
346
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
347
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
348
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
349
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
350
+ relative_coords[:, :, 1] += window_size[1] - 1
351
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
352
+ relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
353
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
354
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
355
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
356
+ relative_position_index[0, 0] = self.num_relative_distance - 1
357
+
358
+ self.register_buffer("relative_position_index", relative_position_index)
359
+
360
+ def forward(self):
361
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
362
+ return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
363
+
364
+
365
+ class EVAVisionTransformer(nn.Module):
366
+ """Vision Transformer with support for patch or hybrid CNN input stage"""
367
+
368
+ def __init__(
369
+ self,
370
+ img_size=224,
371
+ patch_size=16,
372
+ in_chans=3,
373
+ num_classes=1000,
374
+ embed_dim=768,
375
+ depth=12,
376
+ num_heads=12,
377
+ mlp_ratio=4.0,
378
+ qkv_bias=False,
379
+ qk_scale=None,
380
+ drop_rate=0.0,
381
+ attn_drop_rate=0.0,
382
+ drop_path_rate=0.0,
383
+ norm_layer=nn.LayerNorm,
384
+ init_values=None,
385
+ patch_dropout=0.0,
386
+ use_abs_pos_emb=True,
387
+ use_rel_pos_bias=False,
388
+ use_shared_rel_pos_bias=False,
389
+ rope=False,
390
+ use_mean_pooling=True,
391
+ init_scale=0.001,
392
+ grad_checkpointing=False,
393
+ xattn=False,
394
+ postnorm=False,
395
+ pt_hw_seq_len=16,
396
+ intp_freq=False,
397
+ naiveswiglu=False,
398
+ subln=False,
399
+ ):
400
+ super().__init__()
401
+ self.image_size = img_size
402
+ self.num_classes = num_classes
403
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
404
+
405
+ self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
406
+ num_patches = self.patch_embed.num_patches
407
+
408
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
409
+ # self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
410
+ if use_abs_pos_emb:
411
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
412
+ else:
413
+ self.pos_embed = None
414
+ self.pos_drop = nn.Dropout(p=drop_rate)
415
+
416
+ if use_shared_rel_pos_bias:
417
+ self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads)
418
+ else:
419
+ self.rel_pos_bias = None
420
+
421
+ if rope:
422
+ half_head_dim = embed_dim // num_heads // 2
423
+ hw_seq_len = img_size // patch_size
424
+ self.rope = VisionRotaryEmbeddingFast(
425
+ dim=half_head_dim,
426
+ pt_seq_len=pt_hw_seq_len,
427
+ ft_seq_len=hw_seq_len if intp_freq else None,
428
+ # patch_dropout=patch_dropout
429
+ )
430
+ else:
431
+ self.rope = None
432
+
433
+ self.naiveswiglu = naiveswiglu
434
+
435
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
436
+ self.use_rel_pos_bias = use_rel_pos_bias
437
+ self.blocks = nn.ModuleList(
438
+ [
439
+ Block(
440
+ dim=embed_dim,
441
+ num_heads=num_heads,
442
+ mlp_ratio=mlp_ratio,
443
+ qkv_bias=qkv_bias,
444
+ qk_scale=qk_scale,
445
+ drop=drop_rate,
446
+ attn_drop=attn_drop_rate,
447
+ drop_path=dpr[i],
448
+ norm_layer=norm_layer,
449
+ init_values=init_values,
450
+ window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None,
451
+ xattn=xattn,
452
+ rope=self.rope,
453
+ postnorm=postnorm,
454
+ subln=subln,
455
+ naiveswiglu=naiveswiglu,
456
+ )
457
+ for i in range(depth)
458
+ ]
459
+ )
460
+ self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
461
+ self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
462
+ self.head = nn.Linear(embed_dim, num_classes, bias=qkv_bias) if num_classes > 0 else nn.Identity()
463
+
464
+ if self.pos_embed is not None:
465
+ trunc_normal_(self.pos_embed, std=0.02)
466
+
467
+ trunc_normal_(self.cls_token, std=0.02)
468
+
469
+ self.apply(self._init_weights)
470
+ self.fix_init_weight()
471
+
472
+ if isinstance(self.head, nn.Linear):
473
+ trunc_normal_(self.head.weight, std=0.02)
474
+ self.head.weight.data.mul_(init_scale)
475
+ if self.head.bias is not None:
476
+ self.head.bias.data.mul_(init_scale)
477
+
478
+ # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn
479
+ self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0.0 else nn.Identity()
480
+
481
+ self.grad_checkpointing = grad_checkpointing
482
+
483
+ def fix_init_weight(self):
484
+ def rescale(param, layer_id):
485
+ param.div_(math.sqrt(2.0 * layer_id))
486
+
487
+ for layer_id, layer in enumerate(self.blocks):
488
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
489
+ if self.naiveswiglu:
490
+ rescale(layer.mlp.w3.weight.data, layer_id + 1)
491
+ else:
492
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
493
+
494
+ def get_cast_dtype(self) -> torch.dtype:
495
+ return self.blocks[0].mlp.fc2.weight.dtype
496
+
497
+ def _init_weights(self, m):
498
+ if isinstance(m, nn.Linear):
499
+ trunc_normal_(m.weight, std=0.02)
500
+ if m.bias is not None:
501
+ nn.init.constant_(m.bias, 0)
502
+ elif isinstance(m, nn.LayerNorm):
503
+ nn.init.constant_(m.bias, 0)
504
+ nn.init.constant_(m.weight, 1.0)
505
+
506
+ def get_num_layers(self):
507
+ return len(self.blocks)
508
+
509
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
510
+ assert unlocked_groups == 0, "partial locking not currently supported for this model"
511
+ for param in self.parameters():
512
+ param.requires_grad = False
513
+
514
+ @torch.jit.ignore
515
+ def set_grad_checkpointing(self, enable=True):
516
+ self.grad_checkpointing = enable
517
+
518
+ @torch.jit.ignore
519
+ def no_weight_decay(self):
520
+ return {"pos_embed", "cls_token"}
521
+
522
+ def get_classifier(self):
523
+ return self.head
524
+
525
+ def reset_classifier(self, num_classes, global_pool=""):
526
+ self.num_classes = num_classes
527
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
528
+
529
+ def forward_features(self, x, return_all_features=False):
530
+
531
+ x = self.patch_embed(x)
532
+ batch_size, seq_len, _ = x.size()
533
+
534
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
535
+ x = torch.cat((cls_tokens, x), dim=1)
536
+ if self.pos_embed is not None:
537
+ x = x + self.pos_embed
538
+ x = self.pos_drop(x)
539
+
540
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
541
+ # if os.getenv("RoPE") == "1":
542
+ # if self.training and not isinstance(self.patch_dropout, nn.Identity):
543
+ # x, patch_indices_keep = self.patch_dropout(x)
544
+ # self.rope.forward = partial(self.rope.forward, patch_indices_keep=patch_indices_keep)
545
+ # else:
546
+ # self.rope.forward = partial(self.rope.forward, patch_indices_keep=None)
547
+ # x = self.patch_dropout(x)
548
+ # else:
549
+ x = self.patch_dropout(x)
550
+
551
+ rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
552
+ for blk in self.blocks:
553
+ if self.grad_checkpointing:
554
+ x = checkpoint(blk, x, (rel_pos_bias,))
555
+ else:
556
+ x = blk(x, rel_pos_bias=rel_pos_bias)
557
+
558
+ if not return_all_features:
559
+ x = self.norm(x)
560
+ if self.fc_norm is not None:
561
+ return self.fc_norm(x.mean(1))
562
+ else:
563
+ return x[:, 0]
564
+ return x
565
+
566
+ def forward(self, x, return_all_features=False):
567
+ if return_all_features:
568
+ return self.forward_features(x, return_all_features)
569
+ x = self.forward_features(x)
570
+ x = self.head(x)
571
+ return x
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/factory.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ import pathlib
5
+ import re
6
+ from copy import deepcopy
7
+ from pathlib import Path
8
+ from typing import Optional, Tuple, Union, Dict, Any
9
+ import torch
10
+
11
+ try:
12
+ import deepspeed
13
+ except ImportError:
14
+ deepspeed = None
15
+
16
+ from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
17
+ from .model import CLIP, CustomCLIP, convert_weights_to_lp, convert_to_custom_text_state_dict, get_cast_dtype
18
+ from .openai import load_openai_model
19
+ from .pretrained import is_pretrained_cfg, get_pretrained_cfg, download_pretrained, list_pretrained_tags_by_model
20
+ from .transform import image_transform
21
+ from .tokenizer import HFTokenizer, tokenize
22
+ from .utils import resize_clip_pos_embed, resize_evaclip_pos_embed, resize_visual_pos_embed, resize_eva_pos_embed
23
+
24
+
25
+ _MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"]
26
+ _MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs
27
+
28
+
29
+ def _natural_key(string_):
30
+ return [int(s) if s.isdigit() else s for s in re.split(r"(\d+)", string_.lower())]
31
+
32
+
33
+ def _rescan_model_configs():
34
+ global _MODEL_CONFIGS
35
+
36
+ config_ext = (".json",)
37
+ config_files = []
38
+ for config_path in _MODEL_CONFIG_PATHS:
39
+ if config_path.is_file() and config_path.suffix in config_ext:
40
+ config_files.append(config_path)
41
+ elif config_path.is_dir():
42
+ for ext in config_ext:
43
+ config_files.extend(config_path.glob(f"*{ext}"))
44
+
45
+ for cf in config_files:
46
+ with open(cf, "r", encoding="utf8") as f:
47
+ model_cfg = json.load(f)
48
+ if all(a in model_cfg for a in ("embed_dim", "vision_cfg", "text_cfg")):
49
+ _MODEL_CONFIGS[cf.stem] = model_cfg
50
+
51
+ _MODEL_CONFIGS = dict(sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0])))
52
+
53
+
54
+ _rescan_model_configs() # initial populate of model config registry
55
+
56
+
57
+ def list_models():
58
+ """enumerate available model architectures based on config files"""
59
+ return list(_MODEL_CONFIGS.keys())
60
+
61
+
62
+ def add_model_config(path):
63
+ """add model config path or file and update registry"""
64
+ if not isinstance(path, Path):
65
+ path = Path(path)
66
+ _MODEL_CONFIG_PATHS.append(path)
67
+ _rescan_model_configs()
68
+
69
+
70
+ def get_model_config(model_name):
71
+ if model_name in _MODEL_CONFIGS:
72
+ return deepcopy(_MODEL_CONFIGS[model_name])
73
+ else:
74
+ return None
75
+
76
+
77
+ def get_tokenizer(model_name):
78
+ config = get_model_config(model_name)
79
+ tokenizer = HFTokenizer(config["text_cfg"]["hf_tokenizer_name"]) if "hf_tokenizer_name" in config["text_cfg"] else tokenize
80
+ return tokenizer
81
+
82
+
83
+ # loading openai CLIP weights when is_openai=True for training
84
+ def load_state_dict(checkpoint_path: str, map_location: str = "cpu", model_key: str = "model|module|state_dict", is_openai: bool = False, skip_list: list = []):
85
+ if is_openai:
86
+ model = torch.jit.load(checkpoint_path, map_location="cpu").eval()
87
+ state_dict = model.state_dict()
88
+ for key in ["input_resolution", "context_length", "vocab_size"]:
89
+ state_dict.pop(key, None)
90
+ else:
91
+ checkpoint = torch.load(checkpoint_path, map_location=map_location)
92
+ for mk in model_key.split("|"):
93
+ if isinstance(checkpoint, dict) and mk in checkpoint:
94
+ state_dict = checkpoint[mk]
95
+ break
96
+ else:
97
+ state_dict = checkpoint
98
+ if next(iter(state_dict.items()))[0].startswith("module"):
99
+ state_dict = {k[7:]: v for k, v in state_dict.items()}
100
+
101
+ for k in skip_list:
102
+ if k in list(state_dict.keys()):
103
+ logging.info(f"Removing key {k} from pretrained checkpoint")
104
+ del state_dict[k]
105
+
106
+ if os.getenv("RoPE") == "1":
107
+ for k in list(state_dict.keys()):
108
+ if "freqs_cos" in k or "freqs_sin" in k:
109
+ del state_dict[k]
110
+ return state_dict
111
+
112
+
113
+ def load_checkpoint(model, checkpoint_path, model_key="model|module|state_dict", strict=True):
114
+ state_dict = load_state_dict(checkpoint_path, model_key=model_key, is_openai=False)
115
+ # detect old format and make compatible with new format
116
+ if "positional_embedding" in state_dict and not hasattr(model, "positional_embedding"):
117
+ state_dict = convert_to_custom_text_state_dict(state_dict)
118
+ if "text.logit_scale" in state_dict and hasattr(model, "logit_scale"):
119
+ state_dict["logit_scale"] = state_dict["text.logit_scale"]
120
+ del state_dict["text.logit_scale"]
121
+
122
+ # resize_clip_pos_embed for CLIP and open CLIP
123
+ if "visual.positional_embedding" in state_dict:
124
+ resize_clip_pos_embed(state_dict, model)
125
+ # specified to eva_vit_model
126
+ elif "visual.pos_embed" in state_dict:
127
+ resize_evaclip_pos_embed(state_dict, model)
128
+
129
+ # resize_clip_pos_embed(state_dict, model)
130
+ incompatible_keys = model.load_state_dict(state_dict, strict=strict)
131
+ logging.info(f"incompatible_keys.missing_keys: {incompatible_keys.missing_keys}")
132
+ return incompatible_keys
133
+
134
+
135
+ def load_clip_visual_state_dict(checkpoint_path: str, map_location: str = "cpu", is_openai: bool = False, skip_list: list = []):
136
+ state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list)
137
+
138
+ for k in list(state_dict.keys()):
139
+ if not k.startswith("visual."):
140
+ del state_dict[k]
141
+ for k in list(state_dict.keys()):
142
+ if k.startswith("visual."):
143
+ new_k = k[7:]
144
+ state_dict[new_k] = state_dict[k]
145
+ del state_dict[k]
146
+ return state_dict
147
+
148
+
149
+ def load_clip_text_state_dict(checkpoint_path: str, map_location: str = "cpu", is_openai: bool = False, skip_list: list = []):
150
+ state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list)
151
+
152
+ for k in list(state_dict.keys()):
153
+ if k.startswith("visual."):
154
+ del state_dict[k]
155
+ return state_dict
156
+
157
+
158
+ def get_pretrained_tag(pretrained_model):
159
+ pretrained_model = pretrained_model.lower()
160
+ if "laion" in pretrained_model or "open_clip" in pretrained_model:
161
+ return "open_clip"
162
+ elif "openai" in pretrained_model:
163
+ return "clip"
164
+ elif "eva" in pretrained_model and "clip" in pretrained_model:
165
+ return "eva_clip"
166
+ else:
167
+ return "other"
168
+
169
+
170
+ def load_zero_partitions(model, state_dict, is_deepspeed_zero3_enabled, pretrained_model_path, ignore_mismatched_sizes=False):
171
+ """
172
+ adept from pytorch lightning and transformers
173
+ with deepspeed.zero.Init():
174
+ model = MyModel()
175
+ state_dict = torch.load(model_path, map_location="cpu")
176
+ load_zero_partitions(model, prefix="")
177
+ """
178
+
179
+ # because zero3 puts placeholders in model params, this context
180
+ # manager gathers (unpartitions) the params of the current layer, then loads from
181
+ # the state dict and then re-partitions them again
182
+ model_state_dict = model.state_dict()
183
+ expected_keys = list(model_state_dict.keys())
184
+ loaded_keys = list(state_dict.keys())
185
+ missing_keys = list(set(expected_keys) - set(loaded_keys))
186
+ unexpected_keys = list(set(loaded_keys) - set(expected_keys))
187
+
188
+ # Mistmatched keys contains tuples key/shape1/shape2 of weights in the checkpoint that have a shape not
189
+ # matching the weights in the model.
190
+ mismatched_keys = []
191
+ if ignore_mismatched_sizes:
192
+ for checkpoint_key in loaded_keys:
193
+ model_key = checkpoint_key
194
+
195
+ if model_key in model_state_dict and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape:
196
+ mismatched_keys.append((checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape))
197
+ del state_dict[checkpoint_key]
198
+ # copy state_dict so _load_from_state_dict can modify it
199
+ metadata = getattr(state_dict, "_metadata", None)
200
+ state_dict = state_dict.copy()
201
+ if metadata is not None:
202
+ state_dict._metadata = metadata
203
+
204
+ error_msgs = []
205
+
206
+ # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
207
+ # so we need to apply the function recursively.
208
+ def load(module, prefix=""):
209
+ local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
210
+ args = (state_dict, prefix, local_metadata, True, [], [], error_msgs)
211
+ if is_deepspeed_zero3_enabled:
212
+ # because zero3 puts placeholders in model params, this context
213
+ # manager gathers (unpartitions) the params of the current layer, then loads from
214
+ # the state dict and then re-partitions them again
215
+ with deepspeed.zero.GatheredParameters(list(module.parameters(recurse=False)), modifier_rank=0):
216
+ if torch.distributed.get_rank() == 0:
217
+ module._load_from_state_dict(*args)
218
+ else:
219
+ module._load_from_state_dict(*args)
220
+
221
+ for name, child in module._modules.items():
222
+ if child is not None:
223
+ load(child, prefix + name + ".")
224
+
225
+ # Make sure we are able to load base models as well as derived models (with heads)
226
+ start_prefix = ""
227
+ model_to_load = model
228
+ load(model_to_load, prefix=start_prefix)
229
+ del state_dict
230
+ if len(error_msgs) > 0:
231
+ error_msg = "\n\t".join(error_msgs)
232
+ if "size mismatch" in error_msg:
233
+ error_msg += "\n\tYou may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method."
234
+ raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}")
235
+ if len(unexpected_keys) > 0:
236
+ logging.warning(
237
+ f"Some weights of the model checkpoint at {pretrained_model_path} were not used when"
238
+ f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
239
+ f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or"
240
+ " with another architecture (e.g. initializing a BertForSequenceClassification model from a"
241
+ " BertForPreTraining model).\n- This IS NOT expected if you are initializing"
242
+ f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly identical"
243
+ " (initializing a BertForSequenceClassification model from a BertForSequenceClassification model)."
244
+ )
245
+ else:
246
+ logging.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
247
+ if len(missing_keys) > 0:
248
+ logging.warning(
249
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
250
+ f" {pretrained_model_path} and are newly initialized: {missing_keys}\nYou should probably"
251
+ " TRAIN this model on a down-stream task to be able to use it for predictions and inference."
252
+ )
253
+ elif len(mismatched_keys) == 0:
254
+ logging.info(
255
+ f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
256
+ f" {pretrained_model_path}.\nIf your task is similar to the task the model of the checkpoint"
257
+ f" was trained on, you can already use {model.__class__.__name__} for predictions without further"
258
+ " training."
259
+ )
260
+ if len(mismatched_keys) > 0:
261
+ mismatched_warning = "\n".join([f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated" for key, shape1, shape2 in mismatched_keys])
262
+ logging.warning(
263
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
264
+ f" {pretrained_model_path} and are newly initialized because the shapes did not"
265
+ f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be able"
266
+ " to use it for predictions and inference."
267
+ )
268
+
269
+
270
+ def load_pretrained_checkpoint(model, visual_checkpoint_path, text_checkpoint_path, strict=True, visual_model=None, text_model=None, model_key="model|module|state_dict", skip_list=[]):
271
+ visual_tag = get_pretrained_tag(visual_model)
272
+ text_tag = get_pretrained_tag(text_model)
273
+
274
+ logging.info(f"num of model state_dict keys: {len(model.state_dict().keys())}")
275
+ visual_incompatible_keys, text_incompatible_keys = None, None
276
+ if visual_checkpoint_path:
277
+ if visual_tag == "eva_clip" or visual_tag == "open_clip":
278
+ visual_state_dict = load_clip_visual_state_dict(visual_checkpoint_path, is_openai=False, skip_list=skip_list)
279
+ elif visual_tag == "clip":
280
+ visual_state_dict = load_clip_visual_state_dict(visual_checkpoint_path, is_openai=True, skip_list=skip_list)
281
+ else:
282
+ visual_state_dict = load_state_dict(visual_checkpoint_path, model_key=model_key, is_openai=False, skip_list=skip_list)
283
+
284
+ # resize_clip_pos_embed for CLIP and open CLIP
285
+ if "positional_embedding" in visual_state_dict:
286
+ resize_visual_pos_embed(visual_state_dict, model)
287
+ # specified to EVA model
288
+ elif "pos_embed" in visual_state_dict:
289
+ resize_eva_pos_embed(visual_state_dict, model)
290
+
291
+ visual_incompatible_keys = model.visual.load_state_dict(visual_state_dict, strict=strict)
292
+ logging.info(f"num of loaded visual_state_dict keys: {len(visual_state_dict.keys())}")
293
+ logging.info(f"visual_incompatible_keys.missing_keys: {visual_incompatible_keys.missing_keys}")
294
+
295
+ if text_checkpoint_path:
296
+ if text_tag == "eva_clip" or text_tag == "open_clip":
297
+ text_state_dict = load_clip_text_state_dict(text_checkpoint_path, is_openai=False, skip_list=skip_list)
298
+ elif text_tag == "clip":
299
+ text_state_dict = load_clip_text_state_dict(text_checkpoint_path, is_openai=True, skip_list=skip_list)
300
+ else:
301
+ text_state_dict = load_state_dict(visual_checkpoint_path, model_key=model_key, is_openai=False, skip_list=skip_list)
302
+
303
+ text_incompatible_keys = model.text.load_state_dict(text_state_dict, strict=strict)
304
+
305
+ logging.info(f"num of loaded text_state_dict keys: {len(text_state_dict.keys())}")
306
+ logging.info(f"text_incompatible_keys.missing_keys: {text_incompatible_keys.missing_keys}")
307
+
308
+ return visual_incompatible_keys, text_incompatible_keys
309
+
310
+
311
+ def create_model(
312
+ model_name: str,
313
+ pretrained: Optional[str] = None,
314
+ precision: str = "fp32",
315
+ device: Union[str, torch.device] = "cpu",
316
+ jit: bool = False,
317
+ force_quick_gelu: bool = False,
318
+ force_custom_clip: bool = False,
319
+ force_patch_dropout: Optional[float] = None,
320
+ pretrained_image: str = "",
321
+ pretrained_text: str = "",
322
+ pretrained_hf: bool = True,
323
+ pretrained_visual_model: str = None,
324
+ pretrained_text_model: str = None,
325
+ cache_dir: Optional[str] = None,
326
+ skip_list: list = [],
327
+ ):
328
+ model_name = model_name.replace("/", "-") # for callers using old naming with / in ViT names
329
+ if isinstance(device, str):
330
+ device = torch.device(device)
331
+
332
+ if pretrained and pretrained.lower() == "openai":
333
+ logging.info(f"Loading pretrained {model_name} from OpenAI.")
334
+ model = load_openai_model(
335
+ model_name,
336
+ precision=precision,
337
+ device=device,
338
+ jit=jit,
339
+ cache_dir=cache_dir,
340
+ )
341
+ else:
342
+ model_cfg = get_model_config(model_name)
343
+ if model_cfg is not None:
344
+ logging.info(f"Loaded {model_name} model config.")
345
+ else:
346
+ logging.error(f"Model config for {model_name} not found; available models {list_models()}.")
347
+ raise RuntimeError(f"Model config for {model_name} not found.")
348
+
349
+ if "rope" in model_cfg.get("vision_cfg", {}):
350
+ if model_cfg["vision_cfg"]["rope"]:
351
+ os.environ["RoPE"] = "1"
352
+ else:
353
+ os.environ["RoPE"] = "0"
354
+
355
+ if force_quick_gelu:
356
+ # override for use of QuickGELU on non-OpenAI transformer models
357
+ model_cfg["quick_gelu"] = True
358
+
359
+ if force_patch_dropout is not None:
360
+ # override the default patch dropout value
361
+ model_cfg["vision_cfg"]["patch_dropout"] = force_patch_dropout
362
+
363
+ cast_dtype = get_cast_dtype(precision)
364
+ custom_clip = model_cfg.pop("custom_text", False) or force_custom_clip or ("hf_model_name" in model_cfg["text_cfg"])
365
+
366
+ if custom_clip:
367
+ if "hf_model_name" in model_cfg.get("text_cfg", {}):
368
+ model_cfg["text_cfg"]["hf_model_pretrained"] = pretrained_hf
369
+ model = CustomCLIP(**model_cfg, cast_dtype=cast_dtype)
370
+ else:
371
+ model = CLIP(**model_cfg, cast_dtype=cast_dtype)
372
+
373
+ pretrained_cfg = {}
374
+ if pretrained:
375
+ checkpoint_path = ""
376
+ pretrained_cfg = get_pretrained_cfg(model_name, pretrained)
377
+ if pretrained_cfg:
378
+ checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir)
379
+ elif os.path.exists(pretrained):
380
+ checkpoint_path = pretrained
381
+
382
+ if checkpoint_path:
383
+ logging.info(f"Loading pretrained {model_name} weights ({pretrained}).")
384
+ load_checkpoint(model, checkpoint_path, model_key="model|module|state_dict", strict=False)
385
+ else:
386
+ error_str = f"Pretrained weights ({pretrained}) not found for model {model_name}." f"Available pretrained tags ({list_pretrained_tags_by_model(model_name)}."
387
+ logging.warning(error_str)
388
+ raise RuntimeError(error_str)
389
+ else:
390
+ visual_checkpoint_path = ""
391
+ text_checkpoint_path = ""
392
+
393
+ if pretrained_image:
394
+ pretrained_visual_model = pretrained_visual_model.replace("/", "-") # for callers using old naming with / in ViT names
395
+ pretrained_image_cfg = get_pretrained_cfg(pretrained_visual_model, pretrained_image)
396
+ if "timm_model_name" in model_cfg.get("vision_cfg", {}):
397
+ # pretrained weight loading for timm models set via vision_cfg
398
+ model_cfg["vision_cfg"]["timm_model_pretrained"] = True
399
+ elif pretrained_image_cfg:
400
+ visual_checkpoint_path = download_pretrained(pretrained_image_cfg, cache_dir=cache_dir)
401
+ elif os.path.exists(pretrained_image):
402
+ visual_checkpoint_path = pretrained_image
403
+ else:
404
+ logging.warning(f"Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.")
405
+ raise RuntimeError(f"Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.")
406
+
407
+ if pretrained_text:
408
+ pretrained_text_model = pretrained_text_model.replace("/", "-") # for callers using old naming with / in ViT names
409
+ pretrained_text_cfg = get_pretrained_cfg(pretrained_text_model, pretrained_text)
410
+ if pretrained_image_cfg:
411
+ text_checkpoint_path = download_pretrained(pretrained_text_cfg, cache_dir=cache_dir)
412
+ elif os.path.exists(pretrained_text):
413
+ text_checkpoint_path = pretrained_text
414
+ else:
415
+ logging.warning(f"Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.")
416
+ raise RuntimeError(f"Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.")
417
+
418
+ if visual_checkpoint_path:
419
+ logging.info(f"Loading pretrained {model_name}.visual weights ({visual_checkpoint_path}).")
420
+ if text_checkpoint_path:
421
+ logging.info(f"Loading pretrained {model_name}.text weights ({text_checkpoint_path}).")
422
+
423
+ if visual_checkpoint_path or text_checkpoint_path:
424
+ load_pretrained_checkpoint(model, visual_checkpoint_path, text_checkpoint_path, strict=False, visual_model=pretrained_visual_model, text_model=pretrained_text_model, model_key="model|module|state_dict", skip_list=skip_list)
425
+
426
+ if "fp16" in precision or "bf16" in precision:
427
+ logging.info(f"convert precision to {precision}")
428
+ model = model.to(torch.bfloat16) if "bf16" in precision else model.to(torch.float16)
429
+
430
+ # model.to(device=device)
431
+
432
+ # set image / mean metadata from pretrained_cfg if available, or use default
433
+ model.visual.image_mean = pretrained_cfg.get("mean", None) or OPENAI_DATASET_MEAN
434
+ model.visual.image_std = pretrained_cfg.get("std", None) or OPENAI_DATASET_STD
435
+
436
+ if jit:
437
+ model = torch.jit.script(model)
438
+
439
+ return model
440
+
441
+
442
+ def create_model_and_transforms(
443
+ model_name: str,
444
+ pretrained: Optional[str] = None,
445
+ precision: str = "fp32",
446
+ device: Union[str, torch.device] = "cpu",
447
+ jit: bool = False,
448
+ force_quick_gelu: bool = False,
449
+ force_custom_clip: bool = False,
450
+ force_patch_dropout: Optional[float] = None,
451
+ pretrained_image: str = "",
452
+ pretrained_text: str = "",
453
+ pretrained_hf: bool = True,
454
+ pretrained_visual_model: str = None,
455
+ pretrained_text_model: str = None,
456
+ image_mean: Optional[Tuple[float, ...]] = None,
457
+ image_std: Optional[Tuple[float, ...]] = None,
458
+ cache_dir: Optional[str] = None,
459
+ skip_list: list = [],
460
+ ):
461
+ model = create_model(
462
+ model_name,
463
+ pretrained,
464
+ precision=precision,
465
+ device=device,
466
+ jit=jit,
467
+ force_quick_gelu=force_quick_gelu,
468
+ force_custom_clip=force_custom_clip,
469
+ force_patch_dropout=force_patch_dropout,
470
+ pretrained_image=pretrained_image,
471
+ pretrained_text=pretrained_text,
472
+ pretrained_hf=pretrained_hf,
473
+ pretrained_visual_model=pretrained_visual_model,
474
+ pretrained_text_model=pretrained_text_model,
475
+ cache_dir=cache_dir,
476
+ skip_list=skip_list,
477
+ )
478
+
479
+ image_mean = image_mean or getattr(model.visual, "image_mean", None)
480
+ image_std = image_std or getattr(model.visual, "image_std", None)
481
+ preprocess_train = image_transform(model.visual.image_size, is_train=True, mean=image_mean, std=image_std)
482
+ preprocess_val = image_transform(model.visual.image_size, is_train=False, mean=image_mean, std=image_std)
483
+
484
+ return model, preprocess_train, preprocess_val
485
+
486
+
487
+ def create_model_from_pretrained(
488
+ model_name: str,
489
+ pretrained: str,
490
+ precision: str = "fp32",
491
+ device: Union[str, torch.device] = "cpu",
492
+ jit: bool = False,
493
+ force_quick_gelu: bool = False,
494
+ force_custom_clip: bool = False,
495
+ force_patch_dropout: Optional[float] = None,
496
+ return_transform: bool = True,
497
+ image_mean: Optional[Tuple[float, ...]] = None,
498
+ image_std: Optional[Tuple[float, ...]] = None,
499
+ cache_dir: Optional[str] = None,
500
+ is_frozen: bool = False,
501
+ ):
502
+ if not is_pretrained_cfg(model_name, pretrained) and not os.path.exists(pretrained):
503
+ raise RuntimeError(f"{pretrained} is not a valid pretrained cfg or checkpoint for {model_name}." f" Use open_clip.list_pretrained() to find one.")
504
+
505
+ model = create_model(
506
+ model_name,
507
+ pretrained,
508
+ precision=precision,
509
+ device=device,
510
+ jit=jit,
511
+ force_quick_gelu=force_quick_gelu,
512
+ force_custom_clip=force_custom_clip,
513
+ force_patch_dropout=force_patch_dropout,
514
+ cache_dir=cache_dir,
515
+ )
516
+
517
+ if is_frozen:
518
+ for param in model.parameters():
519
+ param.requires_grad = False
520
+
521
+ if not return_transform:
522
+ return model
523
+
524
+ image_mean = image_mean or getattr(model.visual, "image_mean", None)
525
+ image_std = image_std or getattr(model.visual, "image_std", None)
526
+ preprocess = image_transform(model.visual.image_size, is_train=False, mean=image_mean, std=image_std)
527
+
528
+ return model, preprocess
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_configs.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HF architecture dict:
2
+ arch_dict = {
3
+ # https://huggingface.co/docs/transformers/model_doc/roberta#roberta
4
+ "roberta": {
5
+ "config_names": {
6
+ "context_length": "max_position_embeddings",
7
+ "vocab_size": "vocab_size",
8
+ "width": "hidden_size",
9
+ "heads": "num_attention_heads",
10
+ "layers": "num_hidden_layers",
11
+ "layer_attr": "layer",
12
+ "token_embeddings_attr": "embeddings",
13
+ },
14
+ "pooler": "mean_pooler",
15
+ },
16
+ # https://huggingface.co/docs/transformers/model_doc/xlm-roberta#transformers.XLMRobertaConfig
17
+ "xlm-roberta": {
18
+ "config_names": {
19
+ "context_length": "max_position_embeddings",
20
+ "vocab_size": "vocab_size",
21
+ "width": "hidden_size",
22
+ "heads": "num_attention_heads",
23
+ "layers": "num_hidden_layers",
24
+ "layer_attr": "layer",
25
+ "token_embeddings_attr": "embeddings",
26
+ },
27
+ "pooler": "mean_pooler",
28
+ },
29
+ # https://huggingface.co/docs/transformers/model_doc/mt5#mt5
30
+ "mt5": {
31
+ "config_names": {
32
+ # unlimited seqlen
33
+ # https://github.com/google-research/text-to-text-transfer-transformer/issues/273
34
+ # https://github.com/huggingface/transformers/blob/v4.24.0/src/transformers/models/t5/modeling_t5.py#L374
35
+ "context_length": "",
36
+ "vocab_size": "vocab_size",
37
+ "width": "d_model",
38
+ "heads": "num_heads",
39
+ "layers": "num_layers",
40
+ "layer_attr": "block",
41
+ "token_embeddings_attr": "embed_tokens",
42
+ },
43
+ "pooler": "mean_pooler",
44
+ },
45
+ "bert": {
46
+ "config_names": {
47
+ "context_length": "max_position_embeddings",
48
+ "vocab_size": "vocab_size",
49
+ "width": "hidden_size",
50
+ "heads": "num_attention_heads",
51
+ "layers": "num_hidden_layers",
52
+ "layer_attr": "layer",
53
+ "token_embeddings_attr": "embeddings",
54
+ },
55
+ "pooler": "mean_pooler",
56
+ },
57
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/hf_model.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ huggingface model adapter
2
+
3
+ Wraps HuggingFace transformers (https://github.com/huggingface/transformers) models for use as a text tower in CLIP model.
4
+ """
5
+
6
+ import re
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from torch.nn import functional as F
11
+ from torch import TensorType
12
+
13
+ try:
14
+ import transformers
15
+ from transformers import AutoModel, AutoModelForMaskedLM, AutoTokenizer, AutoConfig, PretrainedConfig
16
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, BaseModelOutputWithPoolingAndCrossAttentions
17
+ except ImportError as e:
18
+ transformers = None
19
+
20
+ class BaseModelOutput:
21
+ pass
22
+
23
+ class PretrainedConfig:
24
+ pass
25
+
26
+
27
+ from .hf_configs import arch_dict
28
+
29
+
30
+ # utils
31
+ def _camel2snake(s):
32
+ return re.sub(r"(?<!^)(?=[A-Z])", "_", s).lower()
33
+
34
+
35
+ # TODO: ?last - for gpt-like models
36
+ _POOLERS = {}
37
+
38
+
39
+ def register_pooler(cls):
40
+ """Decorator registering pooler class"""
41
+ _POOLERS[_camel2snake(cls.__name__)] = cls
42
+ return cls
43
+
44
+
45
+ @register_pooler
46
+ class MeanPooler(nn.Module):
47
+ """Mean pooling"""
48
+
49
+ def forward(self, x: BaseModelOutput, attention_mask: TensorType):
50
+ masked_output = x.last_hidden_state * attention_mask.unsqueeze(-1)
51
+ return masked_output.sum(dim=1) / attention_mask.sum(-1, keepdim=True)
52
+
53
+
54
+ @register_pooler
55
+ class MaxPooler(nn.Module):
56
+ """Max pooling"""
57
+
58
+ def forward(self, x: BaseModelOutput, attention_mask: TensorType):
59
+ masked_output = x.last_hidden_state.masked_fill(attention_mask.unsqueeze(-1), -torch.inf)
60
+ return masked_output.max(1).values
61
+
62
+
63
+ @register_pooler
64
+ class ClsPooler(nn.Module):
65
+ """CLS token pooling"""
66
+
67
+ def __init__(self, use_pooler_output=True):
68
+ super().__init__()
69
+ self.cls_token_position = 0
70
+ self.use_pooler_output = use_pooler_output
71
+
72
+ def forward(self, x: BaseModelOutput, attention_mask: TensorType):
73
+
74
+ if self.use_pooler_output and isinstance(x, (BaseModelOutputWithPooling, BaseModelOutputWithPoolingAndCrossAttentions)) and (x.pooler_output is not None):
75
+ return x.pooler_output
76
+
77
+ return x.last_hidden_state[:, self.cls_token_position, :]
78
+
79
+
80
+ class HFTextEncoder(nn.Module):
81
+ """HuggingFace model adapter"""
82
+
83
+ def __init__(self, model_name_or_path: str, output_dim: int, tokenizer_name: str = None, config: PretrainedConfig = None, pooler_type: str = None, proj: str = None, pretrained: bool = True, masked_language_modeling: bool = False):
84
+ super().__init__()
85
+
86
+ self.output_dim = output_dim
87
+
88
+ # TODO: find better way to get this information
89
+ uses_transformer_pooler = pooler_type == "cls_pooler"
90
+
91
+ if transformers is None:
92
+ raise RuntimeError("Please `pip install transformers` to use pre-trained HuggingFace models")
93
+ if config is None:
94
+ self.config = AutoConfig.from_pretrained(model_name_or_path)
95
+ if masked_language_modeling:
96
+ create_func, model_args = (AutoModelForMaskedLM.from_pretrained, model_name_or_path) if pretrained else (AutoModelForMaskedLM.from_config, self.config)
97
+ else:
98
+ create_func, model_args = (AutoModel.from_pretrained, model_name_or_path) if pretrained else (AutoModel.from_config, self.config)
99
+ # TODO: do all model configs have this attribute? PretrainedConfig does so yes??
100
+ if hasattr(self.config, "is_encoder_decoder") and self.config.is_encoder_decoder:
101
+ self.transformer = create_func(model_args)
102
+ self.transformer = self.transformer.encoder
103
+ else:
104
+ self.transformer = create_func(model_args, add_pooling_layer=uses_transformer_pooler)
105
+ else:
106
+ self.config = config
107
+ if masked_language_modeling:
108
+ self.transformer = AutoModelForMaskedLM.from_config(config)
109
+ else:
110
+ self.transformer = AutoModel.from_config(config)
111
+
112
+ if pooler_type is None: # get default arch pooler
113
+ self.pooler = _POOLERS[(arch_dict[self.config.model_type]["pooler"])]()
114
+ else:
115
+ self.pooler = _POOLERS[pooler_type]()
116
+
117
+ d_model = getattr(self.config, arch_dict[self.config.model_type]["config_names"]["width"])
118
+ if (d_model == output_dim) and (proj is None): # do we always need a proj?
119
+ self.proj = nn.Identity()
120
+ elif proj == "linear":
121
+ self.proj = nn.Linear(d_model, output_dim, bias=False)
122
+ elif proj == "mlp":
123
+ hidden_size = (d_model + output_dim) // 2
124
+ self.proj = nn.Sequential(
125
+ nn.Linear(d_model, hidden_size, bias=False),
126
+ nn.GELU(),
127
+ nn.Linear(hidden_size, output_dim, bias=False),
128
+ )
129
+
130
+ # self.itm_proj = nn.Linear(d_model, 2, bias=False)
131
+ # self.mlm_proj = nn.Linear(d_model, self.config.vocab_size), bias=False)
132
+ self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
133
+
134
+ # def forward_itm(self, x:TensorType, image_embeds:TensorType) -> TensorType:
135
+ # image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(x.device)
136
+ # attn_mask = (x != self.config.pad_token_id).long()
137
+ # out = self.transformer(
138
+ # input_ids=x,
139
+ # attention_mask=attn_mask,
140
+ # encoder_hidden_states = image_embeds,
141
+ # encoder_attention_mask = image_atts,
142
+ # )
143
+ # pooled_out = self.pooler(out, attn_mask)
144
+
145
+ # return self.itm_proj(pooled_out)
146
+
147
+ def mask(self, input_ids, vocab_size, device, targets=None, masked_indices=None, probability_matrix=None):
148
+ if masked_indices is None:
149
+ masked_indices = torch.bernoulli(probability_matrix).bool()
150
+
151
+ masked_indices[input_ids == self.tokenizer.pad_token_id] = False
152
+ masked_indices[input_ids == self.tokenizer.cls_token_id] = False
153
+
154
+ if targets is not None:
155
+ targets[~masked_indices] = -100 # We only compute loss on masked tokens
156
+
157
+ # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
158
+ indices_replaced = torch.bernoulli(torch.full(input_ids.shape, 0.8)).bool() & masked_indices
159
+ input_ids[indices_replaced] = self.tokenizer.mask_token_id
160
+
161
+ # 10% of the time, we replace masked input tokens with random word
162
+ indices_random = torch.bernoulli(torch.full(input_ids.shape, 0.5)).bool() & masked_indices & ~indices_replaced
163
+ random_words = torch.randint(vocab_size, input_ids.shape, dtype=torch.long).to(device)
164
+ input_ids[indices_random] = random_words[indices_random]
165
+ # The rest of the time (10% of the time) we keep the masked input tokens unchanged
166
+
167
+ if targets is not None:
168
+ return input_ids, targets
169
+ else:
170
+ return input_ids
171
+
172
+ def forward_mlm(self, input_ids, image_embeds, mlm_probability=0.25):
173
+ labels = input_ids.clone()
174
+ attn_mask = (input_ids != self.config.pad_token_id).long()
175
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(input_ids.device)
176
+ vocab_size = getattr(self.config, arch_dict[self.config.model_type]["config_names"]["vocab_size"])
177
+ probability_matrix = torch.full(labels.shape, mlm_probability)
178
+ input_ids, labels = self.mask(input_ids, vocab_size, input_ids.device, targets=labels, probability_matrix=probability_matrix)
179
+ mlm_output = self.transformer(
180
+ input_ids,
181
+ attention_mask=attn_mask,
182
+ encoder_hidden_states=image_embeds,
183
+ encoder_attention_mask=image_atts,
184
+ return_dict=True,
185
+ labels=labels,
186
+ )
187
+ return mlm_output.loss
188
+ # mlm_output = self.transformer(input_ids,
189
+ # attention_mask = attn_mask,
190
+ # encoder_hidden_states = image_embeds,
191
+ # encoder_attention_mask = image_atts,
192
+ # return_dict = True,
193
+ # ).last_hidden_state
194
+ # logits = self.mlm_proj(mlm_output)
195
+
196
+ # # logits = logits[:, :-1, :].contiguous().view(-1, vocab_size)
197
+ # logits = logits[:, 1:, :].contiguous().view(-1, vocab_size)
198
+ # labels = labels[:, 1:].contiguous().view(-1)
199
+
200
+ # mlm_loss = F.cross_entropy(
201
+ # logits,
202
+ # labels,
203
+ # # label_smoothing=0.1,
204
+ # )
205
+ # return mlm_loss
206
+
207
+ def forward(self, x: TensorType) -> TensorType:
208
+ attn_mask = (x != self.config.pad_token_id).long()
209
+ out = self.transformer(input_ids=x, attention_mask=attn_mask)
210
+ pooled_out = self.pooler(out, attn_mask)
211
+
212
+ return self.proj(pooled_out)
213
+
214
+ def lock(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True):
215
+ if not unlocked_layers: # full freezing
216
+ for n, p in self.transformer.named_parameters():
217
+ p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False
218
+ return
219
+
220
+ encoder = self.transformer.encoder if hasattr(self.transformer, "encoder") else self.transformer
221
+ layer_list = getattr(encoder, arch_dict[self.config.model_type]["config_names"]["layer_attr"])
222
+ print(f"Unlocking {unlocked_layers}/{len(layer_list) + 1} layers of hf model")
223
+ embeddings = getattr(self.transformer, arch_dict[self.config.model_type]["config_names"]["token_embeddings_attr"])
224
+ modules = [embeddings, *layer_list][:-unlocked_layers]
225
+ # freeze layers
226
+ for module in modules:
227
+ for n, p in module.named_parameters():
228
+ p.requires_grad = (not freeze_layer_norm) if "LayerNorm" in n.split(".") else False
229
+
230
+ @torch.jit.ignore
231
+ def set_grad_checkpointing(self, enable=True):
232
+ self.transformer.gradient_checkpointing_enable()
233
+
234
+ def get_num_layers(self):
235
+ encoder = self.transformer.encoder if hasattr(self.transformer, "encoder") else self.transformer
236
+ layer_list = getattr(encoder, arch_dict[self.config.model_type]["config_names"]["layer_attr"])
237
+ return len(layer_list)
238
+
239
+ def init_parameters(self):
240
+ pass
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/loss.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+
6
+ try:
7
+ import torch.distributed.nn
8
+ from torch import distributed as dist
9
+
10
+ has_distributed = True
11
+ except ImportError:
12
+ has_distributed = False
13
+
14
+ try:
15
+ import horovod.torch as hvd
16
+ except ImportError:
17
+ hvd = None
18
+
19
+ from timm.loss import LabelSmoothingCrossEntropy
20
+
21
+
22
+ def gather_features(image_features, text_features, local_loss=False, gather_with_grad=False, rank=0, world_size=1, use_horovod=False):
23
+ assert has_distributed, "torch.distributed did not import correctly, please use a PyTorch version with support."
24
+ if use_horovod:
25
+ assert hvd is not None, "Please install horovod"
26
+ if gather_with_grad:
27
+ all_image_features = hvd.allgather(image_features)
28
+ all_text_features = hvd.allgather(text_features)
29
+ else:
30
+ with torch.no_grad():
31
+ all_image_features = hvd.allgather(image_features)
32
+ all_text_features = hvd.allgather(text_features)
33
+ if not local_loss:
34
+ # ensure grads for local rank when all_* features don't have a gradient
35
+ gathered_image_features = list(all_image_features.chunk(world_size, dim=0))
36
+ gathered_text_features = list(all_text_features.chunk(world_size, dim=0))
37
+ gathered_image_features[rank] = image_features
38
+ gathered_text_features[rank] = text_features
39
+ all_image_features = torch.cat(gathered_image_features, dim=0)
40
+ all_text_features = torch.cat(gathered_text_features, dim=0)
41
+ else:
42
+ # We gather tensors from all gpus
43
+ if gather_with_grad:
44
+ all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features), dim=0)
45
+ all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features), dim=0)
46
+ # all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features, async_op=True), dim=0)
47
+ # all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features, async_op=True), dim=0)
48
+ else:
49
+ gathered_image_features = [torch.zeros_like(image_features) for _ in range(world_size)]
50
+ gathered_text_features = [torch.zeros_like(text_features) for _ in range(world_size)]
51
+ dist.all_gather(gathered_image_features, image_features)
52
+ dist.all_gather(gathered_text_features, text_features)
53
+ if not local_loss:
54
+ # ensure grads for local rank when all_* features don't have a gradient
55
+ gathered_image_features[rank] = image_features
56
+ gathered_text_features[rank] = text_features
57
+ all_image_features = torch.cat(gathered_image_features, dim=0)
58
+ all_text_features = torch.cat(gathered_text_features, dim=0)
59
+
60
+ return all_image_features, all_text_features
61
+
62
+
63
+ class ClipLoss(nn.Module):
64
+
65
+ def __init__(
66
+ self,
67
+ local_loss=False,
68
+ gather_with_grad=False,
69
+ cache_labels=False,
70
+ rank=0,
71
+ world_size=1,
72
+ use_horovod=False,
73
+ smoothing=0.0,
74
+ ):
75
+ super().__init__()
76
+ self.local_loss = local_loss
77
+ self.gather_with_grad = gather_with_grad
78
+ self.cache_labels = cache_labels
79
+ self.rank = rank
80
+ self.world_size = world_size
81
+ self.use_horovod = use_horovod
82
+ self.label_smoothing_cross_entropy = LabelSmoothingCrossEntropy(smoothing=smoothing) if smoothing > 0 else None
83
+
84
+ # cache state
85
+ self.prev_num_logits = 0
86
+ self.labels = {}
87
+
88
+ def forward(self, image_features, text_features, logit_scale=1.0):
89
+ device = image_features.device
90
+ if self.world_size > 1:
91
+ all_image_features, all_text_features = gather_features(image_features, text_features, self.local_loss, self.gather_with_grad, self.rank, self.world_size, self.use_horovod)
92
+
93
+ if self.local_loss:
94
+ logits_per_image = logit_scale * image_features @ all_text_features.T
95
+ logits_per_text = logit_scale * text_features @ all_image_features.T
96
+ else:
97
+ logits_per_image = logit_scale * all_image_features @ all_text_features.T
98
+ logits_per_text = logits_per_image.T
99
+ else:
100
+ logits_per_image = logit_scale * image_features @ text_features.T
101
+ logits_per_text = logit_scale * text_features @ image_features.T
102
+ # calculated ground-truth and cache if enabled
103
+ num_logits = logits_per_image.shape[0]
104
+ if self.prev_num_logits != num_logits or device not in self.labels:
105
+ labels = torch.arange(num_logits, device=device, dtype=torch.long)
106
+ if self.world_size > 1 and self.local_loss:
107
+ labels = labels + num_logits * self.rank
108
+ if self.cache_labels:
109
+ self.labels[device] = labels
110
+ self.prev_num_logits = num_logits
111
+ else:
112
+ labels = self.labels[device]
113
+
114
+ if self.label_smoothing_cross_entropy:
115
+ total_loss = (self.label_smoothing_cross_entropy(logits_per_image, labels) + self.label_smoothing_cross_entropy(logits_per_text, labels)) / 2
116
+ else:
117
+ total_loss = (F.cross_entropy(logits_per_image, labels) + F.cross_entropy(logits_per_text, labels)) / 2
118
+
119
+ acc = None
120
+ i2t_acc = (logits_per_image.argmax(-1) == labels).sum() / len(logits_per_image)
121
+ t2i_acc = (logits_per_text.argmax(-1) == labels).sum() / len(logits_per_text)
122
+ acc = {"i2t": i2t_acc, "t2i": t2i_acc}
123
+ return total_loss, acc
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ CLIP Model
2
+
3
+ Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
4
+ """
5
+
6
+ import os
7
+ from dataclasses import dataclass
8
+ from typing import Optional, Tuple, Union
9
+ from functools import partial
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch import nn
15
+
16
+ try:
17
+ from .hf_model import HFTextEncoder
18
+ except:
19
+ HFTextEncoder = None
20
+ from .modified_resnet import ModifiedResNet
21
+ from .timm_model import TimmModel
22
+ from .eva_vit_model import EVAVisionTransformer
23
+ from .transformer import LayerNorm, QuickGELU, Attention, VisionTransformer, TextTransformer
24
+
25
+ try:
26
+ from apex.normalization import FusedLayerNorm
27
+ except:
28
+ FusedLayerNorm = LayerNorm
29
+ # print("Please 'pip install apex'")
30
+
31
+ try:
32
+ import xformers.ops as xops
33
+ except ImportError:
34
+ xops = None
35
+ # print("Please 'pip install xformers'")
36
+
37
+
38
+ class RMSnorm(nn.Module):
39
+ """
40
+ adepted from transformers T5LayerNorm
41
+ """
42
+
43
+ def __init__(self, hidden_size, eps=1e-6):
44
+ """
45
+ Construct a layernorm module in the T5 style. No bias and no subtraction of mean.
46
+ """
47
+ super().__init__()
48
+ self.weight = nn.Parameter(torch.ones(hidden_size))
49
+ self.variance_epsilon = eps
50
+
51
+ def forward(self, hidden_states):
52
+ # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
53
+ # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus varience is calculated
54
+ # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
55
+ # half-precision inputs is done in fp32
56
+
57
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
58
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
59
+
60
+ # convert into half-precision if necessary
61
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
62
+ hidden_states = hidden_states.to(self.weight.dtype)
63
+
64
+ return self.weight * hidden_states
65
+
66
+
67
+ @dataclass
68
+ class CLIPVisionCfg:
69
+ layers: Union[Tuple[int, int, int, int], int] = 12
70
+ width: int = 768
71
+ head_width: int = 64
72
+ mlp_ratio: float = 4.0
73
+ patch_size: int = 16
74
+ image_size: Union[Tuple[int, int], int] = 224
75
+ ls_init_value: Optional[float] = None # layer scale initial value
76
+ patch_dropout: float = 0.0 # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results
77
+ global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580)
78
+ drop_path_rate: Optional[float] = None # drop path rate
79
+ timm_model_name: str = None # a valid model name overrides layers, width, patch_size
80
+ timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model
81
+ timm_pool: str = "avg" # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '')
82
+ timm_proj: str = "linear" # linear projection for timm model output ('linear', 'mlp', '')
83
+ timm_proj_bias: bool = False # enable bias final projection
84
+ eva_model_name: str = None # a valid eva model name overrides layers, width, patch_size
85
+ qkv_bias: bool = True
86
+ fusedLN: bool = False
87
+ xattn: bool = False
88
+ postnorm: bool = False
89
+ rope: bool = False
90
+ pt_hw_seq_len: int = 16 # 224/14
91
+ intp_freq: bool = False
92
+ naiveswiglu: bool = False
93
+ subln: bool = False
94
+ use_rms_norm: bool = False
95
+
96
+
97
+ @dataclass
98
+ class CLIPTextCfg:
99
+ context_length: int = 77
100
+ vocab_size: int = 49408
101
+ width: int = 512
102
+ heads: int = 8
103
+ layers: int = 12
104
+ ls_init_value: Optional[float] = None # layer scale initial value
105
+ hf_model_name: str = None
106
+ hf_tokenizer_name: str = None
107
+ hf_model_pretrained: bool = True
108
+ proj: str = "mlp"
109
+ pooler_type: str = "mean_pooler"
110
+ masked_language_modeling: bool = False
111
+ fusedLN: bool = False
112
+ xattn: bool = False
113
+ attn_mask: bool = True
114
+
115
+
116
+ def get_cast_dtype(precision: str):
117
+ cast_dtype = None
118
+ if precision == "bf16":
119
+ cast_dtype = torch.bfloat16
120
+ elif precision == "fp16":
121
+ cast_dtype = torch.float16
122
+ return cast_dtype
123
+
124
+
125
+ def _build_vision_tower(embed_dim: int, vision_cfg: CLIPVisionCfg, quick_gelu: bool = False, cast_dtype: Optional[torch.dtype] = None):
126
+ if isinstance(vision_cfg, dict):
127
+ vision_cfg = CLIPVisionCfg(**vision_cfg)
128
+
129
+ # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more
130
+ # memory efficient in recent PyTorch releases (>= 1.10).
131
+ # NOTE: timm models always use native GELU regardless of quick_gelu flag.
132
+ act_layer = QuickGELU if quick_gelu else nn.GELU
133
+
134
+ if vision_cfg.eva_model_name:
135
+ vision_heads = vision_cfg.width // vision_cfg.head_width
136
+
137
+ norm_layer = RMSnorm if vision_cfg.use_rms_norm else LayerNorm
138
+
139
+ visual = EVAVisionTransformer(
140
+ img_size=vision_cfg.image_size,
141
+ patch_size=vision_cfg.patch_size,
142
+ num_classes=embed_dim,
143
+ use_mean_pooling=vision_cfg.global_average_pool, # False
144
+ init_values=vision_cfg.ls_init_value,
145
+ patch_dropout=vision_cfg.patch_dropout,
146
+ embed_dim=vision_cfg.width,
147
+ depth=vision_cfg.layers,
148
+ num_heads=vision_heads,
149
+ mlp_ratio=vision_cfg.mlp_ratio,
150
+ qkv_bias=vision_cfg.qkv_bias,
151
+ drop_path_rate=vision_cfg.drop_path_rate,
152
+ norm_layer=partial(norm_layer, eps=1e-6),
153
+ xattn=vision_cfg.xattn,
154
+ rope=vision_cfg.rope,
155
+ postnorm=vision_cfg.postnorm,
156
+ pt_hw_seq_len=vision_cfg.pt_hw_seq_len, # 224/14
157
+ intp_freq=vision_cfg.intp_freq,
158
+ naiveswiglu=vision_cfg.naiveswiglu,
159
+ subln=vision_cfg.subln,
160
+ )
161
+ elif vision_cfg.timm_model_name:
162
+ visual = TimmModel(
163
+ vision_cfg.timm_model_name, pretrained=vision_cfg.timm_model_pretrained, pool=vision_cfg.timm_pool, proj=vision_cfg.timm_proj, proj_bias=vision_cfg.timm_proj_bias, embed_dim=embed_dim, image_size=vision_cfg.image_size
164
+ )
165
+ act_layer = nn.GELU # so that text transformer doesn't use QuickGELU w/ timm models
166
+ elif isinstance(vision_cfg.layers, (tuple, list)):
167
+ vision_heads = vision_cfg.width * 32 // vision_cfg.head_width
168
+ visual = ModifiedResNet(layers=vision_cfg.layers, output_dim=embed_dim, heads=vision_heads, image_size=vision_cfg.image_size, width=vision_cfg.width)
169
+ else:
170
+ vision_heads = vision_cfg.width // vision_cfg.head_width
171
+ norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm
172
+ visual = VisionTransformer(
173
+ image_size=vision_cfg.image_size,
174
+ patch_size=vision_cfg.patch_size,
175
+ width=vision_cfg.width,
176
+ layers=vision_cfg.layers,
177
+ heads=vision_heads,
178
+ mlp_ratio=vision_cfg.mlp_ratio,
179
+ ls_init_value=vision_cfg.ls_init_value,
180
+ patch_dropout=vision_cfg.patch_dropout,
181
+ global_average_pool=vision_cfg.global_average_pool,
182
+ output_dim=embed_dim,
183
+ act_layer=act_layer,
184
+ norm_layer=norm_layer,
185
+ )
186
+
187
+ return visual
188
+
189
+
190
+ def _build_text_tower(
191
+ embed_dim: int,
192
+ text_cfg: CLIPTextCfg,
193
+ quick_gelu: bool = False,
194
+ cast_dtype: Optional[torch.dtype] = None,
195
+ ):
196
+ if isinstance(text_cfg, dict):
197
+ text_cfg = CLIPTextCfg(**text_cfg)
198
+
199
+ if text_cfg.hf_model_name:
200
+ text = HFTextEncoder(text_cfg.hf_model_name, output_dim=embed_dim, tokenizer_name=text_cfg.hf_tokenizer_name, proj=text_cfg.proj, pooler_type=text_cfg.pooler_type, masked_language_modeling=text_cfg.masked_language_modeling)
201
+ else:
202
+ act_layer = QuickGELU if quick_gelu else nn.GELU
203
+ norm_layer = LayerNorm
204
+
205
+ text = TextTransformer(
206
+ context_length=text_cfg.context_length,
207
+ vocab_size=text_cfg.vocab_size,
208
+ width=text_cfg.width,
209
+ heads=text_cfg.heads,
210
+ layers=text_cfg.layers,
211
+ ls_init_value=text_cfg.ls_init_value,
212
+ output_dim=embed_dim,
213
+ act_layer=act_layer,
214
+ norm_layer=FusedLayerNorm if text_cfg.fusedLN else norm_layer,
215
+ xattn=text_cfg.xattn,
216
+ attn_mask=text_cfg.attn_mask,
217
+ )
218
+ return text
219
+
220
+
221
+ class CLIP(nn.Module):
222
+ def __init__(
223
+ self,
224
+ embed_dim: int,
225
+ vision_cfg: CLIPVisionCfg,
226
+ text_cfg: CLIPTextCfg,
227
+ quick_gelu: bool = False,
228
+ cast_dtype: Optional[torch.dtype] = None,
229
+ ):
230
+ super().__init__()
231
+ self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype)
232
+
233
+ text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype)
234
+ self.transformer = text.transformer
235
+ self.vocab_size = text.vocab_size
236
+ self.token_embedding = text.token_embedding
237
+ self.positional_embedding = text.positional_embedding
238
+ self.ln_final = text.ln_final
239
+ self.text_projection = text.text_projection
240
+ self.register_buffer("attn_mask", text.attn_mask, persistent=False)
241
+
242
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
243
+
244
+ def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False):
245
+ # lock image tower as per LiT - https://arxiv.org/abs/2111.07991
246
+ self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats)
247
+
248
+ @torch.jit.ignore
249
+ def set_grad_checkpointing(self, enable=True):
250
+ self.visual.set_grad_checkpointing(enable)
251
+ self.transformer.grad_checkpointing = enable
252
+
253
+ @torch.jit.ignore
254
+ def no_weight_decay(self):
255
+ return {"logit_scale"}
256
+
257
+ def encode_image(self, image, normalize: bool = False):
258
+ features = self.visual(image)
259
+ return F.normalize(features, dim=-1) if normalize else features
260
+
261
+ def encode_text(self, text, normalize: bool = False):
262
+ cast_dtype = self.transformer.get_cast_dtype()
263
+
264
+ x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
265
+
266
+ x = x + self.positional_embedding.to(cast_dtype)
267
+ x = x.permute(1, 0, 2) # NLD -> LND
268
+ x = self.transformer(x, attn_mask=self.attn_mask)
269
+ x = x.permute(1, 0, 2) # LND -> NLD
270
+ x = self.ln_final(x) # [batch_size, n_ctx, transformer.width]
271
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
272
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
273
+ return F.normalize(x, dim=-1) if normalize else x
274
+
275
+ def forward(self, image, text):
276
+ image_features = self.encode_image(image, normalize=True)
277
+ text_features = self.encode_text(text, normalize=True)
278
+ return image_features, text_features, self.logit_scale.exp()
279
+
280
+
281
+ class CustomCLIP(nn.Module):
282
+ def __init__(
283
+ self,
284
+ embed_dim: int,
285
+ vision_cfg: CLIPVisionCfg,
286
+ text_cfg: CLIPTextCfg,
287
+ quick_gelu: bool = False,
288
+ cast_dtype: Optional[torch.dtype] = None,
289
+ itm_task: bool = False,
290
+ ):
291
+ super().__init__()
292
+ self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype)
293
+ self.text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype)
294
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
295
+
296
+ def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False):
297
+ # lock image tower as per LiT - https://arxiv.org/abs/2111.07991
298
+ self.visual.lock(unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats)
299
+
300
+ def lock_text_tower(self, unlocked_layers: int = 0, freeze_layer_norm: bool = True):
301
+ self.text.lock(unlocked_layers, freeze_layer_norm)
302
+
303
+ @torch.jit.ignore
304
+ def set_grad_checkpointing(self, enable=True):
305
+ self.visual.set_grad_checkpointing(enable)
306
+ self.text.set_grad_checkpointing(enable)
307
+
308
+ @torch.jit.ignore
309
+ def no_weight_decay(self):
310
+ return {"logit_scale"}
311
+
312
+ def encode_image(self, image, normalize: bool = False):
313
+ features = self.visual(image)
314
+ return F.normalize(features, dim=-1) if normalize else features
315
+
316
+ def encode_text(self, text, normalize: bool = False):
317
+ features = self.text(text)
318
+ return F.normalize(features, dim=-1) if normalize else features
319
+
320
+ def forward(self, image, text):
321
+ image_features = self.encode_image(image, normalize=True)
322
+ text_features = self.encode_text(text, normalize=True)
323
+ return image_features, text_features, self.logit_scale.exp()
324
+
325
+
326
+ def convert_weights_to_lp(model: nn.Module, dtype=torch.float16):
327
+ """Convert applicable model parameters to low-precision (bf16 or fp16)"""
328
+
329
+ def _convert_weights(l):
330
+
331
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
332
+ l.weight.data = l.weight.data.to(dtype)
333
+ if l.bias is not None:
334
+ l.bias.data = l.bias.data.to(dtype)
335
+
336
+ if isinstance(l, (nn.MultiheadAttention, Attention)):
337
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
338
+ tensor = getattr(l, attr, None)
339
+ if tensor is not None:
340
+ tensor.data = tensor.data.to(dtype)
341
+
342
+ if isinstance(l, nn.Parameter):
343
+ l.data = l.data.to(dtype)
344
+
345
+ for name in ["text_projection", "proj"]:
346
+ if hasattr(l, name) and isinstance(l, nn.Parameter):
347
+ attr = getattr(l, name, None)
348
+ if attr is not None:
349
+ attr.data = attr.data.to(dtype)
350
+
351
+ model.apply(_convert_weights)
352
+
353
+
354
+ convert_weights_to_fp16 = convert_weights_to_lp # backwards compat
355
+
356
+
357
+ # used to maintain checkpoint compatibility
358
+ def convert_to_custom_text_state_dict(state_dict: dict):
359
+ if "text_projection" in state_dict:
360
+ # old format state_dict, move text tower -> .text
361
+ new_state_dict = {}
362
+ for k, v in state_dict.items():
363
+ if any(k.startswith(p) for p in ("text_projection", "positional_embedding", "token_embedding", "transformer", "ln_final", "logit_scale")):
364
+ k = "text." + k
365
+ new_state_dict[k] = v
366
+ return new_state_dict
367
+ return state_dict
368
+
369
+
370
+ def build_model_from_openai_state_dict(
371
+ state_dict: dict,
372
+ quick_gelu=True,
373
+ cast_dtype=torch.float16,
374
+ ):
375
+ vit = "visual.proj" in state_dict
376
+
377
+ if vit:
378
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
379
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
380
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
381
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
382
+ image_size = vision_patch_size * grid_size
383
+ else:
384
+ counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
385
+ vision_layers = tuple(counts)
386
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
387
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
388
+ vision_patch_size = None
389
+ assert output_width**2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
390
+ image_size = output_width * 32
391
+
392
+ embed_dim = state_dict["text_projection"].shape[1]
393
+ context_length = state_dict["positional_embedding"].shape[0]
394
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
395
+ transformer_width = state_dict["ln_final.weight"].shape[0]
396
+ transformer_heads = transformer_width // 64
397
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
398
+
399
+ vision_cfg = CLIPVisionCfg(
400
+ layers=vision_layers,
401
+ width=vision_width,
402
+ patch_size=vision_patch_size,
403
+ image_size=image_size,
404
+ )
405
+ text_cfg = CLIPTextCfg(context_length=context_length, vocab_size=vocab_size, width=transformer_width, heads=transformer_heads, layers=transformer_layers)
406
+ model = CLIP(
407
+ embed_dim,
408
+ vision_cfg=vision_cfg,
409
+ text_cfg=text_cfg,
410
+ quick_gelu=quick_gelu, # OpenAI models were trained with QuickGELU
411
+ cast_dtype=cast_dtype,
412
+ )
413
+
414
+ for key in ["input_resolution", "context_length", "vocab_size"]:
415
+ state_dict.pop(key, None)
416
+
417
+ convert_weights_to_fp16(model) # OpenAI state dicts are partially converted to float16
418
+ model.load_state_dict(state_dict)
419
+ return model.eval()
420
+
421
+
422
+ def trace_model(model, batch_size=256, device=torch.device("cpu")):
423
+ model.eval()
424
+ image_size = model.visual.image_size
425
+ example_images = torch.ones((batch_size, 3, image_size, image_size), device=device)
426
+ example_text = torch.zeros((batch_size, model.context_length), dtype=torch.int, device=device)
427
+ model = torch.jit.trace_module(model, inputs=dict(forward=(example_images, example_text), encode_text=(example_text,), encode_image=(example_images,)))
428
+ model.visual.image_size = image_size
429
+ return model
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-18B.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1536,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 48,
6
+ "width": 5120,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-18b-14-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": true,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-8B-plus.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1280,
3
+ "vision_cfg": {
4
+ "image_size": 448,
5
+ "layers": 32,
6
+ "width": 4096,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-8b-14-plus-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": false,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-8B.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1280,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 32,
6
+ "width": 4096,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-8b-14-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": false,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 12,
6
+ "width": 768,
7
+ "patch_size": 16,
8
+ "eva_model_name": "eva-clip-b-16",
9
+ "ls_init_value": 0.1,
10
+ "drop_path_rate": 0.0
11
+ },
12
+ "text_cfg": {
13
+ "context_length": 77,
14
+ "vocab_size": 49408,
15
+ "width": 512,
16
+ "heads": 8,
17
+ "layers": 12
18
+ }
19
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 40,
6
+ "width": 1408,
7
+ "head_width": 88,
8
+ "mlp_ratio": 4.3637,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-g-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "fusedLN": true
14
+ },
15
+ "text_cfg": {
16
+ "context_length": 77,
17
+ "vocab_size": 49408,
18
+ "width": 1024,
19
+ "heads": 16,
20
+ "layers": 24,
21
+ "xattn": false,
22
+ "fusedLN": true
23
+ }
24
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-g-14.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 40,
6
+ "width": 1408,
7
+ "head_width": 88,
8
+ "mlp_ratio": 4.3637,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-g-14-x",
11
+ "drop_path_rate": 0.4,
12
+ "xattn": true,
13
+ "fusedLN": true
14
+ },
15
+ "text_cfg": {
16
+ "context_length": 77,
17
+ "vocab_size": 49408,
18
+ "width": 768,
19
+ "heads": 12,
20
+ "layers": 12,
21
+ "xattn": false,
22
+ "fusedLN": true
23
+ }
24
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-B-16.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 512,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 12,
6
+ "width": 768,
7
+ "head_width": 64,
8
+ "patch_size": 16,
9
+ "mlp_ratio": 2.6667,
10
+ "eva_model_name": "eva-clip-b-16-X",
11
+ "drop_path_rate": 0.0,
12
+ "xattn": true,
13
+ "fusedLN": true,
14
+ "rope": true,
15
+ "pt_hw_seq_len": 16,
16
+ "intp_freq": true,
17
+ "naiveswiglu": true,
18
+ "subln": true
19
+ },
20
+ "text_cfg": {
21
+ "context_length": 77,
22
+ "vocab_size": 49408,
23
+ "width": 512,
24
+ "heads": 8,
25
+ "layers": 12,
26
+ "xattn": true,
27
+ "fusedLN": true
28
+ }
29
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-L-14-336.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 336,
5
+ "layers": 24,
6
+ "width": 1024,
7
+ "drop_path_rate": 0,
8
+ "head_width": 64,
9
+ "mlp_ratio": 2.6667,
10
+ "patch_size": 14,
11
+ "eva_model_name": "eva-clip-l-14-336",
12
+ "xattn": true,
13
+ "fusedLN": true,
14
+ "rope": true,
15
+ "pt_hw_seq_len": 16,
16
+ "intp_freq": true,
17
+ "naiveswiglu": true,
18
+ "subln": true
19
+ },
20
+ "text_cfg": {
21
+ "context_length": 77,
22
+ "vocab_size": 49408,
23
+ "width": 768,
24
+ "heads": 12,
25
+ "layers": 12,
26
+ "xattn": false,
27
+ "fusedLN": true
28
+ }
29
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-L-14.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 768,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 24,
6
+ "width": 1024,
7
+ "drop_path_rate": 0,
8
+ "head_width": 64,
9
+ "mlp_ratio": 2.6667,
10
+ "patch_size": 14,
11
+ "eva_model_name": "eva-clip-l-14",
12
+ "xattn": true,
13
+ "fusedLN": true,
14
+ "rope": true,
15
+ "pt_hw_seq_len": 16,
16
+ "intp_freq": true,
17
+ "naiveswiglu": true,
18
+ "subln": true
19
+ },
20
+ "text_cfg": {
21
+ "context_length": 77,
22
+ "vocab_size": 49408,
23
+ "width": 768,
24
+ "heads": 12,
25
+ "layers": 12,
26
+ "xattn": false,
27
+ "fusedLN": true
28
+ }
29
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 64,
6
+ "width": 1792,
7
+ "head_width": 112,
8
+ "mlp_ratio": 8.571428571428571,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-4b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": true,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1280,
20
+ "heads": 20,
21
+ "layers": 32,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA02-CLIP-bigE-14.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 64,
6
+ "width": 1792,
7
+ "head_width": 112,
8
+ "mlp_ratio": 8.571428571428571,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-4b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": true,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1024,
20
+ "heads": 16,
21
+ "layers": 24,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14-448.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 448,
5
+ "layers": 77,
6
+ "width": 2304,
7
+ "head_width": 144,
8
+ "mlp_ratio": 10.9722,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-10b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": false,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1280,
20
+ "heads": 20,
21
+ "layers": 32,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1024,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 77,
6
+ "width": 2304,
7
+ "head_width": 144,
8
+ "mlp_ratio": 10.9722,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-10b-14-x",
11
+ "drop_path_rate": 0,
12
+ "xattn": true,
13
+ "postnorm": false,
14
+ "fusedLN": true
15
+ },
16
+ "text_cfg": {
17
+ "context_length": 77,
18
+ "vocab_size": 49408,
19
+ "width": 1280,
20
+ "heads": 20,
21
+ "layers": 32,
22
+ "xattn": false,
23
+ "fusedLN": true
24
+ }
25
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/modified_resnet.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ from .utils import freeze_batch_norm_2d
8
+
9
+
10
+ class Bottleneck(nn.Module):
11
+ expansion = 4
12
+
13
+ def __init__(self, inplanes, planes, stride=1):
14
+ super().__init__()
15
+
16
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
17
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+ self.act1 = nn.ReLU(inplace=True)
20
+
21
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
22
+ self.bn2 = nn.BatchNorm2d(planes)
23
+ self.act2 = nn.ReLU(inplace=True)
24
+
25
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
26
+
27
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
28
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
29
+ self.act3 = nn.ReLU(inplace=True)
30
+
31
+ self.downsample = None
32
+ self.stride = stride
33
+
34
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
35
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
36
+ self.downsample = nn.Sequential(OrderedDict([("-1", nn.AvgPool2d(stride)), ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), ("1", nn.BatchNorm2d(planes * self.expansion))]))
37
+
38
+ def forward(self, x: torch.Tensor):
39
+ identity = x
40
+
41
+ out = self.act1(self.bn1(self.conv1(x)))
42
+ out = self.act2(self.bn2(self.conv2(out)))
43
+ out = self.avgpool(out)
44
+ out = self.bn3(self.conv3(out))
45
+
46
+ if self.downsample is not None:
47
+ identity = self.downsample(x)
48
+
49
+ out += identity
50
+ out = self.act3(out)
51
+ return out
52
+
53
+
54
+ class AttentionPool2d(nn.Module):
55
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
56
+ super().__init__()
57
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim**2 + 1, embed_dim) / embed_dim**0.5)
58
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
59
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
60
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
61
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
62
+ self.num_heads = num_heads
63
+
64
+ def forward(self, x):
65
+ x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
66
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
67
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
68
+ x, _ = F.multi_head_attention_forward(
69
+ query=x,
70
+ key=x,
71
+ value=x,
72
+ embed_dim_to_check=x.shape[-1],
73
+ num_heads=self.num_heads,
74
+ q_proj_weight=self.q_proj.weight,
75
+ k_proj_weight=self.k_proj.weight,
76
+ v_proj_weight=self.v_proj.weight,
77
+ in_proj_weight=None,
78
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
79
+ bias_k=None,
80
+ bias_v=None,
81
+ add_zero_attn=False,
82
+ dropout_p=0.0,
83
+ out_proj_weight=self.c_proj.weight,
84
+ out_proj_bias=self.c_proj.bias,
85
+ use_separate_proj_weight=True,
86
+ training=self.training,
87
+ need_weights=False,
88
+ )
89
+
90
+ return x[0]
91
+
92
+
93
+ class ModifiedResNet(nn.Module):
94
+ """
95
+ A ResNet class that is similar to torchvision's but contains the following changes:
96
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
97
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
98
+ - The final pooling layer is a QKV attention instead of an average pool
99
+ """
100
+
101
+ def __init__(self, layers, output_dim, heads, image_size=224, width=64):
102
+ super().__init__()
103
+ self.output_dim = output_dim
104
+ self.image_size = image_size
105
+
106
+ # the 3-layer stem
107
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
108
+ self.bn1 = nn.BatchNorm2d(width // 2)
109
+ self.act1 = nn.ReLU(inplace=True)
110
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
111
+ self.bn2 = nn.BatchNorm2d(width // 2)
112
+ self.act2 = nn.ReLU(inplace=True)
113
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
114
+ self.bn3 = nn.BatchNorm2d(width)
115
+ self.act3 = nn.ReLU(inplace=True)
116
+ self.avgpool = nn.AvgPool2d(2)
117
+
118
+ # residual layers
119
+ self._inplanes = width # this is a *mutable* variable used during construction
120
+ self.layer1 = self._make_layer(width, layers[0])
121
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
122
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
123
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
124
+
125
+ embed_dim = width * 32 # the ResNet feature dimension
126
+ self.attnpool = AttentionPool2d(image_size // 32, embed_dim, heads, output_dim)
127
+
128
+ self.init_parameters()
129
+
130
+ def _make_layer(self, planes, blocks, stride=1):
131
+ layers = [Bottleneck(self._inplanes, planes, stride)]
132
+
133
+ self._inplanes = planes * Bottleneck.expansion
134
+ for _ in range(1, blocks):
135
+ layers.append(Bottleneck(self._inplanes, planes))
136
+
137
+ return nn.Sequential(*layers)
138
+
139
+ def init_parameters(self):
140
+ if self.attnpool is not None:
141
+ std = self.attnpool.c_proj.in_features**-0.5
142
+ nn.init.normal_(self.attnpool.q_proj.weight, std=std)
143
+ nn.init.normal_(self.attnpool.k_proj.weight, std=std)
144
+ nn.init.normal_(self.attnpool.v_proj.weight, std=std)
145
+ nn.init.normal_(self.attnpool.c_proj.weight, std=std)
146
+
147
+ for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]:
148
+ for name, param in resnet_block.named_parameters():
149
+ if name.endswith("bn3.weight"):
150
+ nn.init.zeros_(param)
151
+
152
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
153
+ assert unlocked_groups == 0, "partial locking not currently supported for this model"
154
+ for param in self.parameters():
155
+ param.requires_grad = False
156
+ if freeze_bn_stats:
157
+ freeze_batch_norm_2d(self)
158
+
159
+ @torch.jit.ignore
160
+ def set_grad_checkpointing(self, enable=True):
161
+ # FIXME support for non-transformer
162
+ pass
163
+
164
+ def stem(self, x):
165
+ x = self.act1(self.bn1(self.conv1(x)))
166
+ x = self.act2(self.bn2(self.conv2(x)))
167
+ x = self.act3(self.bn3(self.conv3(x)))
168
+ x = self.avgpool(x)
169
+ return x
170
+
171
+ def forward(self, x):
172
+ x = self.stem(x)
173
+ x = self.layer1(x)
174
+ x = self.layer2(x)
175
+ x = self.layer3(x)
176
+ x = self.layer4(x)
177
+ x = self.attnpool(x)
178
+
179
+ return x
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/openai.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ OpenAI pretrained model functions
2
+
3
+ Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
4
+ """
5
+
6
+ import os
7
+ import warnings
8
+ from typing import List, Optional, Union
9
+
10
+ import torch
11
+
12
+ from .model import build_model_from_openai_state_dict, convert_weights_to_lp, get_cast_dtype
13
+ from .pretrained import get_pretrained_url, list_pretrained_models_by_tag, download_pretrained_from_url
14
+
15
+ __all__ = ["list_openai_models", "load_openai_model"]
16
+
17
+
18
+ def list_openai_models() -> List[str]:
19
+ """Returns the names of available CLIP models"""
20
+ return list_pretrained_models_by_tag("openai")
21
+
22
+
23
+ def load_openai_model(
24
+ name: str,
25
+ precision: Optional[str] = None,
26
+ device: Optional[Union[str, torch.device]] = None,
27
+ jit: bool = True,
28
+ cache_dir: Optional[str] = None,
29
+ ):
30
+ """Load a CLIP model
31
+
32
+ Parameters
33
+ ----------
34
+ name : str
35
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
36
+ precision: str
37
+ Model precision, if None defaults to 'fp32' if device == 'cpu' else 'fp16'.
38
+ device : Union[str, torch.device]
39
+ The device to put the loaded model
40
+ jit : bool
41
+ Whether to load the optimized JIT model (default) or more hackable non-JIT model.
42
+ cache_dir : Optional[str]
43
+ The directory to cache the downloaded model weights
44
+
45
+ Returns
46
+ -------
47
+ model : torch.nn.Module
48
+ The CLIP model
49
+ preprocess : Callable[[PIL.Image], torch.Tensor]
50
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
51
+ """
52
+ if device is None:
53
+ device = "cuda" if torch.cuda.is_available() else "cpu"
54
+ if precision is None:
55
+ precision = "fp32" if device == "cpu" else "fp16"
56
+
57
+ if get_pretrained_url(name, "openai"):
58
+ model_path = download_pretrained_from_url(get_pretrained_url(name, "openai"), cache_dir=cache_dir)
59
+ elif os.path.isfile(name):
60
+ model_path = name
61
+ else:
62
+ raise RuntimeError(f"Model {name} not found; available models = {list_openai_models()}")
63
+
64
+ try:
65
+ # loading JIT archive
66
+ model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval()
67
+ state_dict = None
68
+ except RuntimeError:
69
+ # loading saved state dict
70
+ if jit:
71
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
72
+ jit = False
73
+ state_dict = torch.load(model_path, map_location="cpu")
74
+
75
+ if not jit:
76
+ # Build a non-jit model from the OpenAI jitted model state dict
77
+ cast_dtype = get_cast_dtype(precision)
78
+ try:
79
+ model = build_model_from_openai_state_dict(state_dict or model.state_dict(), cast_dtype=cast_dtype)
80
+ except KeyError:
81
+ sd = {k[7:]: v for k, v in state_dict["state_dict"].items()}
82
+ model = build_model_from_openai_state_dict(sd, cast_dtype=cast_dtype)
83
+
84
+ # model from OpenAI state dict is in manually cast fp16 mode, must be converted for AMP/fp32/bf16 use
85
+ model = model.to(device)
86
+ if precision.startswith("amp") or precision == "fp32":
87
+ model.float()
88
+ elif precision == "bf16":
89
+ convert_weights_to_lp(model, dtype=torch.bfloat16)
90
+
91
+ return model
92
+
93
+ # patch the device names
94
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
95
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
96
+
97
+ def patch_device(module):
98
+ try:
99
+ graphs = [module.graph] if hasattr(module, "graph") else []
100
+ except RuntimeError:
101
+ graphs = []
102
+
103
+ if hasattr(module, "forward1"):
104
+ graphs.append(module.forward1.graph)
105
+
106
+ for graph in graphs:
107
+ for node in graph.findAllNodes("prim::Constant"):
108
+ if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
109
+ node.copyAttributes(device_node)
110
+
111
+ model.apply(patch_device)
112
+ patch_device(model.encode_image)
113
+ patch_device(model.encode_text)
114
+
115
+ # patch dtype to float32 (typically for CPU)
116
+ if precision == "fp32":
117
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
118
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
119
+ float_node = float_input.node()
120
+
121
+ def patch_float(module):
122
+ try:
123
+ graphs = [module.graph] if hasattr(module, "graph") else []
124
+ except RuntimeError:
125
+ graphs = []
126
+
127
+ if hasattr(module, "forward1"):
128
+ graphs.append(module.forward1.graph)
129
+
130
+ for graph in graphs:
131
+ for node in graph.findAllNodes("aten::to"):
132
+ inputs = list(node.inputs())
133
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
134
+ if inputs[i].node()["value"] == 5:
135
+ inputs[i].node().copyAttributes(float_node)
136
+
137
+ model.apply(patch_float)
138
+ patch_float(model.encode_image)
139
+ patch_float(model.encode_text)
140
+ model.float()
141
+
142
+ # ensure image_size attr available at consistent location for both jit and non-jit
143
+ model.visual.image_size = model.input_resolution.item()
144
+ return model
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/pretrained.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import urllib
4
+ import warnings
5
+ from typing import Dict, Union
6
+
7
+ from tqdm import tqdm
8
+
9
+ try:
10
+ from huggingface_hub import hf_hub_download
11
+
12
+ _has_hf_hub = True
13
+ except ImportError:
14
+ hf_hub_download = None
15
+ _has_hf_hub = False
16
+
17
+
18
+ def _pcfg(url="", hf_hub="", filename="", mean=None, std=None):
19
+ return dict(
20
+ url=url,
21
+ hf_hub=hf_hub,
22
+ mean=mean,
23
+ std=std,
24
+ )
25
+
26
+
27
+ _VITB32 = dict(
28
+ openai=_pcfg("https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"),
29
+ laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"),
30
+ laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"),
31
+ laion2b_e16=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-laion2b_e16-af8dbd0c.pth"),
32
+ laion2b_s34b_b79k=_pcfg(hf_hub="laion/CLIP-ViT-B-32-laion2B-s34B-b79K/"),
33
+ )
34
+
35
+ _VITB32_quickgelu = dict(
36
+ openai=_pcfg("https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"),
37
+ laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"),
38
+ laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"),
39
+ )
40
+
41
+ _VITB16 = dict(
42
+ openai=_pcfg("https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt"),
43
+ laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e31-00efa78f.pt"),
44
+ laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e32-55e67d44.pt"),
45
+ laion2b_s34b_b88k=_pcfg(hf_hub="laion/CLIP-ViT-B-16-laion2B-s34B-b88K/"),
46
+ )
47
+
48
+ _EVAB16 = dict(
49
+ eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_B_psz14to16.pt"),
50
+ eva02=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_B_psz14to16.pt"),
51
+ eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_B_psz16_s8B.pt"),
52
+ eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_B_psz16_s8B.pt"),
53
+ )
54
+
55
+ _VITB16_PLUS_240 = dict(
56
+ laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e31-8fb26589.pt"),
57
+ laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e32-699c4b84.pt"),
58
+ )
59
+
60
+ _VITL14 = dict(
61
+ openai=_pcfg("https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt"),
62
+ laion400m_e31=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e31-69988bb6.pt"),
63
+ laion400m_e32=_pcfg("https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e32-3d133497.pt"),
64
+ laion2b_s32b_b82k=_pcfg(hf_hub="laion/CLIP-ViT-L-14-laion2B-s32B-b82K/", mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)),
65
+ )
66
+
67
+ _EVAL14 = dict(
68
+ eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_L_psz14.pt"),
69
+ eva02=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_L_psz14.pt"),
70
+ eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_s4B.pt"),
71
+ eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_s4B.pt"),
72
+ )
73
+
74
+ _VITL14_336 = dict(
75
+ openai=_pcfg("https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt"),
76
+ )
77
+
78
+ _EVAL14_336 = dict(
79
+ eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14_s6B.pt"),
80
+ eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14_s6B.pt"),
81
+ eva_clip_224to336=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_224to336.pt"),
82
+ eva02_clip_224to336=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_224to336.pt"),
83
+ )
84
+
85
+ _VITH14 = dict(
86
+ laion2b_s32b_b79k=_pcfg(hf_hub="laion/CLIP-ViT-H-14-laion2B-s32B-b79K/"),
87
+ )
88
+
89
+ _VITg14 = dict(
90
+ laion2b_s12b_b42k=_pcfg(hf_hub="laion/CLIP-ViT-g-14-laion2B-s12B-b42K/"),
91
+ laion2b_s34b_b88k=_pcfg(hf_hub="laion/CLIP-ViT-g-14-laion2B-s34B-b88K/"),
92
+ )
93
+
94
+ _EVAg14 = dict(
95
+ eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/"),
96
+ eva01=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_g_psz14.pt"),
97
+ eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_CLIP_g_14_psz14_s11B.pt"),
98
+ eva01_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_CLIP_g_14_psz14_s11B.pt"),
99
+ )
100
+
101
+ _EVAg14_PLUS = dict(
102
+ eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/"),
103
+ eva01=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_g_psz14.pt"),
104
+ eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14_s11B.pt"),
105
+ eva01_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14_s11B.pt"),
106
+ )
107
+
108
+ _VITbigG14 = dict(
109
+ laion2b_s39b_b160k=_pcfg(hf_hub="laion/CLIP-ViT-bigG-14-laion2B-39B-b160k/"),
110
+ )
111
+
112
+ _EVAbigE14 = dict(
113
+ eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_E_psz14.pt"),
114
+ eva02=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_E_psz14.pt"),
115
+ eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_s4B.pt"),
116
+ eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_s4B.pt"),
117
+ )
118
+
119
+ _EVAbigE14_PLUS = dict(
120
+ eva=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_E_psz14.pt"),
121
+ eva02=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_E_psz14.pt"),
122
+ eva_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt"),
123
+ eva02_clip=_pcfg(hf_hub="QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt"),
124
+ )
125
+
126
+ _EVA_8B = dict(
127
+ eva=_pcfg(hf_hub="BAAI/EVA-CLIP-8B/EVA_8B_psz14.bin"),
128
+ eva_clip=_pcfg(hf_hub="BAAI/EVA-CLIP-8B/EVA_CLIP_8B_psz14_s9B.pt"),
129
+ )
130
+
131
+ _EVA_8B_PLUS = dict(
132
+ eva_clip=_pcfg(hf_hub="BAAI/EVA-CLIP-8B-448/EVA_CLIP_8B_psz14_plus_s0.6B.pt"),
133
+ )
134
+
135
+
136
+ _PRETRAINED = {
137
+ # "ViT-B-32": _VITB32,
138
+ "OpenaiCLIP-B-32": _VITB32,
139
+ "OpenCLIP-B-32": _VITB32,
140
+ # "ViT-B-32-quickgelu": _VITB32_quickgelu,
141
+ "OpenaiCLIP-B-32-quickgelu": _VITB32_quickgelu,
142
+ "OpenCLIP-B-32-quickgelu": _VITB32_quickgelu,
143
+ # "ViT-B-16": _VITB16,
144
+ "OpenaiCLIP-B-16": _VITB16,
145
+ "OpenCLIP-B-16": _VITB16,
146
+ "EVA02-B-16": _EVAB16,
147
+ "EVA02-CLIP-B-16": _EVAB16,
148
+ # "ViT-B-16-plus-240": _VITB16_PLUS_240,
149
+ "OpenCLIP-B-16-plus-240": _VITB16_PLUS_240,
150
+ # "ViT-L-14": _VITL14,
151
+ "OpenaiCLIP-L-14": _VITL14,
152
+ "OpenCLIP-L-14": _VITL14,
153
+ "EVA02-L-14": _EVAL14,
154
+ "EVA02-CLIP-L-14": _EVAL14,
155
+ # "ViT-L-14-336": _VITL14_336,
156
+ "OpenaiCLIP-L-14-336": _VITL14_336,
157
+ "EVA02-CLIP-L-14-336": _EVAL14_336,
158
+ # "ViT-H-14": _VITH14,
159
+ # "ViT-g-14": _VITg14,
160
+ "OpenCLIP-H-14": _VITH14,
161
+ "OpenCLIP-g-14": _VITg14,
162
+ "EVA01-CLIP-g-14": _EVAg14,
163
+ "EVA01-CLIP-g-14-plus": _EVAg14_PLUS,
164
+ # "ViT-bigG-14": _VITbigG14,
165
+ "OpenCLIP-bigG-14": _VITbigG14,
166
+ "EVA02-CLIP-bigE-14": _EVAbigE14,
167
+ "EVA02-CLIP-bigE-14-plus": _EVAbigE14_PLUS,
168
+ "EVA-CLIP-8B": _EVA_8B,
169
+ "EVA-CLIP-8B-448": _EVA_8B_PLUS,
170
+ "EVA-CLIP-8B-plus": _EVA_8B_PLUS,
171
+ }
172
+
173
+
174
+ def _clean_tag(tag: str):
175
+ # normalize pretrained tags
176
+ return tag.lower().replace("-", "_")
177
+
178
+
179
+ def list_pretrained(as_str: bool = False):
180
+ """returns list of pretrained models
181
+ Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True
182
+ """
183
+ return [":".join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()]
184
+
185
+
186
+ def list_pretrained_models_by_tag(tag: str):
187
+ """return all models having the specified pretrain tag"""
188
+ models = []
189
+ tag = _clean_tag(tag)
190
+ for k in _PRETRAINED.keys():
191
+ if tag in _PRETRAINED[k]:
192
+ models.append(k)
193
+ return models
194
+
195
+
196
+ def list_pretrained_tags_by_model(model: str):
197
+ """return all pretrain tags for the specified model architecture"""
198
+ tags = []
199
+ if model in _PRETRAINED:
200
+ tags.extend(_PRETRAINED[model].keys())
201
+ return tags
202
+
203
+
204
+ def is_pretrained_cfg(model: str, tag: str):
205
+ if model not in _PRETRAINED:
206
+ return False
207
+ return _clean_tag(tag) in _PRETRAINED[model]
208
+
209
+
210
+ def get_pretrained_cfg(model: str, tag: str):
211
+ if model not in _PRETRAINED:
212
+ return {}
213
+ model_pretrained = _PRETRAINED[model]
214
+ return model_pretrained.get(_clean_tag(tag), {})
215
+
216
+
217
+ def get_pretrained_url(model: str, tag: str):
218
+ cfg = get_pretrained_cfg(model, _clean_tag(tag))
219
+ return cfg.get("url", "")
220
+
221
+
222
+ def download_pretrained_from_url(
223
+ url: str,
224
+ cache_dir: Union[str, None] = None,
225
+ ):
226
+ if not cache_dir:
227
+ cache_dir = os.path.expanduser("~/.cache/clip")
228
+ os.makedirs(cache_dir, exist_ok=True)
229
+ filename = os.path.basename(url)
230
+
231
+ if "openaipublic" in url:
232
+ expected_sha256 = url.split("/")[-2]
233
+ elif "mlfoundations" in url:
234
+ expected_sha256 = os.path.splitext(filename)[0].split("-")[-1]
235
+ else:
236
+ expected_sha256 = ""
237
+
238
+ download_target = os.path.join(cache_dir, filename)
239
+
240
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
241
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
242
+
243
+ if os.path.isfile(download_target):
244
+ if expected_sha256:
245
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256):
246
+ return download_target
247
+ else:
248
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
249
+ else:
250
+ return download_target
251
+
252
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
253
+ with tqdm(total=int(source.headers.get("Content-Length")), ncols=80, unit="iB", unit_scale=True) as loop:
254
+ while True:
255
+ buffer = source.read(8192)
256
+ if not buffer:
257
+ break
258
+
259
+ output.write(buffer)
260
+ loop.update(len(buffer))
261
+
262
+ if expected_sha256 and not hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256):
263
+ raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match")
264
+
265
+ return download_target
266
+
267
+
268
+ def has_hf_hub(necessary=False):
269
+ if not _has_hf_hub and necessary:
270
+ # if no HF Hub module installed, and it is necessary to continue, raise error
271
+ raise RuntimeError("Hugging Face hub model specified but package not installed. Run `pip install huggingface_hub`.")
272
+ return _has_hf_hub
273
+
274
+
275
+ def download_pretrained_from_hf(
276
+ model_id: str,
277
+ filename: str = "open_clip_pytorch_model.bin",
278
+ revision=None,
279
+ cache_dir: Union[str, None] = None,
280
+ ):
281
+ has_hf_hub(True)
282
+ cached_file = hf_hub_download(model_id, filename, revision=revision, cache_dir=cache_dir)
283
+ return cached_file
284
+
285
+
286
+ def download_pretrained(
287
+ cfg: Dict,
288
+ force_hf_hub: bool = False,
289
+ cache_dir: Union[str, None] = None,
290
+ ):
291
+ target = ""
292
+ if not cfg:
293
+ return target
294
+
295
+ download_url = cfg.get("url", "")
296
+ download_hf_hub = cfg.get("hf_hub", "")
297
+ if download_hf_hub and force_hf_hub:
298
+ # use HF hub even if url exists
299
+ download_url = ""
300
+
301
+ if download_url:
302
+ target = download_pretrained_from_url(download_url, cache_dir=cache_dir)
303
+ elif download_hf_hub:
304
+ has_hf_hub(True)
305
+ # we assume the hf_hub entries in pretrained config combine model_id + filename in
306
+ # 'org/model_name/filename.pt' form. To specify just the model id w/o filename and
307
+ # use 'open_clip_pytorch_model.bin' default, there must be a trailing slash 'org/model_name/'.
308
+ model_id, filename = os.path.split(download_hf_hub)
309
+ if filename:
310
+ target = download_pretrained_from_hf(model_id, filename=filename, cache_dir=cache_dir)
311
+ else:
312
+ target = download_pretrained_from_hf(model_id, cache_dir=cache_dir)
313
+
314
+ return target
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/rope.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import pi
2
+ import torch
3
+ from torch import nn
4
+ from einops import rearrange, repeat
5
+ import logging
6
+
7
+
8
+ def broadcat(tensors, dim=-1):
9
+ num_tensors = len(tensors)
10
+ shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
11
+ assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
12
+ shape_len = list(shape_lens)[0]
13
+ dim = (dim + shape_len) if dim < 0 else dim
14
+ dims = list(zip(*map(lambda t: list(t.shape), tensors)))
15
+ expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
16
+ assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), "invalid dimensions for broadcastable concatentation"
17
+ max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
18
+ expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
19
+ expanded_dims.insert(dim, (dim, dims[dim]))
20
+ expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
21
+ tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
22
+ return torch.cat(tensors, dim=dim)
23
+
24
+
25
+ def rotate_half(x):
26
+ x = rearrange(x, "... (d r) -> ... d r", r=2)
27
+ x1, x2 = x.unbind(dim=-1)
28
+ x = torch.stack((-x2, x1), dim=-1)
29
+ return rearrange(x, "... d r -> ... (d r)")
30
+
31
+
32
+ class VisionRotaryEmbedding(nn.Module):
33
+ def __init__(
34
+ self,
35
+ dim,
36
+ pt_seq_len,
37
+ ft_seq_len=None,
38
+ custom_freqs=None,
39
+ freqs_for="lang",
40
+ theta=10000,
41
+ max_freq=10,
42
+ num_freqs=1,
43
+ ):
44
+ super().__init__()
45
+ if custom_freqs:
46
+ freqs = custom_freqs
47
+ elif freqs_for == "lang":
48
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
49
+ elif freqs_for == "pixel":
50
+ freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
51
+ elif freqs_for == "constant":
52
+ freqs = torch.ones(num_freqs).float()
53
+ else:
54
+ raise ValueError(f"unknown modality {freqs_for}")
55
+
56
+ if ft_seq_len is None:
57
+ ft_seq_len = pt_seq_len
58
+ t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
59
+
60
+ freqs_h = torch.einsum("..., f -> ... f", t, freqs)
61
+ freqs_h = repeat(freqs_h, "... n -> ... (n r)", r=2)
62
+
63
+ freqs_w = torch.einsum("..., f -> ... f", t, freqs)
64
+ freqs_w = repeat(freqs_w, "... n -> ... (n r)", r=2)
65
+
66
+ freqs = broadcat((freqs_h[:, None, :], freqs_w[None, :, :]), dim=-1)
67
+
68
+ self.register_buffer("freqs_cos", freqs.cos())
69
+ self.register_buffer("freqs_sin", freqs.sin())
70
+
71
+ logging.info(f"Shape of rope freq: {self.freqs_cos.shape}")
72
+
73
+ def forward(self, t, start_index=0):
74
+ rot_dim = self.freqs_cos.shape[-1]
75
+ end_index = start_index + rot_dim
76
+ assert rot_dim <= t.shape[-1], f"feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}"
77
+ t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:]
78
+ t = (t * self.freqs_cos) + (rotate_half(t) * self.freqs_sin)
79
+
80
+ return torch.cat((t_left, t, t_right), dim=-1)
81
+
82
+
83
+ class VisionRotaryEmbeddingFast(nn.Module):
84
+ def __init__(self, dim, pt_seq_len, ft_seq_len=None, custom_freqs=None, freqs_for="lang", theta=10000, max_freq=10, num_freqs=1, patch_dropout=0.0):
85
+ super().__init__()
86
+ if custom_freqs:
87
+ freqs = custom_freqs
88
+ elif freqs_for == "lang":
89
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
90
+ elif freqs_for == "pixel":
91
+ freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
92
+ elif freqs_for == "constant":
93
+ freqs = torch.ones(num_freqs).float()
94
+ else:
95
+ raise ValueError(f"unknown modality {freqs_for}")
96
+
97
+ if ft_seq_len is None:
98
+ ft_seq_len = pt_seq_len
99
+ t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
100
+
101
+ freqs = torch.einsum("..., f -> ... f", t, freqs)
102
+ freqs = repeat(freqs, "... n -> ... (n r)", r=2)
103
+ freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
104
+
105
+ freqs_cos = freqs.cos().view(-1, freqs.shape[-1])
106
+ freqs_sin = freqs.sin().view(-1, freqs.shape[-1])
107
+
108
+ self.patch_dropout = patch_dropout
109
+
110
+ self.register_buffer("freqs_cos", freqs_cos)
111
+ self.register_buffer("freqs_sin", freqs_sin)
112
+
113
+ logging.info(f"Shape of rope freq: {self.freqs_cos.shape}")
114
+
115
+ def forward(self, t, patch_indices_keep=None):
116
+ if patch_indices_keep is not None:
117
+ batch = t.size()[0]
118
+ batch_indices = torch.arange(batch)
119
+ batch_indices = batch_indices[..., None]
120
+
121
+ freqs_cos = repeat(self.freqs_cos, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
122
+ freqs_sin = repeat(self.freqs_sin, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
123
+
124
+ freqs_cos = freqs_cos[batch_indices, patch_indices_keep]
125
+ freqs_cos = rearrange(freqs_cos, "n i m j -> n m i j")
126
+ freqs_sin = freqs_sin[batch_indices, patch_indices_keep]
127
+ freqs_sin = rearrange(freqs_sin, "n i m j -> n m i j")
128
+
129
+ return t * freqs_cos + rotate_half(t) * freqs_sin
130
+
131
+ return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/timm_model.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ timm model adapter
2
+
3
+ Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model.
4
+ """
5
+
6
+ import logging
7
+ from collections import OrderedDict
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+
12
+ try:
13
+ import timm
14
+ from timm.models.layers import Mlp, to_2tuple
15
+
16
+ try:
17
+ # old timm imports < 0.8.1
18
+ from timm.models.layers.attention_pool2d import RotAttentionPool2d
19
+ from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d
20
+ except ImportError:
21
+ # new timm imports >= 0.8.1
22
+ from timm.layers import RotAttentionPool2d
23
+ from timm.layers import AttentionPool2d as AbsAttentionPool2d
24
+ except ImportError:
25
+ timm = None
26
+
27
+ from .utils import freeze_batch_norm_2d
28
+
29
+
30
+ class TimmModel(nn.Module):
31
+ """timm model adapter
32
+ # FIXME this adapter is a work in progress, may change in ways that break weight compat
33
+ """
34
+
35
+ def __init__(self, model_name, embed_dim, image_size=224, pool="avg", proj="linear", proj_bias=False, drop=0.0, pretrained=False):
36
+ super().__init__()
37
+ if timm is None:
38
+ raise RuntimeError("Please `pip install timm` to use timm models.")
39
+
40
+ self.image_size = to_2tuple(image_size)
41
+ self.trunk = timm.create_model(model_name, pretrained=pretrained)
42
+ feat_size = self.trunk.default_cfg.get("pool_size", None)
43
+ feature_ndim = 1 if not feat_size else 2
44
+ if pool in ("abs_attn", "rot_attn"):
45
+ assert feature_ndim == 2
46
+ # if attn pooling used, remove both classifier and default pool
47
+ self.trunk.reset_classifier(0, global_pool="")
48
+ else:
49
+ # reset global pool if pool config set, otherwise leave as network default
50
+ reset_kwargs = dict(global_pool=pool) if pool else {}
51
+ self.trunk.reset_classifier(0, **reset_kwargs)
52
+ prev_chs = self.trunk.num_features
53
+
54
+ head_layers = OrderedDict()
55
+ if pool == "abs_attn":
56
+ head_layers["pool"] = AbsAttentionPool2d(prev_chs, feat_size=feat_size, out_features=embed_dim)
57
+ prev_chs = embed_dim
58
+ elif pool == "rot_attn":
59
+ head_layers["pool"] = RotAttentionPool2d(prev_chs, out_features=embed_dim)
60
+ prev_chs = embed_dim
61
+ else:
62
+ assert proj, "projection layer needed if non-attention pooling is used."
63
+
64
+ # NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used
65
+ if proj == "linear":
66
+ head_layers["drop"] = nn.Dropout(drop)
67
+ head_layers["proj"] = nn.Linear(prev_chs, embed_dim, bias=proj_bias)
68
+ elif proj == "mlp":
69
+ head_layers["mlp"] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=drop, bias=(True, proj_bias))
70
+
71
+ self.head = nn.Sequential(head_layers)
72
+
73
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
74
+ """lock modules
75
+ Args:
76
+ unlocked_groups (int): leave last n layer groups unlocked (default: 0)
77
+ """
78
+ if not unlocked_groups:
79
+ # lock full model
80
+ for param in self.trunk.parameters():
81
+ param.requires_grad = False
82
+ if freeze_bn_stats:
83
+ freeze_batch_norm_2d(self.trunk)
84
+ else:
85
+ # NOTE: partial freeze requires latest timm (master) branch and is subject to change
86
+ try:
87
+ # FIXME import here until API stable and in an official release
88
+ from timm.models.helpers import group_parameters, group_modules
89
+ except ImportError:
90
+ raise RuntimeError("Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`")
91
+ matcher = self.trunk.group_matcher()
92
+ gparams = group_parameters(self.trunk, matcher)
93
+ max_layer_id = max(gparams.keys())
94
+ max_layer_id = max_layer_id - unlocked_groups
95
+ for group_idx in range(max_layer_id + 1):
96
+ group = gparams[group_idx]
97
+ for param in group:
98
+ self.trunk.get_parameter(param).requires_grad = False
99
+ if freeze_bn_stats:
100
+ gmodules = group_modules(self.trunk, matcher, reverse=True)
101
+ gmodules = {k for k, v in gmodules.items() if v <= max_layer_id}
102
+ freeze_batch_norm_2d(self.trunk, gmodules)
103
+
104
+ @torch.jit.ignore
105
+ def set_grad_checkpointing(self, enable=True):
106
+ try:
107
+ self.trunk.set_grad_checkpointing(enable)
108
+ except Exception as e:
109
+ logging.warning("grad checkpointing not supported for this timm image tower, continuing without...")
110
+
111
+ def forward(self, x):
112
+ x = self.trunk(x)
113
+ x = self.head(x)
114
+ return x
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/tokenizer.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ CLIP tokenizer
2
+
3
+ Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
4
+ """
5
+
6
+ import gzip
7
+ import html
8
+ import os
9
+ from functools import lru_cache
10
+ from typing import Union, List
11
+
12
+ import ftfy
13
+ import regex as re
14
+ import torch
15
+
16
+ # https://stackoverflow.com/q/62691279
17
+ import os
18
+
19
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
20
+
21
+
22
+ @lru_cache()
23
+ def default_bpe():
24
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
25
+
26
+
27
+ @lru_cache()
28
+ def bytes_to_unicode():
29
+ """
30
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
31
+ The reversible bpe codes work on unicode strings.
32
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
33
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
34
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
35
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
36
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
37
+ """
38
+ bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
39
+ cs = bs[:]
40
+ n = 0
41
+ for b in range(2**8):
42
+ if b not in bs:
43
+ bs.append(b)
44
+ cs.append(2**8 + n)
45
+ n += 1
46
+ cs = [chr(n) for n in cs]
47
+ return dict(zip(bs, cs))
48
+
49
+
50
+ def get_pairs(word):
51
+ """Return set of symbol pairs in a word.
52
+ Word is represented as tuple of symbols (symbols being variable-length strings).
53
+ """
54
+ pairs = set()
55
+ prev_char = word[0]
56
+ for char in word[1:]:
57
+ pairs.add((prev_char, char))
58
+ prev_char = char
59
+ return pairs
60
+
61
+
62
+ def basic_clean(text):
63
+ text = ftfy.fix_text(text)
64
+ text = html.unescape(html.unescape(text))
65
+ return text.strip()
66
+
67
+
68
+ def whitespace_clean(text):
69
+ text = re.sub(r"\s+", " ", text)
70
+ text = text.strip()
71
+ return text
72
+
73
+
74
+ class SimpleTokenizer(object):
75
+ def __init__(self, bpe_path: str = default_bpe(), special_tokens=None):
76
+ self.byte_encoder = bytes_to_unicode()
77
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
78
+ merges = gzip.open(bpe_path).read().decode("utf-8").split("\n")
79
+ merges = merges[1 : 49152 - 256 - 2 + 1]
80
+ merges = [tuple(merge.split()) for merge in merges]
81
+ vocab = list(bytes_to_unicode().values())
82
+ vocab = vocab + [v + "</w>" for v in vocab]
83
+ for merge in merges:
84
+ vocab.append("".join(merge))
85
+ if not special_tokens:
86
+ special_tokens = ["<start_of_text>", "<end_of_text>"]
87
+ else:
88
+ special_tokens = ["<start_of_text>", "<end_of_text>"] + special_tokens
89
+ vocab.extend(special_tokens)
90
+ self.encoder = dict(zip(vocab, range(len(vocab))))
91
+ self.decoder = {v: k for k, v in self.encoder.items()}
92
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
93
+ self.cache = {t: t for t in special_tokens}
94
+ special = "|".join(special_tokens)
95
+ self.pat = re.compile(special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
96
+
97
+ self.vocab_size = len(self.encoder)
98
+ self.all_special_ids = [self.encoder[t] for t in special_tokens]
99
+
100
+ def bpe(self, token):
101
+ if token in self.cache:
102
+ return self.cache[token]
103
+ word = tuple(token[:-1]) + (token[-1] + "</w>",)
104
+ pairs = get_pairs(word)
105
+
106
+ if not pairs:
107
+ return token + "</w>"
108
+
109
+ while True:
110
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
111
+ if bigram not in self.bpe_ranks:
112
+ break
113
+ first, second = bigram
114
+ new_word = []
115
+ i = 0
116
+ while i < len(word):
117
+ try:
118
+ j = word.index(first, i)
119
+ new_word.extend(word[i:j])
120
+ i = j
121
+ except:
122
+ new_word.extend(word[i:])
123
+ break
124
+
125
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
126
+ new_word.append(first + second)
127
+ i += 2
128
+ else:
129
+ new_word.append(word[i])
130
+ i += 1
131
+ new_word = tuple(new_word)
132
+ word = new_word
133
+ if len(word) == 1:
134
+ break
135
+ else:
136
+ pairs = get_pairs(word)
137
+ word = " ".join(word)
138
+ self.cache[token] = word
139
+ return word
140
+
141
+ def encode(self, text):
142
+ bpe_tokens = []
143
+ text = whitespace_clean(basic_clean(text)).lower()
144
+ for token in re.findall(self.pat, text):
145
+ token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
146
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" "))
147
+ return bpe_tokens
148
+
149
+ def decode(self, tokens):
150
+ text = "".join([self.decoder[token] for token in tokens])
151
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors="replace").replace("</w>", " ")
152
+ return text
153
+
154
+
155
+ _tokenizer = SimpleTokenizer()
156
+
157
+
158
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor:
159
+ """
160
+ Returns the tokenized representation of given input string(s)
161
+
162
+ Parameters
163
+ ----------
164
+ texts : Union[str, List[str]]
165
+ An input string or a list of input strings to tokenize
166
+ context_length : int
167
+ The context length to use; all CLIP models use 77 as the context length
168
+
169
+ Returns
170
+ -------
171
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
172
+ """
173
+ if isinstance(texts, str):
174
+ texts = [texts]
175
+
176
+ sot_token = _tokenizer.encoder["<start_of_text>"]
177
+ eot_token = _tokenizer.encoder["<end_of_text>"]
178
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
179
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
180
+
181
+ for i, tokens in enumerate(all_tokens):
182
+ if len(tokens) > context_length:
183
+ tokens = tokens[:context_length] # Truncate
184
+ tokens[-1] = eot_token
185
+ result[i, : len(tokens)] = torch.tensor(tokens)
186
+
187
+ return result
188
+
189
+
190
+ class HFTokenizer:
191
+ "HuggingFace tokenizer wrapper"
192
+
193
+ def __init__(self, tokenizer_name: str):
194
+ from transformers import AutoTokenizer
195
+
196
+ self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
197
+
198
+ def __call__(self, texts: Union[str, List[str]], context_length: int = 77) -> torch.Tensor:
199
+ # same cleaning as for default tokenizer, except lowercasing
200
+ # adding lower (for case-sensitive tokenizers) will make it more robust but less sensitive to nuance
201
+ if isinstance(texts, str):
202
+ texts = [texts]
203
+ texts = [whitespace_clean(basic_clean(text)) for text in texts]
204
+ input_ids = self.tokenizer(texts, return_tensors="pt", max_length=context_length, padding="max_length", truncation=True).input_ids
205
+ return input_ids
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transform.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Sequence, Tuple
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torchvision.transforms.functional as F
6
+
7
+ from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, CenterCrop
8
+
9
+ from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
10
+
11
+
12
+ class ResizeMaxSize(nn.Module):
13
+
14
+ def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn="max", fill=0):
15
+ super().__init__()
16
+ if not isinstance(max_size, int):
17
+ raise TypeError(f"Size should be int. Got {type(max_size)}")
18
+ self.max_size = max_size
19
+ self.interpolation = interpolation
20
+ self.fn = min if fn == "min" else min
21
+ self.fill = fill
22
+
23
+ def forward(self, img):
24
+ if isinstance(img, torch.Tensor):
25
+ height, width = img.shape[:2]
26
+ else:
27
+ width, height = img.size
28
+ scale = self.max_size / float(max(height, width))
29
+ if scale != 1.0:
30
+ new_size = tuple(round(dim * scale) for dim in (height, width))
31
+ img = F.resize(img, new_size, self.interpolation)
32
+ pad_h = self.max_size - new_size[0]
33
+ pad_w = self.max_size - new_size[1]
34
+ img = F.pad(img, padding=[pad_w // 2, pad_h // 2, pad_w - pad_w // 2, pad_h - pad_h // 2], fill=self.fill)
35
+ return img
36
+
37
+
38
+ def _convert_to_rgb(image):
39
+ return image.convert("RGB")
40
+
41
+
42
+ # class CatGen(nn.Module):
43
+ # def __init__(self, num=4):
44
+ # self.num = num
45
+ # def mixgen_batch(image, text):
46
+ # batch_size = image.shape[0]
47
+ # index = np.random.permutation(batch_size)
48
+
49
+ # cat_images = []
50
+ # for i in range(batch_size):
51
+ # # image mixup
52
+ # image[i,:] = lam * image[i,:] + (1 - lam) * image[index[i],:]
53
+ # # text concat
54
+ # text[i] = tokenizer((str(text[i]) + " " + str(text[index[i]])))[0]
55
+ # text = torch.stack(text)
56
+ # return image, text
57
+
58
+
59
+ def image_transform(
60
+ image_size: int,
61
+ is_train: bool,
62
+ mean: Optional[Tuple[float, ...]] = None,
63
+ std: Optional[Tuple[float, ...]] = None,
64
+ resize_longest_max: bool = False,
65
+ fill_color: int = 0,
66
+ ):
67
+ mean = mean or OPENAI_DATASET_MEAN
68
+ if not isinstance(mean, (list, tuple)):
69
+ mean = (mean,) * 3
70
+
71
+ std = std or OPENAI_DATASET_STD
72
+ if not isinstance(std, (list, tuple)):
73
+ std = (std,) * 3
74
+
75
+ if isinstance(image_size, (list, tuple)) and image_size[0] == image_size[1]:
76
+ # for square size, pass size as int so that Resize() uses aspect preserving shortest edge
77
+ image_size = image_size[0]
78
+
79
+ normalize = Normalize(mean=mean, std=std)
80
+ if is_train:
81
+ return Compose(
82
+ [
83
+ RandomResizedCrop(image_size, scale=(0.9, 1.0), interpolation=InterpolationMode.BICUBIC),
84
+ _convert_to_rgb,
85
+ ToTensor(),
86
+ normalize,
87
+ ]
88
+ )
89
+ else:
90
+ if resize_longest_max:
91
+ transforms = [ResizeMaxSize(image_size, fill=fill_color)]
92
+ else:
93
+ transforms = [
94
+ Resize(image_size, interpolation=InterpolationMode.BICUBIC),
95
+ CenterCrop(image_size),
96
+ ]
97
+ transforms.extend(
98
+ [
99
+ _convert_to_rgb,
100
+ ToTensor(),
101
+ normalize,
102
+ ]
103
+ )
104
+ return Compose(transforms)
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/transformer.py ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from collections import OrderedDict
4
+ import math
5
+ from typing import Callable, Optional, Sequence
6
+ import numpy as np
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn import functional as F
10
+
11
+ try:
12
+ from timm.models.layers import trunc_normal_
13
+ except:
14
+ from timm.layers import trunc_normal_
15
+
16
+ from .rope import VisionRotaryEmbedding, VisionRotaryEmbeddingFast
17
+ from .utils import to_2tuple
18
+
19
+ if os.getenv("ENV_TYPE") == "deepspeed":
20
+ try:
21
+ import deepspeed
22
+ from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint
23
+ except:
24
+ print("Please 'pip install deepspeed'")
25
+ deepspeed = None
26
+ from torch.utils.checkpoint import checkpoint
27
+ else:
28
+ from torch.utils.checkpoint import checkpoint
29
+
30
+ try:
31
+ import xformers.ops as xops
32
+ except ImportError:
33
+ xops = None
34
+ # print("Please 'pip install xformers'")
35
+
36
+
37
+ class LayerNormFp32(nn.LayerNorm):
38
+ """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back)."""
39
+
40
+ def __init__(self, *args, **kwargs):
41
+ super().__init__(*args, **kwargs)
42
+
43
+ def forward(self, x: torch.Tensor):
44
+ output = F.layer_norm(
45
+ x.float(),
46
+ self.normalized_shape,
47
+ self.weight.float() if self.weight is not None else None,
48
+ self.bias.float() if self.bias is not None else None,
49
+ self.eps,
50
+ )
51
+ return output.type_as(x)
52
+
53
+
54
+ class LayerNorm(nn.LayerNorm):
55
+ """Subclass torch's LayerNorm (with cast back to input dtype)."""
56
+
57
+ def forward(self, x: torch.Tensor):
58
+ orig_type = x.dtype
59
+ x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
60
+ return x.to(orig_type)
61
+
62
+
63
+ class QuickGELU(nn.Module):
64
+ # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory
65
+ def forward(self, x: torch.Tensor):
66
+ return x * torch.sigmoid(1.702 * x)
67
+
68
+
69
+ class LayerScale(nn.Module):
70
+ def __init__(self, dim, init_values=1e-5, inplace=False):
71
+ super().__init__()
72
+ self.inplace = inplace
73
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
74
+
75
+ def forward(self, x):
76
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
77
+
78
+
79
+ class PatchDropout(nn.Module):
80
+ """
81
+ https://arxiv.org/abs/2212.00794
82
+ """
83
+
84
+ def __init__(self, prob, exclude_first_token=True):
85
+ super().__init__()
86
+ assert 0 <= prob < 1.0
87
+ self.prob = prob
88
+ self.exclude_first_token = exclude_first_token # exclude CLS token
89
+ logging.info(f"os.getenv('RoPE')={os.getenv('RoPE')}")
90
+
91
+ def forward(self, x):
92
+ if not self.training or self.prob == 0.0:
93
+ return x
94
+
95
+ if self.exclude_first_token:
96
+ cls_tokens, x = x[:, :1], x[:, 1:]
97
+ else:
98
+ cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1])
99
+
100
+ batch = x.size()[0]
101
+ num_tokens = x.size()[1]
102
+
103
+ batch_indices = torch.arange(batch)
104
+ batch_indices = batch_indices[..., None]
105
+
106
+ keep_prob = 1 - self.prob
107
+ num_patches_keep = max(1, int(num_tokens * keep_prob))
108
+
109
+ rand = torch.randn(batch, num_tokens)
110
+ patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices
111
+
112
+ x = x[batch_indices, patch_indices_keep]
113
+
114
+ if self.exclude_first_token:
115
+ x = torch.cat((cls_tokens, x), dim=1)
116
+
117
+ if self.training and os.getenv("RoPE") == "1":
118
+ return x, patch_indices_keep
119
+
120
+ return x
121
+
122
+
123
+ def _in_projection_packed(
124
+ q: torch.Tensor,
125
+ k: torch.Tensor,
126
+ v: torch.Tensor,
127
+ w: torch.Tensor,
128
+ b: Optional[torch.Tensor] = None,
129
+ ):
130
+ """
131
+ https://github.com/pytorch/pytorch/blob/db2a237763eb8693a20788be94f8c192e762baa8/torch/nn/functional.py#L4726
132
+ """
133
+ E = q.size(-1)
134
+ if k is v:
135
+ if q is k:
136
+ # self-attention
137
+ return F.linear(q, w, b).chunk(3, dim=-1)
138
+ else:
139
+ # encoder-decoder attention
140
+ w_q, w_kv = w.split([E, E * 2])
141
+ if b is None:
142
+ b_q = b_kv = None
143
+ else:
144
+ b_q, b_kv = b.split([E, E * 2])
145
+ return (F.linear(q, w_q, b_q),) + F.linear(k, w_kv, b_kv).chunk(2, dim=-1)
146
+ else:
147
+ w_q, w_k, w_v = w.chunk(3)
148
+ if b is None:
149
+ b_q = b_k = b_v = None
150
+ else:
151
+ b_q, b_k, b_v = b.chunk(3)
152
+ return F.linear(q, w_q, b_q), F.linear(k, w_k, b_k), F.linear(v, w_v, b_v)
153
+
154
+
155
+ class Attention(nn.Module):
156
+ def __init__(self, dim, num_heads=8, qkv_bias=True, scaled_cosine=False, scale_heads=False, logit_scale_max=math.log(1.0 / 0.01), attn_drop=0.0, proj_drop=0.0, xattn=False, rope=False):
157
+ super().__init__()
158
+ self.scaled_cosine = scaled_cosine
159
+ self.scale_heads = scale_heads
160
+ assert dim % num_heads == 0, "dim should be divisible by num_heads"
161
+ self.num_heads = num_heads
162
+ self.head_dim = dim // num_heads
163
+ self.scale = self.head_dim**-0.5
164
+ self.logit_scale_max = logit_scale_max
165
+
166
+ # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original
167
+ self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale)
168
+ if qkv_bias:
169
+ self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3))
170
+ else:
171
+ self.in_proj_bias = None
172
+
173
+ if self.scaled_cosine:
174
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
175
+ else:
176
+ self.logit_scale = None
177
+ self.attn_drop = nn.Dropout(attn_drop)
178
+ if self.scale_heads:
179
+ self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1)))
180
+ else:
181
+ self.head_scale = None
182
+ self.out_proj = nn.Linear(dim, dim)
183
+ self.out_drop = nn.Dropout(proj_drop)
184
+ self.xattn = xattn
185
+ self.xattn_drop = attn_drop
186
+ self.rope = rope
187
+
188
+ def forward(self, x, attn_mask: Optional[torch.Tensor] = None):
189
+ L, N, C = x.shape
190
+ q, k, v = F.linear(x, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1)
191
+ if self.xattn:
192
+ q = q.contiguous().view(L, N, self.num_heads, -1).transpose(0, 1)
193
+ k = k.contiguous().view(L, N, self.num_heads, -1).transpose(0, 1)
194
+ v = v.contiguous().view(L, N, self.num_heads, -1).transpose(0, 1)
195
+
196
+ x = xops.memory_efficient_attention(
197
+ q,
198
+ k,
199
+ v,
200
+ p=self.xattn_drop,
201
+ scale=self.scale if self.logit_scale is None else None,
202
+ attn_bias=xops.LowerTriangularMask() if attn_mask is not None else None,
203
+ )
204
+ else:
205
+ q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
206
+ k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
207
+ v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
208
+
209
+ if self.logit_scale is not None:
210
+ attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2))
211
+ logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()
212
+ attn = attn.view(N, self.num_heads, L, L) * logit_scale
213
+ attn = attn.view(-1, L, L)
214
+ else:
215
+ q = q * self.scale
216
+ attn = torch.bmm(q, k.transpose(-1, -2))
217
+
218
+ if attn_mask is not None:
219
+ if attn_mask.dtype == torch.bool:
220
+ new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
221
+ new_attn_mask.masked_fill_(attn_mask, float("-inf"))
222
+ attn_mask = new_attn_mask
223
+ attn += attn_mask
224
+
225
+ attn = attn.softmax(dim=-1)
226
+ attn = self.attn_drop(attn)
227
+
228
+ x = torch.bmm(attn, v)
229
+
230
+ if self.head_scale is not None:
231
+ x = x.view(N, self.num_heads, L, C) * self.head_scale
232
+ x = x.view(-1, L, C)
233
+ x = x.transpose(0, 1).reshape(L, N, C)
234
+ x = self.out_proj(x)
235
+ x = self.out_drop(x)
236
+ return x
237
+
238
+
239
+ class CustomAttention(nn.Module):
240
+ def __init__(self, dim, num_heads=8, qkv_bias=True, scaled_cosine=True, scale_heads=False, logit_scale_max=math.log(1.0 / 0.01), attn_drop=0.0, proj_drop=0.0, xattn=False):
241
+ super().__init__()
242
+ self.scaled_cosine = scaled_cosine
243
+ self.scale_heads = scale_heads
244
+ assert dim % num_heads == 0, "dim should be divisible by num_heads"
245
+ self.num_heads = num_heads
246
+ self.head_dim = dim // num_heads
247
+ self.scale = self.head_dim**-0.5
248
+ self.logit_scale_max = logit_scale_max
249
+
250
+ # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original
251
+ self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale)
252
+ if qkv_bias:
253
+ self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3))
254
+ else:
255
+ self.in_proj_bias = None
256
+
257
+ if self.scaled_cosine:
258
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
259
+ else:
260
+ self.logit_scale = None
261
+ self.attn_drop = nn.Dropout(attn_drop)
262
+ if self.scale_heads:
263
+ self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1)))
264
+ else:
265
+ self.head_scale = None
266
+ self.out_proj = nn.Linear(dim, dim)
267
+ self.out_drop = nn.Dropout(proj_drop)
268
+ self.xattn = xattn
269
+ self.xattn_drop = attn_drop
270
+
271
+ def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
272
+ q, k, v = _in_projection_packed(query, key, value, self.in_proj_weight, self.in_proj_bias)
273
+ N_q, B_q, C_q = q.shape
274
+ N_k, B_k, C_k = k.shape
275
+ N_v, B_v, C_v = v.shape
276
+ if self.xattn:
277
+ # B, N, C -> B, N, num_heads, C
278
+ q = q.permute(1, 0, 2).reshape(B_q, N_q, self.num_heads, -1)
279
+ k = k.permute(1, 0, 2).reshape(B_k, N_k, self.num_heads, -1)
280
+ v = v.permute(1, 0, 2).reshape(B_v, N_v, self.num_heads, -1)
281
+
282
+ x = xops.memory_efficient_attention(q, k, v, p=self.xattn_drop, scale=self.scale if self.logit_scale is None else None, attn_bias=xops.LowerTriangularMask() if attn_mask is not None else None)
283
+ else:
284
+ # B*H, L, C
285
+ q = q.contiguous().view(N_q, B_q * self.num_heads, -1).transpose(0, 1)
286
+ k = k.contiguous().view(N_k, B_k * self.num_heads, -1).transpose(0, 1)
287
+ v = v.contiguous().view(N_v, B_v * self.num_heads, -1).transpose(0, 1)
288
+
289
+ if self.logit_scale is not None:
290
+ # B*H, N_q, N_k
291
+ attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2))
292
+ logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()
293
+ attn = attn.view(B_q, self.num_heads, N_q, N_k) * logit_scale
294
+ attn = attn.view(-1, N_q, N_k)
295
+ else:
296
+ q = q * self.scale
297
+ attn = torch.bmm(q, k.transpose(-1, -2))
298
+
299
+ if attn_mask is not None:
300
+ if attn_mask.dtype == torch.bool:
301
+ new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
302
+ new_attn_mask.masked_fill_(attn_mask, float("-inf"))
303
+ attn_mask = new_attn_mask
304
+ attn += attn_mask
305
+
306
+ attn = attn.softmax(dim=-1)
307
+ attn = self.attn_drop(attn)
308
+
309
+ x = torch.bmm(attn, v)
310
+
311
+ if self.head_scale is not None:
312
+ x = x.view(B_q, self.num_heads, N_q, C_q) * self.head_scale
313
+ x = x.view(-1, N_q, C_q)
314
+ x = x.transpose(0, 1).reshape(N_q, B_q, C_q)
315
+ x = self.out_proj(x)
316
+ x = self.out_drop(x)
317
+ return x
318
+
319
+
320
+ class CustomResidualAttentionBlock(nn.Module):
321
+ def __init__(
322
+ self,
323
+ d_model: int,
324
+ n_head: int,
325
+ mlp_ratio: float = 4.0,
326
+ ls_init_value: float = None,
327
+ act_layer: Callable = nn.GELU,
328
+ norm_layer: Callable = LayerNorm,
329
+ scale_cosine_attn: bool = False,
330
+ scale_heads: bool = False,
331
+ scale_attn: bool = False,
332
+ scale_fc: bool = False,
333
+ cross_attn: bool = False,
334
+ xattn: bool = False,
335
+ ):
336
+ super().__init__()
337
+
338
+ self.ln_1 = norm_layer(d_model)
339
+ self.ln_1_k = norm_layer(d_model) if cross_attn else self.ln_1
340
+ self.ln_1_v = norm_layer(d_model) if cross_attn else self.ln_1
341
+ self.attn = CustomAttention(d_model, n_head, qkv_bias=True, attn_drop=0.0, proj_drop=0.0, scaled_cosine=scale_cosine_attn, scale_heads=scale_heads, xattn=xattn)
342
+
343
+ self.ln_attn = norm_layer(d_model) if scale_attn else nn.Identity()
344
+ self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
345
+
346
+ self.ln_2 = norm_layer(d_model)
347
+ mlp_width = int(d_model * mlp_ratio)
348
+ self.mlp = nn.Sequential(OrderedDict([("c_fc", nn.Linear(d_model, mlp_width)), ("ln", norm_layer(mlp_width) if scale_fc else nn.Identity()), ("gelu", act_layer()), ("c_proj", nn.Linear(mlp_width, d_model))]))
349
+
350
+ self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
351
+
352
+ def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
353
+ q = q + self.ls_1(self.ln_attn(self.attn(self.ln_1(q), self.ln_1_k(k), self.ln_1_v(v), attn_mask=attn_mask)))
354
+ q = q + self.ls_2(self.mlp(self.ln_2(q)))
355
+ return q
356
+
357
+
358
+ class CustomTransformer(nn.Module):
359
+ def __init__(
360
+ self,
361
+ width: int,
362
+ layers: int,
363
+ heads: int,
364
+ mlp_ratio: float = 4.0,
365
+ ls_init_value: float = None,
366
+ act_layer: Callable = nn.GELU,
367
+ norm_layer: Callable = LayerNorm,
368
+ scale_cosine_attn: bool = True,
369
+ scale_heads: bool = False,
370
+ scale_attn: bool = False,
371
+ scale_fc: bool = False,
372
+ cross_attn: bool = False,
373
+ xattn: bool = False,
374
+ ):
375
+ super().__init__()
376
+ self.width = width
377
+ self.layers = layers
378
+ self.grad_checkpointing = False
379
+ self.xattn = xattn
380
+
381
+ self.resblocks = nn.ModuleList(
382
+ [
383
+ CustomResidualAttentionBlock(
384
+ width,
385
+ heads,
386
+ mlp_ratio,
387
+ ls_init_value=ls_init_value,
388
+ act_layer=act_layer,
389
+ norm_layer=norm_layer,
390
+ scale_cosine_attn=scale_cosine_attn,
391
+ scale_heads=scale_heads,
392
+ scale_attn=scale_attn,
393
+ scale_fc=scale_fc,
394
+ cross_attn=cross_attn,
395
+ xattn=xattn,
396
+ )
397
+ for _ in range(layers)
398
+ ]
399
+ )
400
+
401
+ def get_cast_dtype(self) -> torch.dtype:
402
+ return self.resblocks[0].mlp.c_fc.weight.dtype
403
+
404
+ def forward(self, q: torch.Tensor, k: torch.Tensor = None, v: torch.Tensor = None, attn_mask: Optional[torch.Tensor] = None):
405
+ if k is None and v is None:
406
+ k = v = q
407
+ for r in self.resblocks:
408
+ if self.grad_checkpointing and not torch.jit.is_scripting():
409
+ q = checkpoint(r, q, k, v, attn_mask)
410
+ else:
411
+ q = r(q, k, v, attn_mask=attn_mask)
412
+ return q
413
+
414
+
415
+ class ResidualAttentionBlock(nn.Module):
416
+ def __init__(
417
+ self,
418
+ d_model: int,
419
+ n_head: int,
420
+ mlp_ratio: float = 4.0,
421
+ ls_init_value: float = None,
422
+ act_layer: Callable = nn.GELU,
423
+ norm_layer: Callable = LayerNorm,
424
+ xattn: bool = False,
425
+ ):
426
+ super().__init__()
427
+
428
+ self.ln_1 = norm_layer(d_model)
429
+ if xattn:
430
+ self.attn = Attention(d_model, n_head, xattn=True)
431
+ else:
432
+ self.attn = nn.MultiheadAttention(d_model, n_head)
433
+ self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
434
+
435
+ self.ln_2 = norm_layer(d_model)
436
+ mlp_width = int(d_model * mlp_ratio)
437
+ self.mlp = nn.Sequential(OrderedDict([("c_fc", nn.Linear(d_model, mlp_width)), ("gelu", act_layer()), ("c_proj", nn.Linear(mlp_width, d_model))]))
438
+
439
+ self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
440
+ self.xattn = xattn
441
+
442
+ def attention(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
443
+ attn_mask = attn_mask.to(x.dtype) if attn_mask is not None else None
444
+ if self.xattn:
445
+ return self.attn(x, attn_mask=attn_mask)
446
+ return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
447
+
448
+ def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
449
+ x = x + self.ls_1(self.attention(self.ln_1(x), attn_mask=attn_mask))
450
+ x = x + self.ls_2(self.mlp(self.ln_2(x)))
451
+ return x
452
+
453
+
454
+ class Transformer(nn.Module):
455
+ def __init__(
456
+ self,
457
+ width: int,
458
+ layers: int,
459
+ heads: int,
460
+ mlp_ratio: float = 4.0,
461
+ ls_init_value: float = None,
462
+ act_layer: Callable = nn.GELU,
463
+ norm_layer: Callable = LayerNorm,
464
+ xattn: bool = False,
465
+ ):
466
+ super().__init__()
467
+ self.width = width
468
+ self.layers = layers
469
+ self.grad_checkpointing = False
470
+
471
+ self.resblocks = nn.ModuleList([ResidualAttentionBlock(width, heads, mlp_ratio, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer, xattn=xattn) for _ in range(layers)])
472
+
473
+ def get_cast_dtype(self) -> torch.dtype:
474
+ return self.resblocks[0].mlp.c_fc.weight.dtype
475
+
476
+ def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
477
+ for r in self.resblocks:
478
+ if self.grad_checkpointing and not torch.jit.is_scripting():
479
+ x = checkpoint(r, x, attn_mask)
480
+ else:
481
+ x = r(x, attn_mask=attn_mask)
482
+ return x
483
+
484
+
485
+ class VisionTransformer(nn.Module):
486
+ def __init__(
487
+ self,
488
+ image_size: int,
489
+ patch_size: int,
490
+ width: int,
491
+ layers: int,
492
+ heads: int,
493
+ mlp_ratio: float,
494
+ ls_init_value: float = None,
495
+ patch_dropout: float = 0.0,
496
+ global_average_pool: bool = False,
497
+ output_dim: int = 512,
498
+ act_layer: Callable = nn.GELU,
499
+ norm_layer: Callable = LayerNorm,
500
+ xattn: bool = False,
501
+ ):
502
+ super().__init__()
503
+ self.image_size = to_2tuple(image_size)
504
+ self.patch_size = to_2tuple(patch_size)
505
+ self.grid_size = (self.image_size[0] // self.patch_size[0], self.image_size[1] // self.patch_size[1])
506
+ self.output_dim = output_dim
507
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
508
+
509
+ scale = width**-0.5
510
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
511
+ self.positional_embedding = nn.Parameter(scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width))
512
+
513
+ # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn
514
+ self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0.0 else nn.Identity()
515
+ self.ln_pre = norm_layer(width)
516
+
517
+ self.transformer = Transformer(width, layers, heads, mlp_ratio, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer, xattn=xattn)
518
+
519
+ self.global_average_pool = global_average_pool
520
+ self.ln_post = norm_layer(width)
521
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
522
+
523
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
524
+ for param in self.parameters():
525
+ param.requires_grad = False
526
+
527
+ if unlocked_groups != 0:
528
+ groups = [
529
+ [
530
+ self.conv1,
531
+ self.class_embedding,
532
+ self.positional_embedding,
533
+ self.ln_pre,
534
+ ],
535
+ *self.transformer.resblocks[:-1],
536
+ [
537
+ self.transformer.resblocks[-1],
538
+ self.ln_post,
539
+ ],
540
+ self.proj,
541
+ ]
542
+
543
+ def _unlock(x):
544
+ if isinstance(x, Sequence):
545
+ for g in x:
546
+ _unlock(g)
547
+ else:
548
+ if isinstance(x, torch.nn.Parameter):
549
+ x.requires_grad = True
550
+ else:
551
+ for p in x.parameters():
552
+ p.requires_grad = True
553
+
554
+ _unlock(groups[-unlocked_groups:])
555
+
556
+ def get_num_layers(self):
557
+ return self.transformer.layers
558
+
559
+ @torch.jit.ignore
560
+ def set_grad_checkpointing(self, enable=True):
561
+ self.transformer.grad_checkpointing = enable
562
+
563
+ @torch.jit.ignore
564
+ def no_weight_decay(self):
565
+ return {"positional_embedding", "class_embedding"}
566
+
567
+ def forward(self, x: torch.Tensor, return_all_features: bool = False):
568
+ x = self.conv1(x) # shape = [*, width, grid, grid]
569
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
570
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
571
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
572
+ x = x + self.positional_embedding.to(x.dtype)
573
+
574
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
575
+ x = self.patch_dropout(x)
576
+ x = self.ln_pre(x)
577
+
578
+ x = x.permute(1, 0, 2) # NLD -> LND
579
+ x = self.transformer(x)
580
+ x = x.permute(1, 0, 2) # LND -> NLD
581
+
582
+ if not return_all_features:
583
+ if self.global_average_pool:
584
+ x = x.mean(dim=1) # x = x[:,1:,:].mean(dim=1)
585
+ else:
586
+ x = x[:, 0]
587
+
588
+ x = self.ln_post(x)
589
+
590
+ if self.proj is not None:
591
+ x = x @ self.proj
592
+
593
+ return x
594
+
595
+
596
+ class TextTransformer(nn.Module):
597
+ def __init__(
598
+ self,
599
+ context_length: int = 77,
600
+ vocab_size: int = 49408,
601
+ width: int = 512,
602
+ heads: int = 8,
603
+ layers: int = 12,
604
+ ls_init_value: float = None,
605
+ output_dim: int = 512,
606
+ act_layer: Callable = nn.GELU,
607
+ norm_layer: Callable = LayerNorm,
608
+ xattn: bool = False,
609
+ attn_mask: bool = True,
610
+ ):
611
+ super().__init__()
612
+ self.context_length = context_length
613
+ self.vocab_size = vocab_size
614
+ self.width = width
615
+ self.output_dim = output_dim
616
+
617
+ self.token_embedding = nn.Embedding(vocab_size, width)
618
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, width))
619
+ self.transformer = Transformer(width=width, layers=layers, heads=heads, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer, xattn=xattn)
620
+
621
+ self.xattn = xattn
622
+ self.ln_final = norm_layer(width)
623
+ self.text_projection = nn.Parameter(torch.empty(width, output_dim))
624
+
625
+ if attn_mask:
626
+ self.register_buffer("attn_mask", self.build_attention_mask(), persistent=False)
627
+ else:
628
+ self.attn_mask = None
629
+
630
+ self.init_parameters()
631
+
632
+ def init_parameters(self):
633
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
634
+ nn.init.normal_(self.positional_embedding, std=0.01)
635
+
636
+ proj_std = (self.transformer.width**-0.5) * ((2 * self.transformer.layers) ** -0.5)
637
+ attn_std = self.transformer.width**-0.5
638
+ fc_std = (2 * self.transformer.width) ** -0.5
639
+ for block in self.transformer.resblocks:
640
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
641
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
642
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
643
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
644
+
645
+ if self.text_projection is not None:
646
+ nn.init.normal_(self.text_projection, std=self.transformer.width**-0.5)
647
+
648
+ @torch.jit.ignore
649
+ def set_grad_checkpointing(self, enable=True):
650
+ self.transformer.grad_checkpointing = enable
651
+
652
+ @torch.jit.ignore
653
+ def no_weight_decay(self):
654
+ # return {'positional_embedding', 'token_embedding'}
655
+ return {"positional_embedding"}
656
+
657
+ def get_num_layers(self):
658
+ return self.transformer.layers
659
+
660
+ def build_attention_mask(self):
661
+ # lazily create causal attention mask, with full attention between the vision tokens
662
+ # pytorch uses additive attention mask; fill with -inf
663
+ mask = torch.empty(self.context_length, self.context_length)
664
+ mask.fill_(float("-inf"))
665
+ mask.triu_(1) # zero out the lower diagonal
666
+ return mask
667
+
668
+ def forward(self, text, return_all_features: bool = False):
669
+ cast_dtype = self.transformer.get_cast_dtype()
670
+ x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
671
+
672
+ x = x + self.positional_embedding.to(cast_dtype)
673
+ x = x.permute(1, 0, 2) # NLD -> LND
674
+ x = self.transformer(x, attn_mask=self.attn_mask)
675
+ # x = self.transformer(x) # no attention mask is applied
676
+ x = x.permute(1, 0, 2) # LND -> NLD
677
+ x = self.ln_final(x)
678
+
679
+ if not return_all_features:
680
+ # x.shape = [batch_size, n_ctx, transformer.width]
681
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
682
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
683
+ return x
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/utils.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import repeat
2
+ import collections.abc
3
+ import logging
4
+ import math
5
+ import numpy as np
6
+
7
+ import torch
8
+ from torch import nn as nn
9
+ from torchvision.ops.misc import FrozenBatchNorm2d
10
+ import torch.nn.functional as F
11
+
12
+
13
+ # open CLIP
14
+ def resize_clip_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
15
+ # Rescale the grid of position embeddings when loading from state_dict
16
+ old_pos_embed = state_dict.get("visual.positional_embedding", None)
17
+ if old_pos_embed is None or not hasattr(model.visual, "grid_size"):
18
+ return
19
+ grid_size = to_2tuple(model.visual.grid_size)
20
+ extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
21
+ new_seq_len = grid_size[0] * grid_size[1] + extra_tokens
22
+ if new_seq_len == old_pos_embed.shape[0]:
23
+ return
24
+
25
+ if extra_tokens:
26
+ pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:]
27
+ else:
28
+ pos_emb_tok, pos_emb_img = None, old_pos_embed
29
+ old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img))))
30
+
31
+ logging.info("Resizing position embedding grid-size from %s to %s", old_grid_size, grid_size)
32
+ pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2)
33
+ pos_emb_img = F.interpolate(
34
+ pos_emb_img,
35
+ size=grid_size,
36
+ mode=interpolation,
37
+ align_corners=True,
38
+ )
39
+ pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0]
40
+ if pos_emb_tok is not None:
41
+ new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0)
42
+ else:
43
+ new_pos_embed = pos_emb_img
44
+ state_dict["visual.positional_embedding"] = new_pos_embed
45
+
46
+
47
+ def resize_visual_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
48
+ # Rescale the grid of position embeddings when loading from state_dict
49
+ old_pos_embed = state_dict.get("positional_embedding", None)
50
+ if old_pos_embed is None or not hasattr(model.visual, "grid_size"):
51
+ return
52
+ grid_size = to_2tuple(model.visual.grid_size)
53
+ extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
54
+ new_seq_len = grid_size[0] * grid_size[1] + extra_tokens
55
+ if new_seq_len == old_pos_embed.shape[0]:
56
+ return
57
+
58
+ if extra_tokens:
59
+ pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:]
60
+ else:
61
+ pos_emb_tok, pos_emb_img = None, old_pos_embed
62
+ old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img))))
63
+
64
+ logging.info("Resizing position embedding grid-size from %s to %s", old_grid_size, grid_size)
65
+ pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2)
66
+ pos_emb_img = F.interpolate(
67
+ pos_emb_img,
68
+ size=grid_size,
69
+ mode=interpolation,
70
+ align_corners=True,
71
+ )
72
+ pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0]
73
+ if pos_emb_tok is not None:
74
+ new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0)
75
+ else:
76
+ new_pos_embed = pos_emb_img
77
+ state_dict["positional_embedding"] = new_pos_embed
78
+
79
+
80
+ def resize_evaclip_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
81
+ all_keys = list(state_dict.keys())
82
+ # interpolate position embedding
83
+ if "visual.pos_embed" in state_dict:
84
+ pos_embed_checkpoint = state_dict["visual.pos_embed"]
85
+ embedding_size = pos_embed_checkpoint.shape[-1]
86
+ num_patches = model.visual.patch_embed.num_patches
87
+ # num_extra_tokens = model.visual.pos_embed.shape[-2] - num_patches
88
+ num_extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
89
+ # height (== width) for the checkpoint position embedding
90
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
91
+ # height (== width) for the new position embedding
92
+ new_size = int(num_patches**0.5)
93
+ # class_token and dist_token are kept unchanged
94
+ if orig_size != new_size:
95
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
96
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
97
+ # only the position tokens are interpolated
98
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
99
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
100
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=(new_size, new_size), mode="bicubic", align_corners=False)
101
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
102
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
103
+ state_dict["visual.pos_embed"] = new_pos_embed
104
+
105
+ patch_embed_proj = state_dict["visual.patch_embed.proj.weight"]
106
+ patch_size = model.visual.patch_embed.patch_size
107
+ state_dict["visual.patch_embed.proj.weight"] = torch.nn.functional.interpolate(patch_embed_proj.float(), size=patch_size, mode="bicubic", align_corners=False)
108
+
109
+
110
+ def resize_eva_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
111
+ all_keys = list(state_dict.keys())
112
+ # interpolate position embedding
113
+ if "pos_embed" in state_dict:
114
+ pos_embed_checkpoint = state_dict["pos_embed"]
115
+ embedding_size = pos_embed_checkpoint.shape[-1]
116
+ num_patches = model.visual.patch_embed.num_patches
117
+ # num_extra_tokens = model.visual.pos_embed.shape[-2] - num_patches
118
+ num_extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
119
+ # height (== width) for the checkpoint position embedding
120
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
121
+ # height (== width) for the new position embedding
122
+ new_size = int(num_patches**0.5)
123
+ # class_token and dist_token are kept unchanged
124
+ if orig_size != new_size:
125
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
126
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
127
+ # only the position tokens are interpolated
128
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
129
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
130
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=(new_size, new_size), mode="bicubic", align_corners=False)
131
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
132
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
133
+ state_dict["pos_embed"] = new_pos_embed
134
+
135
+ patch_embed_proj = state_dict["patch_embed.proj.weight"]
136
+ patch_size = model.visual.patch_embed.patch_size
137
+ state_dict["patch_embed.proj.weight"] = torch.nn.functional.interpolate(patch_embed_proj.float(), size=patch_size, mode="bicubic", align_corners=False)
138
+
139
+
140
+ def resize_rel_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1):
141
+ all_keys = list(state_dict.keys())
142
+ for key in all_keys:
143
+ if "relative_position_index" in key:
144
+ state_dict.pop(key)
145
+
146
+ if "relative_position_bias_table" in key:
147
+ rel_pos_bias = state_dict[key]
148
+ src_num_pos, num_attn_heads = rel_pos_bias.size()
149
+ dst_num_pos, _ = model.visual.state_dict()[key].size()
150
+ dst_patch_shape = model.visual.patch_embed.patch_shape
151
+ if dst_patch_shape[0] != dst_patch_shape[1]:
152
+ raise NotImplementedError()
153
+ num_extra_tokens = dst_num_pos - (dst_patch_shape[0] * 2 - 1) * (dst_patch_shape[1] * 2 - 1)
154
+ src_size = int((src_num_pos - num_extra_tokens) ** 0.5)
155
+ dst_size = int((dst_num_pos - num_extra_tokens) ** 0.5)
156
+ if src_size != dst_size:
157
+ print("Position interpolate for %s from %dx%d to %dx%d" % (key, src_size, src_size, dst_size, dst_size))
158
+ extra_tokens = rel_pos_bias[-num_extra_tokens:, :]
159
+ rel_pos_bias = rel_pos_bias[:-num_extra_tokens, :]
160
+
161
+ def geometric_progression(a, r, n):
162
+ return a * (1.0 - r**n) / (1.0 - r)
163
+
164
+ left, right = 1.01, 1.5
165
+ while right - left > 1e-6:
166
+ q = (left + right) / 2.0
167
+ gp = geometric_progression(1, q, src_size // 2)
168
+ if gp > dst_size // 2:
169
+ right = q
170
+ else:
171
+ left = q
172
+
173
+ # if q > 1.090307:
174
+ # q = 1.090307
175
+
176
+ dis = []
177
+ cur = 1
178
+ for i in range(src_size // 2):
179
+ dis.append(cur)
180
+ cur += q ** (i + 1)
181
+
182
+ r_ids = [-_ for _ in reversed(dis)]
183
+
184
+ x = r_ids + [0] + dis
185
+ y = r_ids + [0] + dis
186
+
187
+ t = dst_size // 2.0
188
+ dx = np.arange(-t, t + 0.1, 1.0)
189
+ dy = np.arange(-t, t + 0.1, 1.0)
190
+
191
+ print("Original positions = %s" % str(x))
192
+ print("Target positions = %s" % str(dx))
193
+
194
+ all_rel_pos_bias = []
195
+
196
+ for i in range(num_attn_heads):
197
+ z = rel_pos_bias[:, i].view(src_size, src_size).float().numpy()
198
+ f = F.interpolate.interp2d(x, y, z, kind="cubic")
199
+ all_rel_pos_bias.append(torch.Tensor(f(dx, dy)).contiguous().view(-1, 1).to(rel_pos_bias.device))
200
+
201
+ rel_pos_bias = torch.cat(all_rel_pos_bias, dim=-1)
202
+
203
+ new_rel_pos_bias = torch.cat((rel_pos_bias, extra_tokens), dim=0)
204
+ state_dict[key] = new_rel_pos_bias
205
+
206
+ # interpolate position embedding
207
+ if "pos_embed" in state_dict:
208
+ pos_embed_checkpoint = state_dict["pos_embed"]
209
+ embedding_size = pos_embed_checkpoint.shape[-1]
210
+ num_patches = model.visual.patch_embed.num_patches
211
+ num_extra_tokens = model.visual.pos_embed.shape[-2] - num_patches
212
+ # height (== width) for the checkpoint position embedding
213
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
214
+ # height (== width) for the new position embedding
215
+ new_size = int(num_patches**0.5)
216
+ # class_token and dist_token are kept unchanged
217
+ if orig_size != new_size:
218
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
219
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
220
+ # only the position tokens are interpolated
221
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
222
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
223
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens, size=(new_size, new_size), mode="bicubic", align_corners=False)
224
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
225
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
226
+ state_dict["pos_embed"] = new_pos_embed
227
+
228
+ patch_embed_proj = state_dict["patch_embed.proj.weight"]
229
+ patch_size = model.visual.patch_embed.patch_size
230
+ state_dict["patch_embed.proj.weight"] = torch.nn.functional.interpolate(patch_embed_proj.float(), size=patch_size, mode="bicubic", align_corners=False)
231
+
232
+
233
+ def freeze_batch_norm_2d(module, module_match={}, name=""):
234
+ """
235
+ Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
236
+ itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and
237
+ returned. Otherwise, the module is walked recursively and submodules are converted in place.
238
+
239
+ Args:
240
+ module (torch.nn.Module): Any PyTorch module.
241
+ module_match (dict): Dictionary of full module names to freeze (all if empty)
242
+ name (str): Full module name (prefix)
243
+
244
+ Returns:
245
+ torch.nn.Module: Resulting module
246
+
247
+ Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762
248
+ """
249
+ res = module
250
+ is_match = True
251
+ if module_match:
252
+ is_match = name in module_match
253
+ if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)):
254
+ res = FrozenBatchNorm2d(module.num_features)
255
+ res.num_features = module.num_features
256
+ res.affine = module.affine
257
+ if module.affine:
258
+ res.weight.data = module.weight.data.clone().detach()
259
+ res.bias.data = module.bias.data.clone().detach()
260
+ res.running_mean.data = module.running_mean.data
261
+ res.running_var.data = module.running_var.data
262
+ res.eps = module.eps
263
+ else:
264
+ for child_name, child in module.named_children():
265
+ full_child_name = ".".join([name, child_name]) if name else child_name
266
+ new_child = freeze_batch_norm_2d(child, module_match, full_child_name)
267
+ if new_child is not child:
268
+ res.add_module(child_name, new_child)
269
+ return res
270
+
271
+
272
+ # From PyTorch internals
273
+ def _ntuple(n):
274
+ def parse(x):
275
+ if isinstance(x, collections.abc.Iterable):
276
+ return x
277
+ return tuple(repeat(x, n))
278
+
279
+ return parse
280
+
281
+
282
+ to_1tuple = _ntuple(1)
283
+ to_2tuple = _ntuple(2)
284
+ to_3tuple = _ntuple(3)
285
+ to_4tuple = _ntuple(4)
286
+ to_ntuple = lambda n, x: _ntuple(n)(x)
287
+
288
+
289
+ def is_logging(args):
290
+ def is_global_master(args):
291
+ return args.rank == 0
292
+
293
+ def is_local_master(args):
294
+ return args.local_rank == 0
295
+
296
+ def is_master(args, local=False):
297
+ return is_local_master(args) if local else is_global_master(args)
298
+
299
+ return is_master
300
+
301
+
302
+ class AllGather(torch.autograd.Function):
303
+ """An autograd function that performs allgather on a tensor.
304
+ Performs all_gather operation on the provided tensors.
305
+ *** Warning ***: torch.distributed.all_gather has no gradient.
306
+ """
307
+
308
+ @staticmethod
309
+ def forward(ctx, tensor, rank, world_size):
310
+ tensors_gather = [torch.empty_like(tensor) for _ in range(world_size)]
311
+ torch.distributed.all_gather(tensors_gather, tensor)
312
+ ctx.rank = rank
313
+ ctx.batch_size = tensor.shape[0]
314
+ return torch.cat(tensors_gather, 0)
315
+
316
+ @staticmethod
317
+ def backward(ctx, grad_output):
318
+ return (grad_output[ctx.batch_size * ctx.rank : ctx.batch_size * (ctx.rank + 1)], None, None)
319
+
320
+
321
+ allgather = AllGather.apply
LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_vit.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Based on EVA, BEIT, timm and DeiT code bases
2
+ # https://github.com/baaivision/EVA
3
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm
4
+ # https://github.com/microsoft/unilm/tree/master/beit
5
+ # https://github.com/facebookresearch/deit/
6
+ # https://github.com/facebookresearch/dino
7
+ # --------------------------------------------------------'
8
+ # not tested yet
9
+ import math
10
+ from transformers import CLIPImageProcessor
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import torch.utils.checkpoint as checkpoint
16
+ from timm.models.layers import drop_path, to_2tuple, trunc_normal_
17
+ from .eva_clip import create_model_and_transforms, get_model_config
18
+ import torch
19
+ import torchvision
20
+ import time
21
+
22
+ from llava.utils import rank0_print
23
+
24
+
25
+ class EvaViTWrapper(nn.Module):
26
+ def __init__(self, vision_tower, args, delay_load=False):
27
+ super().__init__()
28
+
29
+ self.is_loaded = False
30
+ self.vision_tower_name = vision_tower
31
+ self.pretrained = args.vision_tower_pretrained
32
+ self.args = args
33
+
34
+ self.select_layer = args.mm_vision_select_layer
35
+ if self.select_layer < -1:
36
+ self.select_layer += 1
37
+ self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
38
+
39
+ self.model_config = get_model_config(self.vision_tower_name)
40
+
41
+ if not delay_load:
42
+ rank0_print(f"Loading vision tower: {vision_tower}")
43
+ self.load_model()
44
+ elif getattr(args, "unfreeze_mm_vision_tower", False):
45
+ # TODO: better detector is needed.
46
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
47
+ self.load_model()
48
+ elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts:
49
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
50
+ self.load_model()
51
+
52
+ def load_model(self):
53
+ rank0_print(f"Loading: {self.vision_tower_name}")
54
+ rank0_print(f"Pretrained: {self.pretrained}")
55
+ time_start = time.time()
56
+ model, _, image_processor = create_model_and_transforms(self.vision_tower_name, self.pretrained, force_custom_clip=True, precision="fp16")
57
+ time_end = time.time()
58
+ rank0_print(f"Loaded: {self.vision_tower_name} in {time_end - time_start:.2f}s")
59
+ self.device = next(model.parameters()).device
60
+ self.dtype = next(model.parameters()).dtype
61
+ if self.device.type != "meta":
62
+ model = model.to("cuda")
63
+ self.vision_tower = model.visual
64
+ resize_transform = [t for t in image_processor.transforms if isinstance(t, torchvision.transforms.Resize)][0]
65
+ normalize_transform = [t for t in image_processor.transforms if isinstance(t, torchvision.transforms.Normalize)][0]
66
+ self.resize_transform_size = resize_transform.size
67
+ self.image_processor = CLIPImageProcessor.from_pretrained(
68
+ "openai/clip-vit-large-patch14",
69
+ crop_size=resize_transform.size,
70
+ size={"shortest_edge": resize_transform.size},
71
+ image_mean=list(normalize_transform.mean),
72
+ image_std=list(normalize_transform.std),
73
+ )
74
+ rank0_print(f"Loaded image processor: {self.image_processor}")
75
+ self.vision_tower.requires_grad_(False)
76
+ self.is_loaded = True
77
+
78
+ def feature_select(self, image_features):
79
+ select_feature_type = self.select_feature
80
+
81
+ # if self.select_feature in ["slicefour_patch", "slicefour_cls_patch"]:
82
+ # select_every_k_layer = len(image_features) // 4
83
+ # image_features = torch.cat([image_features[i] for i in range(select_every_k_layer + self.select_layer, len(image_features), select_every_k_layer)], dim=-1)
84
+ # select_feature_type = select_feature_type.replace("slicefour_", "")
85
+ # elif self.select_feature in ["slice_m25811_f6_patch", "slice_m25811_f6_cls_patch"]:
86
+ # select_layers = [-1, -4, -7, -10, 6]
87
+ # image_features = torch.cat([image_features[i] for i in select_layers], dim=-1)
88
+ # select_feature_type = select_feature_type.replace("slice_m25811_f6_", "")
89
+ # else:
90
+ # image_features = image_features[self.select_layer]
91
+
92
+ if select_feature_type == "patch":
93
+ image_features = image_features[:, 1:]
94
+ elif select_feature_type == "cls_patch":
95
+ image_features = image_features
96
+ else:
97
+ raise ValueError(f"Unexpected select feature: {select_feature_type}")
98
+ return image_features
99
+
100
+ def train(self, mode=True):
101
+ self.training = mode
102
+
103
+ if self.is_loaded:
104
+ self.vision_tower.eval()
105
+
106
+ def forward(self, images):
107
+ if type(images) is list:
108
+ image_features = []
109
+ for image in images:
110
+ image_features = self.vision_tower.forward_features(image.to(self.dtype), return_all_features=True)
111
+ image_features = self.feature_select(image_features).to(self.dtype)
112
+ image_features.append(image_features)
113
+ else:
114
+ image_features = self.vision_tower.forward_features(images.to(self.dtype), return_all_features=True)
115
+ image_features = self.feature_select(image_features).to(self.dtype)
116
+
117
+ return image_features
118
+
119
+ @property
120
+ def dummy_feature(self):
121
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
122
+
123
+ @property
124
+ def hidden_size(self):
125
+ return self.model_config["vision_cfg"]["width"]
126
+
127
+ @property
128
+ def num_patches(self):
129
+ return (self.model_config["vision_cfg"]["image_size"] // self.model_config["vision_cfg"]["patch_size"]) ** 2
130
+
131
+ @property
132
+ def num_patches_per_side(self):
133
+ return self.model_config["vision_cfg"]["image_size"] // self.model_config["vision_cfg"]["patch_size"]
134
+
135
+ @property
136
+ def config(self):
137
+ return self.model_config
138
+
139
+ @property
140
+ def image_size(self):
141
+ return self.model_config["vision_cfg"]["image_size"]
LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_encoder.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from .eva_clip_processors import EvaClipImageTrainProcessor
5
+ from .eva_vit import EVAEncoderWrapper
6
+ from .factory import list_models, add_model_config, get_model_config
7
+
8
+ from llava.utils import rank0_print
9
+
10
+
11
+ class EvaClipVisionTower(nn.Module):
12
+ def __init__(self, vision_tower, args, delay_load=False):
13
+ super().__init__()
14
+
15
+ self.is_loaded = False
16
+ self.vision_tower_name = vision_tower
17
+ self.vision_tower_pretrained = args.vision_tower_pretrained
18
+ self.config = get_model_config(vision_tower)
19
+
20
+ if not delay_load:
21
+ rank0_print(f"Loading EVA ViT: {self.vision_tower_name}")
22
+ self.load_model()
23
+ elif getattr(args, "unfreeze_mm_vision_tower", False):
24
+ # TODO: better detector is needed.
25
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
26
+ self.load_model()
27
+ elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts:
28
+ rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
29
+ self.load_model()
30
+ else:
31
+ self.cfg_only = self.config
32
+
33
+ def load_model(self, device_map=None):
34
+ rank0_print(f"Pretrained: {self.vision_tower_pretrained}")
35
+ self.image_processor = EvaClipImageTrainProcessor(self.config["vision_cfg"]["image_size"])
36
+ self.vision_tower = EVAEncoderWrapper(self.vision_tower_pretrained, self.config)
37
+ rank0_print(f"Loaded image processor: {self.image_processor}")
38
+ self.vision_tower.requires_grad_(False)
39
+ self.is_loaded = True
40
+
41
+ def forward(self, images):
42
+ if type(images) is list:
43
+ image_features = []
44
+ for image in images:
45
+ image_feature = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0)).to(image.dtype)
46
+ image_features.append(image_feature)
47
+ else:
48
+ image_features = self.vision_tower(images.to(device=self.device, dtype=self.dtype)).to(images.dtype)
49
+
50
+ return image_features
51
+
52
+ @property
53
+ def dtype(self):
54
+ return self.vision_tower.dtype
55
+
56
+ @property
57
+ def device(self):
58
+ return self.vision_tower.device
59
+
60
+ @property
61
+ def hidden_size(self):
62
+ return self.config["vision_cfg"]["width"]
63
+
64
+ @property
65
+ def num_patches(self):
66
+ return (self.config["vision_cfg"]["image_size"] // self.config["vision_cfg"]["patch_size"]) ** 2
67
+
68
+ @property
69
+ def num_patches_per_side(self):
70
+ return self.config["vision_cfg"]["image_size"] // self.config["vision_cfg"]["patch_size"]
71
+
72
+ @property
73
+ def image_size(self):
74
+ return self.config["vision_cfg"]["image_size"]
LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_processors.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ # Adapted from https://github.com/baaivision/EVA/tree/master/EVA-CLIP
3
+ """
4
+
5
+ from torchvision import transforms
6
+ from torchvision.transforms.functional import InterpolationMode
7
+ from transformers.image_processing_utils import BatchFeature
8
+ from PIL import Image
9
+ from transformers.image_transforms import convert_to_rgb
10
+
11
+
12
+ class BaseProcessor:
13
+ def __init__(self):
14
+ self.transform = lambda x: x
15
+ return
16
+
17
+ def __call__(self, item):
18
+ return self.transform(item)
19
+
20
+
21
+ class EvaClipImageBaseProcessor(BaseProcessor):
22
+ def __init__(self, mean=None, std=None):
23
+ self.mean = (0.48145466, 0.4578275, 0.40821073) if mean is None else mean
24
+ self.std = (0.26862954, 0.26130258, 0.27577711) if std is None else std
25
+
26
+ self.normalize = transforms.Normalize(self.mean, self.std)
27
+
28
+ @property
29
+ def image_mean(self):
30
+ return self.mean
31
+
32
+
33
+ class EvaClipImageTrainProcessor(EvaClipImageBaseProcessor):
34
+ def __init__(self, image_size=224, mean=None, std=None, min_scale=0.5, max_scale=1.0):
35
+ super().__init__(mean=mean, std=std)
36
+
37
+ self.transform = transforms.Compose(
38
+ [
39
+ convert_to_rgb,
40
+ transforms.Resize(
41
+ image_size,
42
+ interpolation=InterpolationMode.BICUBIC,
43
+ ),
44
+ transforms.CenterCrop(image_size),
45
+ transforms.ToTensor(),
46
+ self.normalize,
47
+ ]
48
+ )
49
+
50
+ self.image_size = image_size
51
+
52
+ def preprocess(self, images, return_tensors):
53
+ if isinstance(images, Image.Image):
54
+ images = [images]
55
+ else:
56
+ assert isinstance(images, list)
57
+
58
+ transformed_images = [self.transform(image).numpy() for image in images]
59
+ data = {"pixel_values": transformed_images}
60
+
61
+ return BatchFeature(data=data, tensor_type=return_tensors)
62
+
63
+ def __call__(self, item):
64
+ return self.transform(item)
65
+
66
+ @property
67
+ def crop_size(self):
68
+ return {"height": self.image_size, "width": self.image_size}
69
+
70
+ @property
71
+ def size(self):
72
+ return {"shortest_edge": self.image_size}
LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_vit.py ADDED
@@ -0,0 +1,856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ # Adapted from https://github.com/baaivision/EVA/tree/master/EVA-CLIP
3
+ """
4
+
5
+ from math import pi
6
+ import torch
7
+ from torch import nn
8
+ from einops import rearrange, repeat
9
+ import logging
10
+ from llava.utils import rank0_print
11
+
12
+
13
+ def broadcat(tensors, dim=-1):
14
+ num_tensors = len(tensors)
15
+ shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
16
+ assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
17
+ shape_len = list(shape_lens)[0]
18
+ dim = (dim + shape_len) if dim < 0 else dim
19
+ dims = list(zip(*map(lambda t: list(t.shape), tensors)))
20
+ expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
21
+ assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), "invalid dimensions for broadcastable concatentation"
22
+ max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
23
+ expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
24
+ expanded_dims.insert(dim, (dim, dims[dim]))
25
+ expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
26
+ tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
27
+ return torch.cat(tensors, dim=dim)
28
+
29
+
30
+ def rotate_half(x):
31
+ x = rearrange(x, "... (d r) -> ... d r", r=2)
32
+ x1, x2 = x.unbind(dim=-1)
33
+ x = torch.stack((-x2, x1), dim=-1)
34
+ return rearrange(x, "... d r -> ... (d r)")
35
+
36
+
37
+ class VisionRotaryEmbeddingFast(nn.Module):
38
+ def __init__(self, dim, pt_seq_len, ft_seq_len=None, custom_freqs=None, freqs_for="lang", theta=10000, max_freq=10, num_freqs=1, patch_dropout=0.0):
39
+ super().__init__()
40
+ if custom_freqs:
41
+ freqs = custom_freqs
42
+ elif freqs_for == "lang":
43
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
44
+ elif freqs_for == "pixel":
45
+ freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
46
+ elif freqs_for == "constant":
47
+ freqs = torch.ones(num_freqs).float()
48
+ else:
49
+ raise ValueError(f"unknown modality {freqs_for}")
50
+
51
+ if ft_seq_len is None:
52
+ ft_seq_len = pt_seq_len
53
+ t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len
54
+
55
+ freqs = torch.einsum("..., f -> ... f", t, freqs)
56
+ freqs = repeat(freqs, "... n -> ... (n r)", r=2)
57
+ freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
58
+
59
+ freqs_cos = freqs.cos().view(-1, freqs.shape[-1])
60
+ freqs_sin = freqs.sin().view(-1, freqs.shape[-1])
61
+
62
+ self.patch_dropout = patch_dropout
63
+
64
+ self.register_buffer("freqs_cos", freqs_cos)
65
+ self.register_buffer("freqs_sin", freqs_sin)
66
+
67
+ logging.info(f"Shape of rope freq: {self.freqs_cos.shape}")
68
+
69
+ def forward(self, t, patch_indices_keep=None):
70
+ if patch_indices_keep is not None:
71
+ batch = t.size()[0]
72
+ batch_indices = torch.arange(batch)
73
+ batch_indices = batch_indices[..., None]
74
+
75
+ freqs_cos = repeat(self.freqs_cos, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
76
+ freqs_sin = repeat(self.freqs_sin, "i j -> n i m j", n=t.shape[0], m=t.shape[1])
77
+
78
+ freqs_cos = freqs_cos[batch_indices, patch_indices_keep]
79
+ freqs_cos = rearrange(freqs_cos, "n i m j -> n m i j")
80
+ freqs_sin = freqs_sin[batch_indices, patch_indices_keep]
81
+ freqs_sin = rearrange(freqs_sin, "n i m j -> n m i j")
82
+
83
+ return t * freqs_cos + rotate_half(t) * freqs_sin
84
+
85
+ return t * self.freqs_cos + rotate_half(t) * self.freqs_sin
86
+
87
+
88
+ class LayerNorm(nn.LayerNorm):
89
+ """Subclass torch's LayerNorm (with cast back to input dtype)."""
90
+
91
+ def forward(self, x: torch.Tensor):
92
+ orig_type = x.dtype
93
+ x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
94
+ return x.to(orig_type)
95
+
96
+
97
+ class PatchDropout(nn.Module):
98
+ """
99
+ https://arxiv.org/abs/2212.00794
100
+ """
101
+
102
+ def __init__(self, prob, exclude_first_token=True):
103
+ super().__init__()
104
+ assert 0 <= prob < 1.0
105
+ self.prob = prob
106
+ self.exclude_first_token = exclude_first_token # exclude CLS token
107
+ logging.info(f"os.getenv('RoPE')={os.getenv('RoPE')}")
108
+
109
+ def forward(self, x):
110
+ if not self.training or self.prob == 0.0:
111
+ return x
112
+
113
+ if self.exclude_first_token:
114
+ cls_tokens, x = x[:, :1], x[:, 1:]
115
+ else:
116
+ cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1])
117
+
118
+ batch = x.size()[0]
119
+ num_tokens = x.size()[1]
120
+
121
+ batch_indices = torch.arange(batch)
122
+ batch_indices = batch_indices[..., None]
123
+
124
+ keep_prob = 1 - self.prob
125
+ num_patches_keep = max(1, int(num_tokens * keep_prob))
126
+
127
+ rand = torch.randn(batch, num_tokens)
128
+ patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices
129
+
130
+ x = x[batch_indices, patch_indices_keep]
131
+
132
+ if self.exclude_first_token:
133
+ x = torch.cat((cls_tokens, x), dim=1)
134
+
135
+ if self.training and os.getenv("RoPE") == "1":
136
+ return x, patch_indices_keep
137
+
138
+ return x
139
+
140
+
141
+ # --------------------------------------------------------
142
+ # Adapted from https://github.com/microsoft/unilm/tree/master/beit
143
+ # --------------------------------------------------------
144
+ import math
145
+ import os
146
+ import torch.nn as nn
147
+ import torch.nn.functional as F
148
+
149
+ try:
150
+ from timm.models.layers import drop_path, to_2tuple, trunc_normal_
151
+ except:
152
+ from timm.layers import drop_path, to_2tuple, trunc_normal_
153
+
154
+ if os.getenv("ENV_TYPE") == "deepspeed":
155
+ try:
156
+ from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint
157
+ except:
158
+ from torch.utils.checkpoint import checkpoint
159
+ else:
160
+ from torch.utils.checkpoint import checkpoint
161
+
162
+ try:
163
+ import xformers.ops as xops
164
+ except ImportError:
165
+ xops = None
166
+ # print("Please 'pip install xformers'")
167
+
168
+
169
+ class DropPath(nn.Module):
170
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
171
+
172
+ def __init__(self, drop_prob=None):
173
+ super(DropPath, self).__init__()
174
+ self.drop_prob = drop_prob
175
+
176
+ def forward(self, x):
177
+ return drop_path(x, self.drop_prob, self.training)
178
+
179
+ def extra_repr(self) -> str:
180
+ return "p={}".format(self.drop_prob)
181
+
182
+
183
+ class Mlp(nn.Module):
184
+ def __init__(
185
+ self,
186
+ in_features,
187
+ hidden_features=None,
188
+ out_features=None,
189
+ act_layer=nn.GELU,
190
+ norm_layer=nn.LayerNorm,
191
+ drop=0.0,
192
+ subln=False,
193
+ ):
194
+ super().__init__()
195
+ out_features = out_features or in_features
196
+ hidden_features = hidden_features or in_features
197
+ self.fc1 = nn.Linear(in_features, hidden_features)
198
+ self.act = act_layer()
199
+
200
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
201
+
202
+ self.fc2 = nn.Linear(hidden_features, out_features)
203
+ self.drop = nn.Dropout(drop)
204
+
205
+ def forward(self, x):
206
+ x = self.fc1(x)
207
+ x = self.act(x)
208
+ # x = self.drop(x)
209
+ # commit this for the orignal BERT implement
210
+ x = self.ffn_ln(x)
211
+
212
+ x = self.fc2(x)
213
+ x = self.drop(x)
214
+ return x
215
+
216
+
217
+ class SwiGLU(nn.Module):
218
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0, norm_layer=nn.LayerNorm, subln=False):
219
+ super().__init__()
220
+ out_features = out_features or in_features
221
+ hidden_features = hidden_features or in_features
222
+
223
+ self.w1 = nn.Linear(in_features, hidden_features)
224
+ self.w2 = nn.Linear(in_features, hidden_features)
225
+
226
+ self.act = act_layer()
227
+ self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
228
+ self.w3 = nn.Linear(hidden_features, out_features)
229
+
230
+ self.drop = nn.Dropout(drop)
231
+
232
+ def forward(self, x):
233
+ x1 = self.w1(x)
234
+ x2 = self.w2(x)
235
+ hidden = self.act(x1) * x2
236
+ x = self.ffn_ln(hidden)
237
+ x = self.w3(x)
238
+ x = self.drop(x)
239
+ return x
240
+
241
+
242
+ class Attention(nn.Module):
243
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, window_size=None, attn_head_dim=None, xattn=False, rope=None, subln=False, norm_layer=nn.LayerNorm):
244
+ super().__init__()
245
+ self.num_heads = num_heads
246
+ head_dim = dim // num_heads
247
+ if attn_head_dim is not None:
248
+ head_dim = attn_head_dim
249
+ all_head_dim = head_dim * self.num_heads
250
+ self.scale = qk_scale or head_dim**-0.5
251
+
252
+ self.subln = subln
253
+ if self.subln:
254
+ self.q_proj = nn.Linear(dim, all_head_dim, bias=False)
255
+ self.k_proj = nn.Linear(dim, all_head_dim, bias=False)
256
+ self.v_proj = nn.Linear(dim, all_head_dim, bias=False)
257
+ else:
258
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
259
+
260
+ if qkv_bias:
261
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
262
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
263
+ else:
264
+ self.q_bias = None
265
+ self.v_bias = None
266
+
267
+ if window_size:
268
+ self.window_size = window_size
269
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
270
+ self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
271
+ # cls to token & token 2 cls & cls to cls
272
+
273
+ # get pair-wise relative position index for each token inside the window
274
+ coords_h = torch.arange(window_size[0])
275
+ coords_w = torch.arange(window_size[1])
276
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
277
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
278
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
279
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
280
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
281
+ relative_coords[:, :, 1] += window_size[1] - 1
282
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
283
+ relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
284
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
285
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
286
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
287
+ relative_position_index[0, 0] = self.num_relative_distance - 1
288
+
289
+ self.register_buffer("relative_position_index", relative_position_index)
290
+ else:
291
+ self.window_size = None
292
+ self.relative_position_bias_table = None
293
+ self.relative_position_index = None
294
+
295
+ self.attn_drop = nn.Dropout(attn_drop)
296
+ self.inner_attn_ln = norm_layer(all_head_dim) if subln else nn.Identity()
297
+ # self.proj = nn.Linear(all_head_dim, all_head_dim)
298
+ self.proj = nn.Linear(all_head_dim, dim)
299
+ self.proj_drop = nn.Dropout(proj_drop)
300
+ self.xattn = xattn
301
+ self.xattn_drop = attn_drop
302
+
303
+ self.rope = rope
304
+
305
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
306
+ B, N, C = x.shape
307
+ if self.subln:
308
+ q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
309
+ k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
310
+ v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
311
+
312
+ q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C
313
+ k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
314
+ v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
315
+ else:
316
+
317
+ qkv_bias = None
318
+ if self.q_bias is not None:
319
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
320
+
321
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
322
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C
323
+ q, k, v = qkv[0], qkv[1], qkv[2]
324
+
325
+ if self.rope:
326
+ # slightly fast impl
327
+ q_t = q[:, :, 1:, :]
328
+ ro_q_t = self.rope(q_t)
329
+ q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v)
330
+
331
+ k_t = k[:, :, 1:, :]
332
+ ro_k_t = self.rope(k_t)
333
+ k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v)
334
+
335
+ if self.xattn and xops is not None:
336
+ q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C
337
+ k = k.permute(0, 2, 1, 3)
338
+ v = v.permute(0, 2, 1, 3)
339
+
340
+ x = xops.memory_efficient_attention(
341
+ q,
342
+ k,
343
+ v,
344
+ p=self.xattn_drop,
345
+ scale=self.scale,
346
+ )
347
+ x = x.reshape(B, N, -1)
348
+ x = self.inner_attn_ln(x)
349
+ x = self.proj(x)
350
+ x = self.proj_drop(x)
351
+ else:
352
+ q = q * self.scale
353
+ attn = q @ k.transpose(-2, -1)
354
+
355
+ if self.relative_position_bias_table is not None:
356
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
357
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
358
+ attn = attn + relative_position_bias.unsqueeze(0).type_as(attn)
359
+
360
+ if rel_pos_bias is not None:
361
+ attn = attn + rel_pos_bias.type_as(attn)
362
+
363
+ if attn_mask is not None:
364
+ attn_mask = attn_mask.bool()
365
+ attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf"))
366
+
367
+ attn = attn.softmax(dim=-1)
368
+ attn = self.attn_drop(attn)
369
+
370
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
371
+ x = self.inner_attn_ln(x)
372
+ x = self.proj(x)
373
+ x = self.proj_drop(x)
374
+ return x
375
+
376
+
377
+ class Block(nn.Module):
378
+
379
+ def __init__(
380
+ self,
381
+ dim,
382
+ num_heads,
383
+ mlp_ratio=4.0,
384
+ qkv_bias=False,
385
+ qk_scale=None,
386
+ drop=0.0,
387
+ attn_drop=0.0,
388
+ drop_path=0.0,
389
+ init_values=None,
390
+ act_layer=nn.GELU,
391
+ norm_layer=nn.LayerNorm,
392
+ window_size=None,
393
+ attn_head_dim=None,
394
+ xattn=False,
395
+ rope=None,
396
+ postnorm=False,
397
+ subln=False,
398
+ naiveswiglu=False,
399
+ ):
400
+ super().__init__()
401
+ self.norm1 = norm_layer(dim)
402
+ self.attn = Attention(
403
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim, xattn=xattn, rope=rope, subln=subln, norm_layer=norm_layer
404
+ )
405
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
406
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
407
+ self.norm2 = norm_layer(dim)
408
+ mlp_hidden_dim = int(dim * mlp_ratio)
409
+
410
+ if naiveswiglu:
411
+ self.mlp = SwiGLU(
412
+ in_features=dim,
413
+ hidden_features=mlp_hidden_dim,
414
+ subln=subln,
415
+ norm_layer=norm_layer,
416
+ )
417
+ else:
418
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, subln=subln, drop=drop)
419
+
420
+ if init_values is not None and init_values > 0:
421
+ self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
422
+ self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
423
+ else:
424
+ self.gamma_1, self.gamma_2 = None, None
425
+
426
+ self.postnorm = postnorm
427
+
428
+ def forward(self, x, rel_pos_bias=None, attn_mask=None):
429
+ if self.gamma_1 is None:
430
+ if self.postnorm:
431
+ x = x + self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
432
+ x = x + self.drop_path(self.norm2(self.mlp(x)))
433
+ else:
434
+ x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
435
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
436
+ else:
437
+ if self.postnorm:
438
+ x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)))
439
+ x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x)))
440
+ else:
441
+ x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))
442
+ x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
443
+ return x
444
+
445
+
446
+ class PatchEmbed(nn.Module):
447
+ """Image to Patch Embedding"""
448
+
449
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
450
+ super().__init__()
451
+ img_size = to_2tuple(img_size)
452
+ patch_size = to_2tuple(patch_size)
453
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
454
+ self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
455
+ self.img_size = img_size
456
+ self.patch_size = patch_size
457
+ self.num_patches = num_patches
458
+
459
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
460
+
461
+ def forward(self, x, **kwargs):
462
+ B, C, H, W = x.shape
463
+ # FIXME look at relaxing size constraints
464
+ assert H == self.img_size[0] and W == self.img_size[1], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
465
+ x = self.proj(x).flatten(2).transpose(1, 2)
466
+ return x
467
+
468
+
469
+ class RelativePositionBias(nn.Module):
470
+
471
+ def __init__(self, window_size, num_heads):
472
+ super().__init__()
473
+ self.window_size = window_size
474
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
475
+ self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH
476
+ # cls to token & token 2 cls & cls to cls
477
+
478
+ # get pair-wise relative position index for each token inside the window
479
+ coords_h = torch.arange(window_size[0])
480
+ coords_w = torch.arange(window_size[1])
481
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
482
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
483
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
484
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
485
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
486
+ relative_coords[:, :, 1] += window_size[1] - 1
487
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
488
+ relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
489
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
490
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
491
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
492
+ relative_position_index[0, 0] = self.num_relative_distance - 1
493
+
494
+ self.register_buffer("relative_position_index", relative_position_index)
495
+
496
+ def forward(self):
497
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
498
+ return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
499
+
500
+
501
+ class EVAVisionTransformer(nn.Module):
502
+ """Vision Transformer with support for patch or hybrid CNN input stage"""
503
+
504
+ def __init__(
505
+ self,
506
+ img_size=224,
507
+ patch_size=16,
508
+ in_chans=3,
509
+ num_classes=1000,
510
+ embed_dim=768,
511
+ depth=12,
512
+ num_heads=12,
513
+ mlp_ratio=4.0,
514
+ qkv_bias=False,
515
+ qk_scale=None,
516
+ drop_rate=0.0,
517
+ attn_drop_rate=0.0,
518
+ drop_path_rate=0.0,
519
+ norm_layer=nn.LayerNorm,
520
+ init_values=None,
521
+ patch_dropout=0.0,
522
+ use_abs_pos_emb=True,
523
+ use_rel_pos_bias=False,
524
+ use_shared_rel_pos_bias=False,
525
+ rope=False,
526
+ use_mean_pooling=True,
527
+ init_scale=0.001,
528
+ grad_checkpointing=False,
529
+ xattn=False,
530
+ postnorm=False,
531
+ pt_hw_seq_len=16,
532
+ intp_freq=False,
533
+ naiveswiglu=False,
534
+ subln=False,
535
+ ):
536
+ super().__init__()
537
+ self.image_size = img_size
538
+ self.num_classes = num_classes
539
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
540
+
541
+ self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
542
+ num_patches = self.patch_embed.num_patches
543
+
544
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
545
+ # self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
546
+ if use_abs_pos_emb:
547
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
548
+ else:
549
+ self.pos_embed = None
550
+ self.pos_drop = nn.Dropout(p=drop_rate)
551
+
552
+ if use_shared_rel_pos_bias:
553
+ self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads)
554
+ else:
555
+ self.rel_pos_bias = None
556
+
557
+ if rope:
558
+ half_head_dim = embed_dim // num_heads // 2
559
+ hw_seq_len = img_size // patch_size
560
+ self.rope = VisionRotaryEmbeddingFast(
561
+ dim=half_head_dim,
562
+ pt_seq_len=pt_hw_seq_len,
563
+ ft_seq_len=hw_seq_len if intp_freq else None,
564
+ # patch_dropout=patch_dropout
565
+ )
566
+ else:
567
+ self.rope = None
568
+
569
+ self.naiveswiglu = naiveswiglu
570
+
571
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
572
+ self.use_rel_pos_bias = use_rel_pos_bias
573
+ self.blocks = nn.ModuleList(
574
+ [
575
+ Block(
576
+ dim=embed_dim,
577
+ num_heads=num_heads,
578
+ mlp_ratio=mlp_ratio,
579
+ qkv_bias=qkv_bias,
580
+ qk_scale=qk_scale,
581
+ drop=drop_rate,
582
+ attn_drop=attn_drop_rate,
583
+ drop_path=dpr[i],
584
+ norm_layer=norm_layer,
585
+ init_values=init_values,
586
+ window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None,
587
+ xattn=xattn,
588
+ rope=self.rope,
589
+ postnorm=postnorm,
590
+ subln=subln,
591
+ naiveswiglu=naiveswiglu,
592
+ )
593
+ for i in range(depth)
594
+ ]
595
+ )
596
+ self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim)
597
+ self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None
598
+ self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
599
+
600
+ if self.pos_embed is not None:
601
+ trunc_normal_(self.pos_embed, std=0.02)
602
+
603
+ trunc_normal_(self.cls_token, std=0.02)
604
+ # trunc_normal_(self.mask_token, std=.02)
605
+
606
+ self.apply(self._init_weights)
607
+ self.fix_init_weight()
608
+
609
+ if isinstance(self.head, nn.Linear):
610
+ trunc_normal_(self.head.weight, std=0.02)
611
+ self.head.weight.data.mul_(init_scale)
612
+ self.head.bias.data.mul_(init_scale)
613
+
614
+ # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn
615
+ self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0.0 else nn.Identity()
616
+
617
+ self.grad_checkpointing = grad_checkpointing
618
+
619
+ def fix_init_weight(self):
620
+ def rescale(param, layer_id):
621
+ param.div_(math.sqrt(2.0 * layer_id))
622
+
623
+ for layer_id, layer in enumerate(self.blocks):
624
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
625
+ if self.naiveswiglu:
626
+ rescale(layer.mlp.w3.weight.data, layer_id + 1)
627
+ else:
628
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
629
+
630
+ def get_cast_dtype(self) -> torch.dtype:
631
+ return self.blocks[0].mlp.fc2.weight.dtype
632
+
633
+ def _init_weights(self, m):
634
+ if isinstance(m, nn.Linear):
635
+ trunc_normal_(m.weight, std=0.02)
636
+ if m.bias is not None:
637
+ nn.init.constant_(m.bias, 0)
638
+ elif isinstance(m, nn.LayerNorm):
639
+ nn.init.constant_(m.bias, 0)
640
+ nn.init.constant_(m.weight, 1.0)
641
+
642
+ def get_num_layers(self):
643
+ return len(self.blocks)
644
+
645
+ def lock(self, unlocked_groups=0, freeze_bn_stats=False):
646
+ assert unlocked_groups == 0, "partial locking not currently supported for this model"
647
+ for param in self.parameters():
648
+ param.requires_grad = False
649
+
650
+ @torch.jit.ignore
651
+ def set_grad_checkpointing(self, enable=True):
652
+ self.grad_checkpointing = enable
653
+
654
+ @torch.jit.ignore
655
+ def no_weight_decay(self):
656
+ return {"pos_embed", "cls_token"}
657
+
658
+ def get_classifier(self):
659
+ return self.head
660
+
661
+ def reset_classifier(self, num_classes, global_pool=""):
662
+ self.num_classes = num_classes
663
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
664
+
665
+ def forward_features(self, x, return_all_features=False):
666
+
667
+ x = self.patch_embed(x)
668
+ batch_size, seq_len, _ = x.size()
669
+
670
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
671
+ x = torch.cat((cls_tokens, x), dim=1)
672
+ if self.pos_embed is not None:
673
+ x = x + self.pos_embed
674
+ x = self.pos_drop(x)
675
+
676
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
677
+ if os.getenv("RoPE") == "1":
678
+ if self.training and not isinstance(self.patch_dropout, nn.Identity):
679
+ x, patch_indices_keep = self.patch_dropout(x)
680
+ # Directly pass patch_indices_keep to self.rope.forward
681
+ x = self.rope.forward(x, patch_indices_keep=patch_indices_keep)
682
+ else:
683
+ # Pass None or omit the patch_indices_keep argument for default behavior
684
+ x = self.rope.forward(x, patch_indices_keep=None)
685
+ x = self.patch_dropout(x)
686
+ else:
687
+ x = self.patch_dropout(x)
688
+
689
+ rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
690
+ for i, blk in enumerate(self.blocks):
691
+ if i == len(self.blocks) - 1:
692
+ continue
693
+ if self.grad_checkpointing:
694
+ x = checkpoint(blk, x, (rel_pos_bias,))
695
+ else:
696
+ x = blk(x, rel_pos_bias=rel_pos_bias)
697
+
698
+ if not return_all_features:
699
+ x = self.norm(x)
700
+ if self.fc_norm is not None:
701
+ return self.fc_norm(x.mean(1))
702
+ else:
703
+ return x[:, 0]
704
+ return x
705
+
706
+ def forward(self, x, return_all_features=False):
707
+ if return_all_features:
708
+ return self.forward_features(x, return_all_features)
709
+ x = self.forward_features(x)
710
+ x = self.head(x)
711
+ return x
712
+
713
+
714
+ def load_state_dict(checkpoint_path: str, map_location: str = "cpu", model_key: str = "model|module|state_dict", is_openai: bool = False, skip_list: list = []):
715
+ if is_openai:
716
+ model = torch.jit.load(checkpoint_path, map_location="cpu").eval()
717
+ state_dict = model.state_dict()
718
+ for key in ["input_resolution", "context_length", "vocab_size"]:
719
+ state_dict.pop(key, None)
720
+ else:
721
+ checkpoint = torch.load(checkpoint_path, map_location=map_location)
722
+ for mk in model_key.split("|"):
723
+ if isinstance(checkpoint, dict) and mk in checkpoint:
724
+ state_dict = checkpoint[mk]
725
+ break
726
+ else:
727
+ state_dict = checkpoint
728
+ if next(iter(state_dict.items()))[0].startswith("module"):
729
+ state_dict = {k[7:]: v for k, v in state_dict.items()}
730
+
731
+ for k in skip_list:
732
+ if k in list(state_dict.keys()):
733
+ logging.info(f"Removing key {k} from pretrained checkpoint")
734
+ del state_dict[k]
735
+
736
+ if os.getenv("RoPE") == "1":
737
+ for k in list(state_dict.keys()):
738
+ if "freqs_cos" in k or "freqs_sin" in k:
739
+ del state_dict[k]
740
+ return state_dict
741
+
742
+
743
+ def load_clip_visual_state_dict(checkpoint_path: str, map_location: str = "cpu", is_openai: bool = False, skip_list: list = []):
744
+ state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list)
745
+ # for k in list(state_dict.keys()):
746
+ # if not k.startswith("visual."):
747
+ # del state_dict[k]
748
+ # for k in list(state_dict.keys()):
749
+ # if k.startswith("visual."):
750
+ # new_k = k[7:]
751
+ # state_dict[new_k] = state_dict[k]
752
+ # del state_dict[k]
753
+ return state_dict
754
+
755
+
756
+ from dataclasses import dataclass
757
+ from typing import Optional, Tuple, Union
758
+
759
+ try:
760
+ from apex.normalization import FusedLayerNorm
761
+ except:
762
+ FusedLayerNorm = LayerNorm
763
+ # print("Please build and install Nvidia apex package with option '--cuda_ext' according to https://github.com/NVIDIA/apex#from-source .")
764
+
765
+
766
+ @dataclass
767
+ class CLIPVisionCfg:
768
+ layers: Union[Tuple[int, int, int, int], int] = 12
769
+ width: int = 768
770
+ head_width: int = 64
771
+ mlp_ratio: float = 4.0
772
+ patch_size: int = 16
773
+ image_size: Union[Tuple[int, int], int] = 224
774
+ ls_init_value: Optional[float] = None # layer scale initial value
775
+ patch_dropout: float = 0.0 # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results
776
+ global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580)
777
+ drop_path_rate: Optional[float] = None # drop path rate
778
+ timm_model_name: str = None # a valid model name overrides layers, width, patch_size
779
+ timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model
780
+ timm_pool: str = "avg" # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '')
781
+ timm_proj: str = "linear" # linear projection for timm model output ('linear', 'mlp', '')
782
+ timm_proj_bias: bool = False # enable bias final projection
783
+ eva_model_name: str = None # a valid eva model name overrides layers, width, patch_size
784
+ qkv_bias: bool = True
785
+ fusedLN: bool = False
786
+ xattn: bool = False
787
+ postnorm: bool = False
788
+ rope: bool = False
789
+ pt_hw_seq_len: int = 16 # 224/14
790
+ intp_freq: bool = False
791
+ naiveswiglu: bool = False
792
+ subln: bool = False
793
+
794
+
795
+ def create_norm_layer_factory(use_fused_ln, eps=1e-6):
796
+ # Otherwise, use the standard LayerNorm
797
+ return lambda num_features: nn.LayerNorm(num_features, eps=eps)
798
+
799
+
800
+ def _build_vision_tower(vision_tower_path: str, embed_dim: int, vision_cfg: CLIPVisionCfg, **kwargs):
801
+ if isinstance(vision_cfg, dict):
802
+ vision_cfg = CLIPVisionCfg(**vision_cfg)
803
+
804
+ if vision_cfg.eva_model_name:
805
+ vision_heads = vision_cfg.width // vision_cfg.head_width
806
+ # Determine the appropriate norm layer factory based on the configuration
807
+ norm_layer_factory = create_norm_layer_factory(vision_cfg.fusedLN, eps=1e-6)
808
+
809
+ visual = EVAVisionTransformer(
810
+ img_size=vision_cfg.image_size,
811
+ patch_size=vision_cfg.patch_size,
812
+ num_classes=embed_dim,
813
+ use_mean_pooling=vision_cfg.global_average_pool, # False
814
+ init_values=vision_cfg.ls_init_value,
815
+ patch_dropout=vision_cfg.patch_dropout,
816
+ embed_dim=vision_cfg.width,
817
+ depth=vision_cfg.layers,
818
+ num_heads=vision_heads,
819
+ mlp_ratio=vision_cfg.mlp_ratio,
820
+ qkv_bias=vision_cfg.qkv_bias,
821
+ drop_path_rate=vision_cfg.drop_path_rate,
822
+ norm_layer=norm_layer_factory,
823
+ xattn=vision_cfg.xattn,
824
+ rope=vision_cfg.rope,
825
+ postnorm=vision_cfg.postnorm,
826
+ pt_hw_seq_len=vision_cfg.pt_hw_seq_len, # 224/14
827
+ intp_freq=vision_cfg.intp_freq,
828
+ naiveswiglu=vision_cfg.naiveswiglu,
829
+ subln=vision_cfg.subln,
830
+ )
831
+
832
+ state_dict = load_clip_visual_state_dict(vision_tower_path)
833
+ incompatible_keys = visual.load_state_dict(state_dict, strict=False)
834
+ rank0_print("EVA-CLIP incompatible_keys:", incompatible_keys)
835
+
836
+ return visual
837
+
838
+
839
+ class EVAEncoderWrapper(nn.Module):
840
+ def __init__(self, vision_tower_pretrained, config):
841
+ super(EVAEncoderWrapper, self).__init__()
842
+ self.config = config
843
+ self.config["vision_tower_path"] = vision_tower_pretrained
844
+ self.model = _build_vision_tower(**self.config)
845
+
846
+ def forward(self, image, **kwargs):
847
+ encode = self.model(image, return_all_features=True)[:, 1:, :] # remove the CLS token
848
+ return encode
849
+
850
+ @property
851
+ def dtype(self):
852
+ return list(self.parameters())[-1].dtype
853
+
854
+ @property
855
+ def device(self):
856
+ return list(self.parameters())[-1].device
LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/factory.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ import pathlib
5
+ import re
6
+ from copy import deepcopy
7
+ from pathlib import Path
8
+ from typing import Optional, Tuple, Union, Dict, Any
9
+ import torch
10
+
11
+ _MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"]
12
+ _MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs
13
+
14
+
15
+ def _natural_key(string_):
16
+ return [int(s) if s.isdigit() else s for s in re.split(r"(\d+)", string_.lower())]
17
+
18
+
19
+ def _rescan_model_configs():
20
+ global _MODEL_CONFIGS
21
+
22
+ config_ext = (".json",)
23
+ config_files = []
24
+ for config_path in _MODEL_CONFIG_PATHS:
25
+ if config_path.is_file() and config_path.suffix in config_ext:
26
+ config_files.append(config_path)
27
+ elif config_path.is_dir():
28
+ for ext in config_ext:
29
+ config_files.extend(config_path.glob(f"*{ext}"))
30
+
31
+ for cf in config_files:
32
+ with open(cf, "r", encoding="utf8") as f:
33
+ model_cfg = json.load(f)
34
+ if all(a in model_cfg for a in ("embed_dim", "vision_cfg", "text_cfg")):
35
+ _MODEL_CONFIGS[cf.stem] = model_cfg
36
+
37
+ _MODEL_CONFIGS = dict(sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0])))
38
+
39
+
40
+ _rescan_model_configs() # initial populate of model config registry
41
+
42
+
43
+ def list_models():
44
+ """enumerate available model architectures based on config files"""
45
+ return list(_MODEL_CONFIGS.keys())
46
+
47
+
48
+ def add_model_config(path):
49
+ """add model config path or file and update registry"""
50
+ if not isinstance(path, Path):
51
+ path = Path(path)
52
+ _MODEL_CONFIG_PATHS.append(path)
53
+ _rescan_model_configs()
54
+
55
+
56
+ def get_model_config(model_name):
57
+ if model_name in _MODEL_CONFIGS:
58
+ return deepcopy(_MODEL_CONFIGS[model_name])
59
+ else:
60
+ return None
LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-18B.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1536,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 48,
6
+ "width": 5120,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-18b-14-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": true,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B-plus.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1280,
3
+ "vision_cfg": {
4
+ "image_size": 448,
5
+ "layers": 32,
6
+ "width": 4096,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-8b-14-plus-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": false,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }
LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "embed_dim": 1280,
3
+ "vision_cfg": {
4
+ "image_size": 224,
5
+ "layers": 32,
6
+ "width": 4096,
7
+ "head_width": 128,
8
+ "mlp_ratio": 5,
9
+ "patch_size": 14,
10
+ "eva_model_name": "eva-clip-8b-14-x",
11
+ "drop_path_rate": 0,
12
+ "qkv_bias": false,
13
+ "xattn": true,
14
+ "postnorm": false,
15
+ "fusedLN": false,
16
+ "use_rms_norm": true
17
+ },
18
+ "text_cfg": {
19
+ "context_length": 77,
20
+ "vocab_size": 49408,
21
+ "width": 1280,
22
+ "heads": 20,
23
+ "layers": 32,
24
+ "xattn": false,
25
+ "fusedLN": false
26
+ }
27
+ }