Penghao Wu commited on
Commit
3672502
1 Parent(s): d148133
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LLaVA/llava/__init__.py +2 -0
  2. LLaVA/llava/constants.py +15 -0
  3. LLaVA/llava/conversation.py +381 -0
  4. LLaVA/llava/mm_utils.py +149 -0
  5. LLaVA/llava/model/__init__.py +3 -0
  6. LLaVA/llava/model/apply_delta.py +48 -0
  7. LLaVA/llava/model/builder.py +154 -0
  8. LLaVA/llava/model/consolidate.py +29 -0
  9. LLaVA/llava/model/language_model/llava_llama.py +140 -0
  10. LLaVA/llava/model/language_model/llava_mpt.py +113 -0
  11. LLaVA/llava/model/language_model/llava_search_llama.py +144 -0
  12. LLaVA/llava/model/language_model/mpt/__pycache__/adapt_tokenizer.cpython-310.pyc +0 -0
  13. LLaVA/llava/model/language_model/mpt/__pycache__/attention.cpython-310.pyc +0 -0
  14. LLaVA/llava/model/language_model/mpt/__pycache__/blocks.cpython-310.pyc +0 -0
  15. LLaVA/llava/model/language_model/mpt/__pycache__/configuration_mpt.cpython-310.pyc +0 -0
  16. LLaVA/llava/model/language_model/mpt/__pycache__/custom_embedding.cpython-310.pyc +0 -0
  17. LLaVA/llava/model/language_model/mpt/__pycache__/flash_attn_triton.cpython-310.pyc +0 -0
  18. LLaVA/llava/model/language_model/mpt/__pycache__/hf_prefixlm_converter.cpython-310.pyc +0 -0
  19. LLaVA/llava/model/language_model/mpt/__pycache__/meta_init_context.cpython-310.pyc +0 -0
  20. LLaVA/llava/model/language_model/mpt/__pycache__/modeling_mpt.cpython-310.pyc +0 -0
  21. LLaVA/llava/model/language_model/mpt/__pycache__/norm.cpython-310.pyc +0 -0
  22. LLaVA/llava/model/language_model/mpt/__pycache__/param_init_fns.cpython-310.pyc +0 -0
  23. LLaVA/llava/model/language_model/mpt/adapt_tokenizer.py +41 -0
  24. LLaVA/llava/model/language_model/mpt/attention.py +300 -0
  25. LLaVA/llava/model/language_model/mpt/blocks.py +41 -0
  26. LLaVA/llava/model/language_model/mpt/configuration_mpt.py +118 -0
  27. LLaVA/llava/model/language_model/mpt/custom_embedding.py +11 -0
  28. LLaVA/llava/model/language_model/mpt/flash_attn_triton.py +484 -0
  29. LLaVA/llava/model/language_model/mpt/hf_prefixlm_converter.py +415 -0
  30. LLaVA/llava/model/language_model/mpt/meta_init_context.py +94 -0
  31. LLaVA/llava/model/language_model/mpt/modeling_mpt.py +331 -0
  32. LLaVA/llava/model/language_model/mpt/norm.py +56 -0
  33. LLaVA/llava/model/language_model/mpt/param_init_fns.py +181 -0
  34. LLaVA/llava/model/llava_arch.py +255 -0
  35. LLaVA/llava/model/llava_search_arch.py +323 -0
  36. LLaVA/llava/model/make_delta.py +52 -0
  37. LLaVA/llava/model/multimodal_encoder/builder.py +11 -0
  38. LLaVA/llava/model/multimodal_encoder/clip_encoder.py +78 -0
  39. LLaVA/llava/model/multimodal_projector/builder.py +70 -0
  40. LLaVA/llava/model/multimodal_projector/perceiver.py +122 -0
  41. LLaVA/llava/model/utils.py +20 -0
  42. LLaVA/llava/train/__init__.py +0 -0
  43. LLaVA/llava/train/__pycache__/__init__.cpython-310.pyc +0 -0
  44. LLaVA/llava/train/__pycache__/llama_flash_attn_monkey_patch.cpython-310.pyc +0 -0
  45. LLaVA/llava/train/__pycache__/llava_trainer.cpython-310.pyc +0 -0
  46. LLaVA/llava/train/__pycache__/train.cpython-310.pyc +0 -0
  47. LLaVA/llava/train/__pycache__/train_search.cpython-310.pyc +0 -0
  48. LLaVA/llava/train/llama_flash_attn_monkey_patch.py +115 -0
  49. LLaVA/llava/train/llava_trainer.py +175 -0
  50. LLaVA/llava/train/train.py +951 -0
LLaVA/llava/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .model import LlavaLlamaForCausalLM
2
+ from .model import LlavaSearchLlamaForCausalLM
LLaVA/llava/constants.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
2
+ WORKER_HEART_BEAT_INTERVAL = 15
3
+
4
+ LOGDIR = "."
5
+
6
+ # Model Constants
7
+ IGNORE_INDEX = -100
8
+ IMAGE_TOKEN_INDEX = -200
9
+ OBJECT_TOKEN_INDEX = -300
10
+ DEFAULT_IMAGE_TOKEN = "<image>"
11
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
12
+ DEFAULT_IM_START_TOKEN = "<im_start>"
13
+ DEFAULT_IM_END_TOKEN = "<im_end>"
14
+
15
+ DEFAULT_OBJECT_TOKEN = "<object>"
LLaVA/llava/conversation.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from enum import auto, Enum
3
+ from typing import List, Tuple
4
+
5
+
6
+ class SeparatorStyle(Enum):
7
+ """Different separator style."""
8
+ SINGLE = auto()
9
+ TWO = auto()
10
+ MPT = auto()
11
+ PLAIN = auto()
12
+ LLAMA_2 = auto()
13
+
14
+
15
+ @dataclasses.dataclass
16
+ class Conversation:
17
+ """A class that keeps all conversation history."""
18
+ system: str
19
+ roles: List[str]
20
+ messages: List[List[str]]
21
+ offset: int
22
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
23
+ sep: str = "###"
24
+ sep2: str = None
25
+ version: str = "Unknown"
26
+
27
+ skip_next: bool = False
28
+
29
+ def get_prompt(self):
30
+ messages = self.messages
31
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
32
+ messages = self.messages.copy()
33
+ init_role, init_msg = messages[0].copy()
34
+ init_msg = init_msg[0].replace("<image>", "").strip()
35
+ if 'mmtag' in self.version:
36
+ messages[0] = (init_role, init_msg)
37
+ messages.insert(0, (self.roles[0], "<Image><image></Image>"))
38
+ messages.insert(1, (self.roles[1], "Received."))
39
+ else:
40
+ messages[0] = (init_role, "<image>\n" + init_msg)
41
+
42
+ if self.sep_style == SeparatorStyle.SINGLE:
43
+ ret = self.system + self.sep
44
+ for role, message in messages:
45
+ if message:
46
+ if type(message) is tuple:
47
+ message, _, _ = message
48
+ ret += role + ": " + message + self.sep
49
+ else:
50
+ ret += role + ":"
51
+ elif self.sep_style == SeparatorStyle.TWO:
52
+ seps = [self.sep, self.sep2]
53
+ ret = self.system + seps[0]
54
+ for i, (role, message) in enumerate(messages):
55
+ if message:
56
+ if type(message) is tuple:
57
+ message, _, _ = message
58
+ ret += role + ": " + message + seps[i % 2]
59
+ else:
60
+ ret += role + ":"
61
+ elif self.sep_style == SeparatorStyle.MPT:
62
+ ret = self.system + self.sep
63
+ for role, message in messages:
64
+ if message:
65
+ if type(message) is tuple:
66
+ message, _, _ = message
67
+ ret += role + message + self.sep
68
+ else:
69
+ ret += role
70
+ elif self.sep_style == SeparatorStyle.LLAMA_2:
71
+ wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
72
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
73
+ ret = ""
74
+
75
+ for i, (role, message) in enumerate(messages):
76
+ if i == 0:
77
+ assert message, "first message should not be none"
78
+ assert role == self.roles[0], "first message should come from user"
79
+ if message:
80
+ if type(message) is tuple:
81
+ message, _, _ = message
82
+ if i == 0: message = wrap_sys(self.system) + message
83
+ if i % 2 == 0:
84
+ message = wrap_inst(message)
85
+ ret += self.sep + message
86
+ else:
87
+ ret += " " + message + " " + self.sep2
88
+ else:
89
+ ret += ""
90
+ ret = ret.lstrip(self.sep)
91
+ elif self.sep_style == SeparatorStyle.PLAIN:
92
+ seps = [self.sep, self.sep2]
93
+ ret = self.system
94
+ for i, (role, message) in enumerate(messages):
95
+ if message:
96
+ if type(message) is tuple:
97
+ message, _, _ = message
98
+ ret += message + seps[i % 2]
99
+ else:
100
+ ret += ""
101
+ else:
102
+ raise ValueError(f"Invalid style: {self.sep_style}")
103
+
104
+ return ret
105
+
106
+ def append_message(self, role, message):
107
+ self.messages.append([role, message])
108
+
109
+ def get_images(self, return_pil=False):
110
+ images = []
111
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
112
+ if i % 2 == 0:
113
+ if type(msg) is tuple:
114
+ import base64
115
+ from io import BytesIO
116
+ from PIL import Image
117
+ msg, image, image_process_mode = msg
118
+ if image_process_mode == "Pad":
119
+ def expand2square(pil_img, background_color=(122, 116, 104)):
120
+ width, height = pil_img.size
121
+ if width == height:
122
+ return pil_img
123
+ elif width > height:
124
+ result = Image.new(pil_img.mode, (width, width), background_color)
125
+ result.paste(pil_img, (0, (width - height) // 2))
126
+ return result
127
+ else:
128
+ result = Image.new(pil_img.mode, (height, height), background_color)
129
+ result.paste(pil_img, ((height - width) // 2, 0))
130
+ return result
131
+ image = expand2square(image)
132
+ elif image_process_mode in ["Default", "Crop"]:
133
+ pass
134
+ elif image_process_mode == "Resize":
135
+ image = image.resize((336, 336))
136
+ else:
137
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
138
+ max_hw, min_hw = max(image.size), min(image.size)
139
+ aspect_ratio = max_hw / min_hw
140
+ max_len, min_len = 800, 400
141
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
142
+ longest_edge = int(shortest_edge * aspect_ratio)
143
+ W, H = image.size
144
+ if longest_edge != max(image.size):
145
+ if H > W:
146
+ H, W = longest_edge, shortest_edge
147
+ else:
148
+ H, W = shortest_edge, longest_edge
149
+ image = image.resize((W, H))
150
+ if return_pil:
151
+ images.append(image)
152
+ else:
153
+ buffered = BytesIO()
154
+ image.save(buffered, format="PNG")
155
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
156
+ images.append(img_b64_str)
157
+ return images
158
+
159
+ def to_gradio_chatbot(self):
160
+ ret = []
161
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
162
+ if i % 2 == 0:
163
+ if type(msg) is tuple:
164
+ import base64
165
+ from io import BytesIO
166
+ msg, image, image_process_mode = msg
167
+ max_hw, min_hw = max(image.size), min(image.size)
168
+ aspect_ratio = max_hw / min_hw
169
+ max_len, min_len = 800, 400
170
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
171
+ longest_edge = int(shortest_edge * aspect_ratio)
172
+ W, H = image.size
173
+ if H > W:
174
+ H, W = longest_edge, shortest_edge
175
+ else:
176
+ H, W = shortest_edge, longest_edge
177
+ image = image.resize((W, H))
178
+ buffered = BytesIO()
179
+ image.save(buffered, format="JPEG")
180
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
181
+ img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
182
+ msg = img_str + msg.replace('<image>', '').strip()
183
+ ret.append([msg, None])
184
+ else:
185
+ ret.append([msg, None])
186
+ else:
187
+ ret[-1][-1] = msg
188
+ return ret
189
+
190
+ def copy(self):
191
+ return Conversation(
192
+ system=self.system,
193
+ roles=self.roles,
194
+ messages=[[x, y] for x, y in self.messages],
195
+ offset=self.offset,
196
+ sep_style=self.sep_style,
197
+ sep=self.sep,
198
+ sep2=self.sep2,
199
+ version=self.version)
200
+
201
+ def dict(self):
202
+ if len(self.get_images()) > 0:
203
+ return {
204
+ "system": self.system,
205
+ "roles": self.roles,
206
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
207
+ "offset": self.offset,
208
+ "sep": self.sep,
209
+ "sep2": self.sep2,
210
+ }
211
+ return {
212
+ "system": self.system,
213
+ "roles": self.roles,
214
+ "messages": self.messages,
215
+ "offset": self.offset,
216
+ "sep": self.sep,
217
+ "sep2": self.sep2,
218
+ }
219
+
220
+
221
+ conv_vicuna_v0 = Conversation(
222
+ system="A chat between a curious human and an artificial intelligence assistant. "
223
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
224
+ roles=("Human", "Assistant"),
225
+ messages=(
226
+ ("Human", "What are the key differences between renewable and non-renewable energy sources?"),
227
+ ("Assistant",
228
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
229
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
230
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
231
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
232
+ "renewable and non-renewable energy sources:\n"
233
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
234
+ "energy sources are finite and will eventually run out.\n"
235
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
236
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
237
+ "and other negative effects.\n"
238
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
239
+ "have lower operational costs than non-renewable sources.\n"
240
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
241
+ "locations than non-renewable sources.\n"
242
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
243
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
244
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
245
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
246
+ ),
247
+ offset=2,
248
+ sep_style=SeparatorStyle.SINGLE,
249
+ sep="###",
250
+ )
251
+
252
+ conv_vicuna_v1 = Conversation(
253
+ system="A chat between a curious user and an artificial intelligence assistant. "
254
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
255
+ roles=("USER", "ASSISTANT"),
256
+ version="v1",
257
+ messages=(),
258
+ offset=0,
259
+ sep_style=SeparatorStyle.TWO,
260
+ sep=" ",
261
+ sep2="</s>",
262
+ )
263
+
264
+ conv_llama_2 = Conversation(
265
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
266
+
267
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
268
+ roles=("USER", "ASSISTANT"),
269
+ version="llama_v2",
270
+ messages=(),
271
+ offset=0,
272
+ sep_style=SeparatorStyle.LLAMA_2,
273
+ sep="<s>",
274
+ sep2="</s>",
275
+ )
276
+
277
+ conv_llava_llama_2 = Conversation(
278
+ system="You are a helpful language and vision assistant. "
279
+ "You are able to understand the visual content that the user provides, "
280
+ "and assist the user with a variety of tasks using natural language.",
281
+ roles=("USER", "ASSISTANT"),
282
+ version="llama_v2",
283
+ messages=(),
284
+ offset=0,
285
+ sep_style=SeparatorStyle.LLAMA_2,
286
+ sep="<s>",
287
+ sep2="</s>",
288
+ )
289
+
290
+ conv_mpt = Conversation(
291
+ system="""<|im_start|>system
292
+ A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
293
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
294
+ version="mpt",
295
+ messages=(),
296
+ offset=0,
297
+ sep_style=SeparatorStyle.MPT,
298
+ sep="<|im_end|>",
299
+ )
300
+
301
+ conv_llava_plain = Conversation(
302
+ system="",
303
+ roles=("", ""),
304
+ messages=(
305
+ ),
306
+ offset=0,
307
+ sep_style=SeparatorStyle.PLAIN,
308
+ sep="\n",
309
+ )
310
+
311
+ conv_llava_v0 = Conversation(
312
+ system="A chat between a curious human and an artificial intelligence assistant. "
313
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
314
+ roles=("Human", "Assistant"),
315
+ messages=(
316
+ ),
317
+ offset=0,
318
+ sep_style=SeparatorStyle.SINGLE,
319
+ sep="###",
320
+ )
321
+
322
+ conv_llava_v0_mmtag = Conversation(
323
+ system="A chat between a curious user and an artificial intelligence assistant. "
324
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
325
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
326
+ roles=("Human", "Assistant"),
327
+ messages=(
328
+ ),
329
+ offset=0,
330
+ sep_style=SeparatorStyle.SINGLE,
331
+ sep="###",
332
+ version="v0_mmtag",
333
+ )
334
+
335
+ conv_llava_v1 = Conversation(
336
+ system="A chat between a curious human and an artificial intelligence assistant. "
337
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
338
+ roles=("USER", "ASSISTANT"),
339
+ version="v1",
340
+ messages=(),
341
+ offset=0,
342
+ sep_style=SeparatorStyle.TWO,
343
+ sep=" ",
344
+ sep2="</s>",
345
+ )
346
+
347
+ conv_llava_v1_mmtag = Conversation(
348
+ system="A chat between a curious user and an artificial intelligence assistant. "
349
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
350
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
351
+ roles=("USER", "ASSISTANT"),
352
+ messages=(),
353
+ offset=0,
354
+ sep_style=SeparatorStyle.TWO,
355
+ sep=" ",
356
+ sep2="</s>",
357
+ version="v1_mmtag",
358
+ )
359
+
360
+ default_conversation = conv_vicuna_v0
361
+ conv_templates = {
362
+ "default": conv_vicuna_v0,
363
+ "v0": conv_vicuna_v0,
364
+ "v1": conv_vicuna_v1,
365
+ "vicuna_v1": conv_vicuna_v1,
366
+ "llama_2": conv_llama_2,
367
+
368
+ "plain": conv_llava_plain,
369
+ "v0_plain": conv_llava_plain,
370
+ "llava_v0": conv_llava_v0,
371
+ "v0_mmtag": conv_llava_v0_mmtag,
372
+ "llava_v1": conv_llava_v1,
373
+ "v1_mmtag": conv_llava_v1_mmtag,
374
+ "llava_llama_2": conv_llava_llama_2,
375
+
376
+ "mpt": conv_mpt,
377
+ }
378
+
379
+
380
+ if __name__ == "__main__":
381
+ print(default_conversation.get_prompt())
LLaVA/llava/mm_utils.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from io import BytesIO
3
+ import base64
4
+
5
+ import torch
6
+ from transformers import StoppingCriteria
7
+ from LLaVA.llava.constants import IMAGE_TOKEN_INDEX, OBJECT_TOKEN_INDEX
8
+
9
+
10
+ def load_image_from_base64(image):
11
+ return Image.open(BytesIO(base64.b64decode(image)))
12
+
13
+
14
+ def expand2square(pil_img, background_color):
15
+ width, height = pil_img.size
16
+ if width == height:
17
+ return pil_img
18
+ elif width > height:
19
+ result = Image.new(pil_img.mode, (width, width), background_color)
20
+ result.paste(pil_img, (0, (width - height) // 2))
21
+ return result
22
+ else:
23
+ result = Image.new(pil_img.mode, (height, height), background_color)
24
+ result.paste(pil_img, ((height - width) // 2, 0))
25
+ return result
26
+
27
+
28
+ def process_images(images, image_processor, model_cfg):
29
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
30
+ new_images = []
31
+ if image_aspect_ratio == 'pad':
32
+ for image in images:
33
+ image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean))
34
+ image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
35
+ new_images.append(image)
36
+ else:
37
+ return image_processor(images, return_tensors='pt')['pixel_values']
38
+ if all(x.shape == new_images[0].shape for x in new_images):
39
+ new_images = torch.stack(new_images, dim=0)
40
+ return new_images
41
+
42
+
43
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
44
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split('<image>')]
45
+
46
+ def insert_separator(X, sep):
47
+ return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]
48
+
49
+ input_ids = []
50
+ offset = 0
51
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
52
+ offset = 1
53
+ input_ids.append(prompt_chunks[0][0])
54
+
55
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
56
+ input_ids.extend(x[offset:])
57
+
58
+ if return_tensors is not None:
59
+ if return_tensors == 'pt':
60
+ return torch.tensor(input_ids, dtype=torch.long)
61
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
62
+ return input_ids
63
+
64
+
65
+ def tokenizer_image_object_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, object_token_index=OBJECT_TOKEN_INDEX, return_tensors=None):
66
+ prompt_chunks = []
67
+ for prompt_chunk in prompt.split('<image>'):
68
+ prompt_chunks.extend(prompt_chunk.split('<object>'))
69
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt_chunks]
70
+ def insert_separator(X, seps):
71
+ return [ele for sublist in zip(X, seps) for ele in sublist][:-1]
72
+
73
+ input_ids = []
74
+ offset = 0
75
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
76
+ offset = 1
77
+ input_ids.append(prompt_chunks[0][0])
78
+
79
+ sep = [[image_token_index] * (offset + 1)] + [[object_token_index] * (offset + 1)]*(len(prompt_chunks)-1)
80
+ for x in insert_separator(prompt_chunks, sep):
81
+ input_ids.extend(x[offset:])
82
+
83
+ if return_tensors is not None:
84
+ if return_tensors == 'pt':
85
+ return torch.tensor(input_ids, dtype=torch.long)
86
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
87
+ return input_ids
88
+
89
+ def tokenizer_object_token(prompt, tokenizer, object_token_index=OBJECT_TOKEN_INDEX, return_tensors=None):
90
+ prompt_chunks = prompt.split('<object>')
91
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt_chunks]
92
+ def insert_separator(X, seps):
93
+ return [ele for sublist in zip(X, seps) for ele in sublist][:-1]
94
+
95
+ input_ids = []
96
+ offset = 0
97
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
98
+ offset = 1
99
+ # input_ids.append(prompt_chunks[0][0])
100
+
101
+ sep = [[object_token_index] * (offset + 1)]*len(prompt_chunks)
102
+ for x in insert_separator(prompt_chunks, sep):
103
+ input_ids.extend(x[offset:])
104
+
105
+ if return_tensors is not None:
106
+ if return_tensors == 'pt':
107
+ return torch.tensor(input_ids, dtype=torch.long)
108
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
109
+ return input_ids
110
+
111
+
112
+ def get_model_name_from_path(model_path):
113
+ model_path = model_path.strip("/")
114
+ model_paths = model_path.split("/")
115
+ if model_paths[-1].startswith('checkpoint-'):
116
+ return model_paths[-2] + "_" + model_paths[-1]
117
+ else:
118
+ return model_paths[-1]
119
+
120
+
121
+
122
+
123
+ class KeywordsStoppingCriteria(StoppingCriteria):
124
+ def __init__(self, keywords, tokenizer, input_ids):
125
+ self.keywords = keywords
126
+ self.keyword_ids = []
127
+ self.max_keyword_len = 0
128
+ for keyword in keywords:
129
+ cur_keyword_ids = tokenizer(keyword).input_ids
130
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
131
+ cur_keyword_ids = cur_keyword_ids[1:]
132
+ if len(cur_keyword_ids) > self.max_keyword_len:
133
+ self.max_keyword_len = len(cur_keyword_ids)
134
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
135
+ self.tokenizer = tokenizer
136
+ self.start_len = input_ids.shape[1]
137
+
138
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
139
+ assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
140
+ offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len)
141
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
142
+ for keyword_id in self.keyword_ids:
143
+ if (output_ids[0, -keyword_id.shape[0]:] == keyword_id).all():
144
+ return True
145
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
146
+ for keyword in self.keywords:
147
+ if keyword in outputs:
148
+ return True
149
+ return False
LLaVA/llava/model/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .language_model.llava_llama import LlavaLlamaForCausalLM, LlavaConfig
2
+ from .language_model.llava_search_llama import LlavaSearchLlamaForCausalLM, LlavaSearchConfig
3
+ from .language_model.llava_mpt import LlavaMPTForCausalLM, LlavaMPTConfig
LLaVA/llava/model/apply_delta.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from tqdm import tqdm
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from LLaVA.llava import LlavaLlamaForCausalLM
11
+
12
+
13
+ def apply_delta(base_model_path, target_model_path, delta_path):
14
+ print("Loading base model")
15
+ base = AutoModelForCausalLM.from_pretrained(
16
+ base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+
18
+ print("Loading delta")
19
+ delta = LlavaLlamaForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
20
+ delta_tokenizer = AutoTokenizer.from_pretrained(delta_path)
21
+
22
+ print("Applying delta")
23
+ for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"):
24
+ if name not in base.state_dict():
25
+ assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
26
+ continue
27
+ if param.data.shape == base.state_dict()[name].shape:
28
+ param.data += base.state_dict()[name]
29
+ else:
30
+ assert name in ['model.embed_tokens.weight', 'lm_head.weight'], \
31
+ f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
32
+ bparam = base.state_dict()[name]
33
+ param.data[:bparam.shape[0], :bparam.shape[1]] += bparam
34
+
35
+ print("Saving target model")
36
+ delta.save_pretrained(target_model_path)
37
+ delta_tokenizer.save_pretrained(target_model_path)
38
+
39
+
40
+ if __name__ == "__main__":
41
+ parser = argparse.ArgumentParser()
42
+ parser.add_argument("--base-model-path", type=str, required=True)
43
+ parser.add_argument("--target-model-path", type=str, required=True)
44
+ parser.add_argument("--delta-path", type=str, required=True)
45
+
46
+ args = parser.parse_args()
47
+
48
+ apply_delta(args.base_model_path, args.target_model_path, args.delta_path)
LLaVA/llava/model/builder.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
17
+ import warnings
18
+ import shutil
19
+
20
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
21
+ import torch
22
+ from LLaVA.llava.model import LlavaSearchLlamaForCausalLM, LlavaLlamaForCausalLM, LlavaMPTForCausalLM
23
+ from LLaVA.llava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
24
+
25
+
26
+ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda"):
27
+ kwargs = {"device_map": device_map}
28
+ load_8bit = True
29
+ if load_8bit:
30
+ kwargs['load_in_8bit'] = True
31
+ elif load_4bit:
32
+ kwargs['load_in_4bit'] = True
33
+ kwargs['quantization_config'] = BitsAndBytesConfig(
34
+ load_in_4bit=True,
35
+ bnb_4bit_compute_dtype=torch.float16,
36
+ bnb_4bit_use_double_quant=True,
37
+ bnb_4bit_quant_type='nf4'
38
+ )
39
+ else:
40
+ kwargs['torch_dtype'] = torch.float16
41
+
42
+
43
+ kwargs["quantization_config"] = BitsAndBytesConfig(
44
+ llm_int8_skip_modules=['mm_projector_object'],
45
+ load_in_8bit=True,
46
+ )
47
+
48
+ if 'llava' in model_name.lower():
49
+ # Load LLaVA model
50
+ if 'lora' in model_name.lower() and model_base is None:
51
+ warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.')
52
+ if 'lora' in model_name.lower() and model_base is not None:
53
+ lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
54
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
55
+ print('Loading LLaVA from base model...')
56
+ model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
57
+ token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
58
+ if model.lm_head.weight.shape[0] != token_num:
59
+ model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
60
+ model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
61
+
62
+ print('Loading additional LLaVA weights...')
63
+ if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
64
+ non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
65
+ else:
66
+ # this is probably from HF Hub
67
+ from huggingface_hub import hf_hub_download
68
+ def load_from_hf(repo_id, filename, subfolder=None):
69
+ cache_file = hf_hub_download(
70
+ repo_id=repo_id,
71
+ filename=filename,
72
+ subfolder=subfolder)
73
+ return torch.load(cache_file, map_location='cpu')
74
+ non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
75
+ non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
76
+ if any(k.startswith('model.model.') for k in non_lora_trainables):
77
+ non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
78
+ model.load_state_dict(non_lora_trainables, strict=False)
79
+
80
+ from peft import PeftModel
81
+ print('Loading LoRA weights...')
82
+ model = PeftModel.from_pretrained(model, model_path)
83
+ print('Merging LoRA weights...')
84
+ model = model.merge_and_unload()
85
+ print('Model is loaded...')
86
+ elif model_base is not None:
87
+ # this may be mm projector only
88
+ print('Loading LLaVA from base model...')
89
+ if 'mpt' in model_name.lower():
90
+ if not os.path.isfile(os.path.join(model_path, 'configuration_mpt.py')):
91
+ shutil.copyfile(os.path.join(model_base, 'configuration_mpt.py'), os.path.join(model_path, 'configuration_mpt.py'))
92
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
93
+ cfg_pretrained = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
94
+ model = LlavaMPTForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
95
+ else:
96
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
97
+ cfg_pretrained = AutoConfig.from_pretrained(model_path)
98
+ model = LlavaSearchLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
99
+
100
+ mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
101
+ mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
102
+ model.load_state_dict(mm_projector_weights, strict=False)
103
+ else:
104
+ if 'mpt' in model_name.lower():
105
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
106
+ model = LlavaMPTForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
107
+ else:
108
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
109
+ model = LlavaSearchLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
110
+ else:
111
+ # Load language model
112
+ if model_base is not None:
113
+ # PEFT model
114
+ from peft import PeftModel
115
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
116
+ model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto")
117
+ print(f"Loading LoRA weights from {model_path}")
118
+ model = PeftModel.from_pretrained(model, model_path)
119
+ print(f"Merging weights")
120
+ model = model.merge_and_unload()
121
+ print('Convert to FP16...')
122
+ model.to(torch.float16)
123
+ else:
124
+ use_fast = False
125
+ if 'mpt' in model_name.lower():
126
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
127
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs)
128
+ else:
129
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
130
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
131
+
132
+ image_processor = None
133
+
134
+ if 'llava' in model_name.lower():
135
+ mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
136
+ mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
137
+ if mm_use_im_patch_token:
138
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
139
+ if mm_use_im_start_end:
140
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
141
+ model.resize_token_embeddings(len(tokenizer))
142
+
143
+ vision_tower = model.get_vision_tower()
144
+ if not vision_tower.is_loaded:
145
+ vision_tower.load_model()
146
+ vision_tower.to(device=device, dtype=torch.float16)
147
+ image_processor = vision_tower.image_processor
148
+
149
+ if hasattr(model.config, "max_sequence_length"):
150
+ context_len = model.config.max_sequence_length
151
+ else:
152
+ context_len = 2048
153
+
154
+ return tokenizer, model, image_processor, context_len
LLaVA/llava/model/consolidate.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM
9
+ from LLaVA.llava.model import *
10
+ from LLaVA.llava.model.utils import auto_upgrade
11
+
12
+
13
+ def consolidate_ckpt(src_path, dst_path):
14
+ print("Loading model")
15
+ auto_upgrade(src_path)
16
+ src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+ src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False)
18
+ src_model.save_pretrained(dst_path)
19
+ src_tokenizer.save_pretrained(dst_path)
20
+
21
+
22
+ if __name__ == "__main__":
23
+ parser = argparse.ArgumentParser()
24
+ parser.add_argument("--src", type=str, required=True)
25
+ parser.add_argument("--dst", type=str, required=True)
26
+
27
+ args = parser.parse_args()
28
+
29
+ consolidate_ckpt(args.src, args.dst)
LLaVA/llava/model/language_model/llava_llama.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, \
23
+ LlamaConfig, LlamaModel, LlamaForCausalLM
24
+
25
+ from transformers.modeling_outputs import CausalLMOutputWithPast
26
+
27
+ from LLaVA.llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
28
+
29
+
30
+ class LlavaConfig(LlamaConfig):
31
+ model_type = "llava"
32
+
33
+
34
+ class LlavaLlamaModel(LlavaMetaModel, LlamaModel):
35
+ config_class = LlavaConfig
36
+
37
+ def __init__(self, config: LlamaConfig):
38
+ super(LlavaLlamaModel, self).__init__(config)
39
+
40
+
41
+ class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
42
+ config_class = LlavaConfig
43
+
44
+ def __init__(self, config):
45
+ super(LlamaForCausalLM, self).__init__(config)
46
+ self.model = LlavaLlamaModel(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
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
61
+ inputs_embeds: Optional[torch.FloatTensor] = None,
62
+ labels: Optional[torch.LongTensor] = None,
63
+ use_cache: Optional[bool] = None,
64
+ output_attentions: Optional[bool] = None,
65
+ output_hidden_states: Optional[bool] = None,
66
+ images: Optional[torch.FloatTensor] = None,
67
+ return_dict: Optional[bool] = None,
68
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
69
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
70
+ output_hidden_states = (
71
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
72
+ )
73
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
74
+
75
+ 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)
76
+
77
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
78
+ outputs = self.model(
79
+ input_ids=input_ids,
80
+ attention_mask=attention_mask,
81
+ past_key_values=past_key_values,
82
+ inputs_embeds=inputs_embeds,
83
+ use_cache=use_cache,
84
+ output_attentions=output_attentions,
85
+ output_hidden_states=output_hidden_states,
86
+ return_dict=return_dict
87
+ )
88
+
89
+ hidden_states = outputs[0]
90
+ logits = self.lm_head(hidden_states)
91
+
92
+ loss = None
93
+ if labels is not None:
94
+ # Shift so that tokens < n predict n
95
+ shift_logits = logits[..., :-1, :].contiguous()
96
+ shift_labels = labels[..., 1:].contiguous()
97
+ # Flatten the tokens
98
+ loss_fct = CrossEntropyLoss()
99
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
100
+ shift_labels = shift_labels.view(-1)
101
+ # Enable model/pipeline parallelism
102
+ shift_labels = shift_labels.to(shift_logits.device)
103
+ loss = loss_fct(shift_logits, shift_labels)
104
+
105
+ if not return_dict:
106
+ output = (logits,) + outputs[1:]
107
+ return (loss,) + output if loss is not None else output
108
+
109
+ return CausalLMOutputWithPast(
110
+ loss=loss,
111
+ logits=logits,
112
+ past_key_values=outputs.past_key_values,
113
+ hidden_states=outputs.hidden_states,
114
+ attentions=outputs.attentions,
115
+ )
116
+
117
+ def prepare_inputs_for_generation(
118
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
119
+ ):
120
+ if past_key_values:
121
+ input_ids = input_ids[:, -1:]
122
+
123
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
124
+ if inputs_embeds is not None and past_key_values is None:
125
+ model_inputs = {"inputs_embeds": inputs_embeds}
126
+ else:
127
+ model_inputs = {"input_ids": input_ids}
128
+
129
+ model_inputs.update(
130
+ {
131
+ "past_key_values": past_key_values,
132
+ "use_cache": kwargs.get("use_cache"),
133
+ "attention_mask": attention_mask,
134
+ "images": kwargs.get("images", None),
135
+ }
136
+ )
137
+ return model_inputs
138
+
139
+ AutoConfig.register("llava", LlavaConfig)
140
+ AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM)
LLaVA/llava/model/language_model/llava_mpt.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
17
+ import warnings
18
+
19
+ import torch
20
+ import torch.nn.functional as F
21
+ import math
22
+
23
+ from transformers import AutoConfig, AutoModelForCausalLM
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+
26
+ from LLaVA.llava.model.language_model.mpt.modeling_mpt import MPTConfig, MPTForCausalLM, MPTModel
27
+ from LLaVA.llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
28
+
29
+
30
+ class LlavaMPTConfig(MPTConfig):
31
+ model_type = "llava_mpt"
32
+
33
+
34
+ class LlavaMPTModel(LlavaMetaModel, MPTModel):
35
+ config_class = LlavaMPTConfig
36
+
37
+ def __init__(self, config: MPTConfig):
38
+ config.hidden_size = config.d_model
39
+ super(LlavaMPTModel, self).__init__(config)
40
+
41
+ def embed_tokens(self, x):
42
+ return self.wte(x)
43
+
44
+
45
+ class LlavaMPTForCausalLM(MPTForCausalLM, LlavaMetaForCausalLM):
46
+ config_class = LlavaMPTConfig
47
+ supports_gradient_checkpointing = True
48
+
49
+ def __init__(self, config):
50
+ super(MPTForCausalLM, self).__init__(config)
51
+
52
+ if not config.tie_word_embeddings:
53
+ raise ValueError('MPTForCausalLM only supports tied word embeddings')
54
+ self.transformer = LlavaMPTModel(config)
55
+ self.logit_scale = None
56
+ if config.logit_scale is not None:
57
+ logit_scale = config.logit_scale
58
+ if isinstance(logit_scale, str):
59
+ if logit_scale == 'inv_sqrt_d_model':
60
+ logit_scale = 1 / math.sqrt(config.d_model)
61
+ else:
62
+ raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
63
+ self.logit_scale = logit_scale
64
+
65
+ def get_model(self):
66
+ return self.transformer
67
+
68
+ def _set_gradient_checkpointing(self, module, value=False):
69
+ if isinstance(module, LlavaMPTModel):
70
+ module.gradient_checkpointing = value
71
+
72
+ def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, images=None):
73
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
74
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
75
+
76
+ 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)
77
+ outputs = self.transformer(input_ids=input_ids, inputs_embeds=inputs_embeds, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
78
+ # FIXME: this is a hack to fix the multiple gpu inference issue in https://github.com/haotian-liu/LLaVA/issues/338
79
+ logits = F.linear(outputs.last_hidden_state.to(self.transformer.wte.weight.device), self.transformer.wte.weight)
80
+ if self.logit_scale is not None:
81
+ if self.logit_scale == 0:
82
+ warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
83
+ logits *= self.logit_scale
84
+ loss = None
85
+ if labels is not None:
86
+ labels = torch.roll(labels, shifts=-1)
87
+ labels[:, -1] = -100
88
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))
89
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states)
90
+
91
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
92
+ if inputs_embeds is not None:
93
+ raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
94
+ attention_mask = kwargs['attention_mask'].bool()
95
+ if attention_mask[:, -1].sum() != attention_mask.shape[0]:
96
+ raise NotImplementedError('MPT does not support generation with right padding.')
97
+ if self.transformer.attn_uses_sequence_id and self.training:
98
+ sequence_id = torch.zeros_like(input_ids[:1])
99
+ else:
100
+ sequence_id = None
101
+ if past_key_values is not None:
102
+ input_ids = input_ids[:, -1].unsqueeze(-1)
103
+ if self.transformer.prefix_lm:
104
+ prefix_mask = torch.ones_like(attention_mask)
105
+ if kwargs.get('use_cache') == False:
106
+ raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
107
+ else:
108
+ prefix_mask = None
109
+ return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True), "images": kwargs.get("images", None)}
110
+
111
+
112
+ AutoConfig.register("llava_mpt", LlavaMPTConfig)
113
+ AutoModelForCausalLM.register(LlavaMPTConfig, LlavaMPTForCausalLM)
LLaVA/llava/model/language_model/llava_search_llama.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, \
23
+ LlamaConfig, LlamaModel, LlamaForCausalLM
24
+
25
+ from transformers.modeling_outputs import CausalLMOutputWithPast
26
+
27
+ from LLaVA.llava.model.llava_search_arch import LlavaSearchMetaModel, LlavaSearchMetaForCausalLM
28
+
29
+
30
+ class LlavaSearchConfig(LlamaConfig):
31
+ model_type = "llava_search"
32
+
33
+
34
+ class LlavaSearchLlamaModel(LlavaSearchMetaModel, LlamaModel):
35
+ config_class = LlavaSearchConfig
36
+
37
+ def __init__(self, config: LlamaConfig):
38
+ super(LlavaSearchLlamaModel, self).__init__(config)
39
+
40
+
41
+ class LlavaSearchLlamaForCausalLM(LlamaForCausalLM, LlavaSearchMetaForCausalLM):
42
+ config_class = LlavaSearchConfig
43
+
44
+ def __init__(self, config):
45
+ super(LlamaForCausalLM, self).__init__(config)
46
+ self.model = LlavaSearchLlamaModel(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
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
61
+ inputs_embeds: Optional[torch.FloatTensor] = None,
62
+ labels: Optional[torch.LongTensor] = None,
63
+ use_cache: Optional[bool] = None,
64
+ output_attentions: Optional[bool] = None,
65
+ output_hidden_states: Optional[bool] = None,
66
+ images: Optional[torch.FloatTensor] = None,
67
+ object_features: Optional[torch.FloatTensor] = None,
68
+ images_long: Optional[torch.BoolTensor] = None,
69
+ objects_long: Optional[torch.BoolTensor] = None,
70
+ return_dict: Optional[bool] = None,
71
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
72
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
73
+ output_hidden_states = (
74
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
75
+ )
76
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
77
+
78
+ 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, object_features, images_long, objects_long)
79
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
80
+ outputs = self.model(
81
+ input_ids=input_ids,
82
+ attention_mask=attention_mask,
83
+ past_key_values=past_key_values,
84
+ inputs_embeds=inputs_embeds,
85
+ use_cache=use_cache,
86
+ output_attentions=output_attentions,
87
+ output_hidden_states=output_hidden_states,
88
+ return_dict=return_dict
89
+ )
90
+
91
+ hidden_states = outputs[0]
92
+ logits = self.lm_head(hidden_states)
93
+
94
+ loss = None
95
+ if labels is not None:
96
+ # Shift so that tokens < n predict n
97
+ shift_logits = logits[..., :-1, :].contiguous()
98
+ shift_labels = labels[..., 1:].contiguous()
99
+ # Flatten the tokens
100
+ loss_fct = CrossEntropyLoss()
101
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
102
+ shift_labels = shift_labels.view(-1)
103
+ # Enable model/pipeline parallelism
104
+ shift_labels = shift_labels.to(shift_logits.device)
105
+ loss = loss_fct(shift_logits, shift_labels)
106
+ if not return_dict:
107
+ output = (logits,) + outputs[1:]
108
+ return (loss,) + output if loss is not None else output
109
+
110
+ return CausalLMOutputWithPast(
111
+ loss=loss,
112
+ logits=logits,
113
+ past_key_values=outputs.past_key_values,
114
+ hidden_states=outputs.hidden_states,
115
+ attentions=outputs.attentions,
116
+ )
117
+
118
+ def prepare_inputs_for_generation(
119
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
120
+ ):
121
+ if past_key_values:
122
+ input_ids = input_ids[:, -1:]
123
+
124
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
125
+ if inputs_embeds is not None and past_key_values is None:
126
+ model_inputs = {"inputs_embeds": inputs_embeds}
127
+ else:
128
+ model_inputs = {"input_ids": input_ids}
129
+
130
+ model_inputs.update(
131
+ {
132
+ "past_key_values": past_key_values,
133
+ "use_cache": kwargs.get("use_cache"),
134
+ "attention_mask": attention_mask,
135
+ "images": kwargs.get("images", None),
136
+ "object_features": kwargs.get("object_features", None),
137
+ "images_long": kwargs.get("images_long", None),
138
+ "objects_long": kwargs.get("objects_long", None),
139
+ }
140
+ )
141
+ return model_inputs
142
+
143
+ AutoConfig.register("llava_search", LlavaSearchConfig)
144
+ AutoModelForCausalLM.register(LlavaSearchConfig, LlavaSearchLlamaForCausalLM)
LLaVA/llava/model/language_model/mpt/__pycache__/adapt_tokenizer.cpython-310.pyc ADDED
Binary file (2.26 kB). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/attention.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/blocks.cpython-310.pyc ADDED
Binary file (2.76 kB). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/configuration_mpt.cpython-310.pyc ADDED
Binary file (8.67 kB). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/custom_embedding.cpython-310.pyc ADDED
Binary file (775 Bytes). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/flash_attn_triton.cpython-310.pyc ADDED
Binary file (20.2 kB). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/hf_prefixlm_converter.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/meta_init_context.cpython-310.pyc ADDED
Binary file (3.81 kB). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/modeling_mpt.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/norm.cpython-310.pyc ADDED
Binary file (2.89 kB). View file
 
LLaVA/llava/model/language_model/mpt/__pycache__/param_init_fns.cpython-310.pyc ADDED
Binary file (8.58 kB). View file
 
LLaVA/llava/model/language_model/mpt/adapt_tokenizer.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+ from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
3
+ Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
4
+ NUM_SENTINEL_TOKENS: int = 100
5
+
6
+ def adapt_tokenizer_for_denoising(tokenizer: Tokenizer):
7
+ """Adds sentinel tokens and padding token (if missing).
8
+
9
+ Expands the tokenizer vocabulary to include sentinel tokens
10
+ used in mixture-of-denoiser tasks as well as a padding token.
11
+
12
+ All added tokens are added as special tokens. No tokens are
13
+ added if sentinel tokens and padding token already exist.
14
+ """
15
+ sentinels_to_add = [f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)]
16
+ tokenizer.add_tokens(sentinels_to_add, special_tokens=True)
17
+ if tokenizer.pad_token is None:
18
+ tokenizer.add_tokens('<pad>', special_tokens=True)
19
+ tokenizer.pad_token = '<pad>'
20
+ assert tokenizer.pad_token_id is not None
21
+ sentinels = ''.join([f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)])
22
+ _sentinel_token_ids = tokenizer(sentinels, add_special_tokens=False).input_ids
23
+ tokenizer.sentinel_token_ids = _sentinel_token_ids
24
+
25
+ class AutoTokenizerForMOD(AutoTokenizer):
26
+ """AutoTokenizer + Adaptation for MOD.
27
+
28
+ A simple wrapper around AutoTokenizer to make instantiating
29
+ an MOD-adapted tokenizer a bit easier.
30
+
31
+ MOD-adapted tokenizers have sentinel tokens (e.g., <extra_id_0>),
32
+ a padding token, and a property to get the token ids of the
33
+ sentinel tokens.
34
+ """
35
+
36
+ @classmethod
37
+ def from_pretrained(cls, *args, **kwargs):
38
+ """See `AutoTokenizer.from_pretrained` docstring."""
39
+ tokenizer = super().from_pretrained(*args, **kwargs)
40
+ adapt_tokenizer_for_denoising(tokenizer)
41
+ return tokenizer
LLaVA/llava/model/language_model/mpt/attention.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attention layers."""
2
+ import math
3
+ import warnings
4
+ from typing import Optional
5
+ import torch
6
+ import torch.nn as nn
7
+ from einops import rearrange
8
+ from packaging import version
9
+ from torch import nn
10
+ from .norm import LPLayerNorm
11
+
12
+ def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool):
13
+ if original_is_causal and num_query_tokens != num_key_tokens:
14
+ if num_query_tokens != 1:
15
+ raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.')
16
+ else:
17
+ return False
18
+ return original_is_causal
19
+
20
+ def scaled_multihead_dot_product_attention(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
21
+ q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads)
22
+ kv_n_heads = 1 if multiquery else n_heads
23
+ k = rearrange(key, 'b s (h d) -> b h d s', h=kv_n_heads)
24
+ v = rearrange(value, 'b s (h d) -> b h s d', h=kv_n_heads)
25
+ if past_key_value is not None:
26
+ if len(past_key_value) != 0:
27
+ k = torch.cat([past_key_value[0], k], dim=3)
28
+ v = torch.cat([past_key_value[1], v], dim=2)
29
+ past_key_value = (k, v)
30
+ (b, _, s_q, d) = q.shape
31
+ s_k = k.size(-1)
32
+ if softmax_scale is None:
33
+ softmax_scale = 1 / math.sqrt(d)
34
+ attn_weight = q.matmul(k) * softmax_scale
35
+ if attn_bias is not None:
36
+ _s_q = max(0, attn_bias.size(2) - s_q)
37
+ _s_k = max(0, attn_bias.size(3) - s_k)
38
+ attn_bias = attn_bias[:, :, _s_q:, _s_k:]
39
+ if attn_bias.size(-1) != 1 and attn_bias.size(-1) != s_k or (attn_bias.size(-2) != 1 and attn_bias.size(-2) != s_q):
40
+ raise RuntimeError(f'attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}.')
41
+ attn_weight = attn_weight + attn_bias
42
+ min_val = torch.finfo(q.dtype).min
43
+ if key_padding_mask is not None:
44
+ if attn_bias is not None:
45
+ warnings.warn('Propogating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unneccessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
46
+ attn_weight = attn_weight.masked_fill(~key_padding_mask.view((b, 1, 1, s_k)), min_val)
47
+ if is_causal and (not q.size(2) == 1):
48
+ s = max(s_q, s_k)
49
+ causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
50
+ causal_mask = causal_mask.tril()
51
+ causal_mask = causal_mask.to(torch.bool)
52
+ causal_mask = ~causal_mask
53
+ causal_mask = causal_mask[-s_q:, -s_k:]
54
+ attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k), min_val)
55
+ attn_weight = torch.softmax(attn_weight, dim=-1)
56
+ if dropout_p:
57
+ attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p, training=training, inplace=True)
58
+ out = attn_weight.to(v.dtype).matmul(v)
59
+ out = rearrange(out, 'b h s d -> b s (h d)')
60
+ if needs_weights:
61
+ return (out, attn_weight, past_key_value)
62
+ return (out, None, past_key_value)
63
+
64
+ def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
65
+ for tensor in tensors:
66
+ if tensor.dtype not in valid_dtypes:
67
+ raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.')
68
+ if not tensor.is_cuda:
69
+ raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
70
+
71
+ def flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
72
+ try:
73
+ from flash_attn import bert_padding, flash_attn_interface
74
+ except:
75
+ raise RuntimeError('Please install flash-attn==1.0.3.post0')
76
+ check_valid_inputs(query, key, value)
77
+ if past_key_value is not None:
78
+ if len(past_key_value) != 0:
79
+ key = torch.cat([past_key_value[0], key], dim=1)
80
+ value = torch.cat([past_key_value[1], value], dim=1)
81
+ past_key_value = (key, value)
82
+ if attn_bias is not None:
83
+ _s_q = max(0, attn_bias.size(2) - query.size(1))
84
+ _s_k = max(0, attn_bias.size(3) - key.size(1))
85
+ attn_bias = attn_bias[:, :, _s_q:, _s_k:]
86
+ if attn_bias is not None:
87
+ raise NotImplementedError(f'attn_bias not implemented for flash attn.')
88
+ (batch_size, seqlen) = query.shape[:2]
89
+ if key_padding_mask is None:
90
+ key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
91
+ query_padding_mask = key_padding_mask[:, -query.size(1):]
92
+ (query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(query, query_padding_mask)
93
+ query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
94
+ (key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(key, key_padding_mask)
95
+ key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
96
+ (value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
97
+ value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
98
+ if multiquery:
99
+ key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
100
+ value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
101
+ dropout_p = dropout_p if training else 0.0
102
+ reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
103
+ output_unpad = flash_attn_interface.flash_attn_unpadded_func(query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
104
+ output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
105
+ return (output, None, past_key_value)
106
+
107
+ def triton_flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
108
+ try:
109
+ from .flash_attn_triton import flash_attn_func
110
+ except:
111
+ _installed = False
112
+ if version.parse(torch.__version__) < version.parse('2.0.0'):
113
+ _installed = True
114
+ try:
115
+ from flash_attn.flash_attn_triton import flash_attn_func
116
+ except:
117
+ _installed = False
118
+ if not _installed:
119
+ raise RuntimeError('Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU and `pip install .[gpu]` if installing from llm-foundry source or `pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). Note: (1) requires you have CMake and PyTorch already installed.')
120
+ check_valid_inputs(query, key, value)
121
+ if past_key_value is not None:
122
+ if len(past_key_value) != 0:
123
+ key = torch.cat([past_key_value[0], key], dim=1)
124
+ value = torch.cat([past_key_value[1], value], dim=1)
125
+ past_key_value = (key, value)
126
+ if attn_bias is not None:
127
+ _s_q = max(0, attn_bias.size(2) - query.size(1))
128
+ _s_k = max(0, attn_bias.size(3) - key.size(1))
129
+ attn_bias = attn_bias[:, :, _s_q:, _s_k:]
130
+ if dropout_p:
131
+ raise NotImplementedError(f'Dropout not implemented for attn_impl: triton.')
132
+ if needs_weights:
133
+ raise NotImplementedError(f'attn_impl: triton cannot return attn weights.')
134
+ if key_padding_mask is not None:
135
+ warnings.warn('Propagating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unnecessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
136
+ (b_size, s_k) = key_padding_mask.shape[:2]
137
+ if attn_bias is None:
138
+ attn_bias = query.new_zeros(b_size, 1, 1, s_k)
139
+ attn_bias = attn_bias.masked_fill(~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min)
140
+ query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
141
+ key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
142
+ value = rearrange(value, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
143
+ if multiquery:
144
+ key = key.expand(*key.shape[:2], n_heads, key.size(-1))
145
+ value = value.expand(*value.shape[:2], n_heads, value.size(-1))
146
+ reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
147
+ attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
148
+ output = attn_output.view(*attn_output.shape[:2], -1)
149
+ return (output, None, past_key_value)
150
+
151
+ class MultiheadAttention(nn.Module):
152
+ """Multi-head self attention.
153
+
154
+ Using torch or triton attention implementation enables user to also use
155
+ additive bias.
156
+ """
157
+
158
+ def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
159
+ super().__init__()
160
+ self.attn_impl = attn_impl
161
+ self.clip_qkv = clip_qkv
162
+ self.qk_ln = qk_ln
163
+ self.d_model = d_model
164
+ self.n_heads = n_heads
165
+ self.softmax_scale = softmax_scale
166
+ if self.softmax_scale is None:
167
+ self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
168
+ self.attn_dropout_p = attn_pdrop
169
+ self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device)
170
+ fuse_splits = (d_model, 2 * d_model)
171
+ self.Wqkv._fused = (0, fuse_splits)
172
+ if self.qk_ln:
173
+ layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
174
+ self.q_ln = layernorm_class(self.d_model, device=device)
175
+ self.k_ln = layernorm_class(self.d_model, device=device)
176
+ if self.attn_impl == 'flash':
177
+ self.attn_fn = flash_attn_fn
178
+ elif self.attn_impl == 'triton':
179
+ self.attn_fn = triton_flash_attn_fn
180
+ if verbose:
181
+ warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
182
+ elif self.attn_impl == 'torch':
183
+ self.attn_fn = scaled_multihead_dot_product_attention
184
+ if torch.cuda.is_available() and verbose:
185
+ warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
186
+ else:
187
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
188
+ self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
189
+ self.out_proj._is_residual = True
190
+
191
+ def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
192
+ qkv = self.Wqkv(x)
193
+ if self.clip_qkv:
194
+ qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
195
+ (query, key, value) = qkv.chunk(3, dim=2)
196
+ key_padding_mask = attention_mask
197
+ if self.qk_ln:
198
+ dtype = query.dtype
199
+ query = self.q_ln(query).to(dtype)
200
+ key = self.k_ln(key).to(dtype)
201
+ (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights)
202
+ return (self.out_proj(context), attn_weights, past_key_value)
203
+
204
+ class MultiQueryAttention(nn.Module):
205
+ """Multi-Query self attention.
206
+
207
+ Using torch or triton attention implementation enables user to also use
208
+ additive bias.
209
+ """
210
+
211
+ def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
212
+ super().__init__()
213
+ self.attn_impl = attn_impl
214
+ self.clip_qkv = clip_qkv
215
+ self.qk_ln = qk_ln
216
+ self.d_model = d_model
217
+ self.n_heads = n_heads
218
+ self.head_dim = d_model // n_heads
219
+ self.softmax_scale = softmax_scale
220
+ if self.softmax_scale is None:
221
+ self.softmax_scale = 1 / math.sqrt(self.head_dim)
222
+ self.attn_dropout_p = attn_pdrop
223
+ self.Wqkv = nn.Linear(d_model, d_model + 2 * self.head_dim, device=device)
224
+ fuse_splits = (d_model, d_model + self.head_dim)
225
+ self.Wqkv._fused = (0, fuse_splits)
226
+ if self.qk_ln:
227
+ layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
228
+ self.q_ln = layernorm_class(d_model, device=device)
229
+ self.k_ln = layernorm_class(self.head_dim, device=device)
230
+ if self.attn_impl == 'flash':
231
+ self.attn_fn = flash_attn_fn
232
+ elif self.attn_impl == 'triton':
233
+ self.attn_fn = triton_flash_attn_fn
234
+ if verbose:
235
+ warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
236
+ elif self.attn_impl == 'torch':
237
+ self.attn_fn = scaled_multihead_dot_product_attention
238
+ if torch.cuda.is_available() and verbose:
239
+ warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
240
+ else:
241
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
242
+ self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
243
+ self.out_proj._is_residual = True
244
+
245
+ def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
246
+ qkv = self.Wqkv(x)
247
+ if self.clip_qkv:
248
+ qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
249
+ (query, key, value) = qkv.split([self.d_model, self.head_dim, self.head_dim], dim=2)
250
+ key_padding_mask = attention_mask
251
+ if self.qk_ln:
252
+ dtype = query.dtype
253
+ query = self.q_ln(query).to(dtype)
254
+ key = self.k_ln(key).to(dtype)
255
+ (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, multiquery=True)
256
+ return (self.out_proj(context), attn_weights, past_key_value)
257
+
258
+ def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):
259
+ if attn_impl == 'flash':
260
+ return None
261
+ elif attn_impl in ['torch', 'triton']:
262
+ if alibi:
263
+ if (prefix_lm or not causal) or use_sequence_id:
264
+ return (1, n_heads, seq_len, seq_len)
265
+ return (1, n_heads, 1, seq_len)
266
+ elif prefix_lm or use_sequence_id:
267
+ return (1, 1, seq_len, seq_len)
268
+ return None
269
+ else:
270
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
271
+
272
+ def build_attn_bias(attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8):
273
+ if attn_impl == 'flash':
274
+ return None
275
+ elif attn_impl in ['torch', 'triton']:
276
+ if alibi:
277
+ (device, dtype) = (attn_bias.device, attn_bias.dtype)
278
+ attn_bias = attn_bias.add(build_alibi_bias(n_heads, seq_len, full=not causal, alibi_bias_max=alibi_bias_max, device=device, dtype=dtype))
279
+ return attn_bias
280
+ else:
281
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
282
+
283
+ def gen_slopes(n_heads, alibi_bias_max=8, device=None):
284
+ _n_heads = 2 ** math.ceil(math.log2(n_heads))
285
+ m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
286
+ m = m.mul(alibi_bias_max / _n_heads)
287
+ slopes = 1.0 / torch.pow(2, m)
288
+ if _n_heads != n_heads:
289
+ slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
290
+ return slopes.view(1, n_heads, 1, 1)
291
+
292
+ def build_alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None):
293
+ alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, 1, seq_len)
294
+ if full:
295
+ alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, seq_len, 1)
296
+ alibi_bias = alibi_bias.abs().mul(-1)
297
+ slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
298
+ alibi_bias = alibi_bias * slopes
299
+ return alibi_bias.to(dtype=dtype)
300
+ ATTN_CLASS_REGISTRY = {'multihead_attention': MultiheadAttention, 'multiquery_attention': MultiQueryAttention}
LLaVA/llava/model/language_model/mpt/blocks.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GPT Blocks used for the GPT Model."""
2
+ from typing import Dict, Optional, Tuple
3
+ import torch
4
+ import torch.nn as nn
5
+ from .attention import ATTN_CLASS_REGISTRY
6
+ from .norm import NORM_CLASS_REGISTRY
7
+
8
+ class MPTMLP(nn.Module):
9
+
10
+ def __init__(self, d_model: int, expansion_ratio: int, device: Optional[str]=None):
11
+ super().__init__()
12
+ self.up_proj = nn.Linear(d_model, expansion_ratio * d_model, device=device)
13
+ self.act = nn.GELU(approximate='none')
14
+ self.down_proj = nn.Linear(expansion_ratio * d_model, d_model, device=device)
15
+ self.down_proj._is_residual = True
16
+
17
+ def forward(self, x):
18
+ return self.down_proj(self.act(self.up_proj(x)))
19
+
20
+ class MPTBlock(nn.Module):
21
+
22
+ def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Dict={'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}, resid_pdrop: float=0.0, norm_type: str='low_precision_layernorm', verbose: int=0, device: Optional[str]=None, **kwargs):
23
+ del kwargs
24
+ super().__init__()
25
+ norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
26
+ attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']]
27
+ self.norm_1 = norm_class(d_model, device=device)
28
+ self.attn = attn_class(attn_impl=attn_config['attn_impl'], clip_qkv=attn_config['clip_qkv'], qk_ln=attn_config['qk_ln'], softmax_scale=attn_config['softmax_scale'], attn_pdrop=attn_config['attn_pdrop'], d_model=d_model, n_heads=n_heads, verbose=verbose, device=device)
29
+ self.norm_2 = norm_class(d_model, device=device)
30
+ self.ffn = MPTMLP(d_model=d_model, expansion_ratio=expansion_ratio, device=device)
31
+ self.resid_attn_dropout = nn.Dropout(resid_pdrop)
32
+ self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
33
+
34
+ def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.ByteTensor]=None, is_causal: bool=True) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor]]]:
35
+ a = self.norm_1(x)
36
+ (b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=is_causal)
37
+ x = x + self.resid_attn_dropout(b)
38
+ m = self.norm_2(x)
39
+ n = self.ffn(m)
40
+ x = x + self.resid_ffn_dropout(n)
41
+ return (x, attn_weights, past_key_value)
LLaVA/llava/model/language_model/mpt/configuration_mpt.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A HuggingFace-style model configuration."""
2
+ from typing import Dict, Optional, Union
3
+ from transformers import PretrainedConfig
4
+ attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
5
+ init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
6
+
7
+ class MPTConfig(PretrainedConfig):
8
+ model_type = 'mpt'
9
+
10
+ def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, verbose: int=0, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, **kwargs):
11
+ """The MPT configuration class.
12
+
13
+ Args:
14
+ d_model (int): The size of the embedding dimension of the model.
15
+ n_heads (int): The number of attention heads.
16
+ n_layers (int): The number of layers in the model.
17
+ expansion_ratio (int): The ratio of the up/down scale in the MLP.
18
+ max_seq_len (int): The maximum sequence length of the model.
19
+ vocab_size (int): The size of the vocabulary.
20
+ resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
21
+ emb_pdrop (float): The dropout probability for the embedding layer.
22
+ learned_pos_emb (bool): Whether to use learned positional embeddings
23
+ attn_config (Dict): A dictionary used to configure the model's attention module:
24
+ attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention
25
+ attn_pdrop (float): The dropout probability for the attention layers.
26
+ attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
27
+ qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
28
+ clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to
29
+ this value.
30
+ softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None,
31
+ use the default scale of ``1/sqrt(d_keys)``.
32
+ prefix_lm (Optional[bool]): Whether the model should operate as a Prefix LM. This requires passing an
33
+ extra `prefix_mask` argument which indicates which tokens belong to the prefix. Tokens in the prefix
34
+ can attend to one another bi-directionally. Tokens outside the prefix use causal attention.
35
+ attn_uses_sequence_id (Optional[bool]): Whether to restrict attention to tokens that have the same sequence_id.
36
+ When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
37
+ which sub-sequence each token belongs to.
38
+ Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
39
+ alibi (bool): Whether to use the alibi bias instead of position embeddings.
40
+ alibi_bias_max (int): The maximum value of the alibi bias.
41
+ init_device (str): The device to use for parameter initialization.
42
+ logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
43
+ no_bias (bool): Whether to use bias in all layers.
44
+ verbose (int): The verbosity level. 0 is silent.
45
+ embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
46
+ norm_type (str): choose type of norm to use
47
+ multiquery_attention (bool): Whether to use multiquery attention implementation.
48
+ use_cache (bool): Whether or not the model should return the last key/values attentions
49
+ init_config (Dict): A dictionary used to configure the model initialization:
50
+ init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
51
+ 'kaiming_uniform_', 'kaiming_normal_', 'neox_init_', 'small_init_', 'xavier_uniform_', or
52
+ 'xavier_normal_'. These mimic the parameter initialization methods in PyTorch.
53
+ init_div_is_residual (Union[int, float, str, bool]): Value to divide initial weights by if ``module._is_residual`` is True.
54
+ emb_init_std (Optional[float]): The standard deviation of the normal distribution used to initialize the embedding layer.
55
+ emb_init_uniform_lim (Optional[Union[Tuple[float, float], float]]): The lower and upper limits of the uniform distribution
56
+ used to initialize the embedding layer. Mutually exclusive with ``emb_init_std``.
57
+ init_std (float): The standard deviation of the normal distribution used to initialize the model,
58
+ if using the baseline_ parameter initialization scheme.
59
+ init_gain (float): The gain to use for parameter initialization with kaiming or xavier initialization schemes.
60
+ fan_mode (str): The fan mode to use for parameter initialization with kaiming initialization schemes.
61
+ init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
62
+ ---
63
+ See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
64
+ """
65
+ self.d_model = d_model
66
+ self.n_heads = n_heads
67
+ self.n_layers = n_layers
68
+ self.expansion_ratio = expansion_ratio
69
+ self.max_seq_len = max_seq_len
70
+ self.vocab_size = vocab_size
71
+ self.resid_pdrop = resid_pdrop
72
+ self.emb_pdrop = emb_pdrop
73
+ self.learned_pos_emb = learned_pos_emb
74
+ self.attn_config = attn_config
75
+ self.init_device = init_device
76
+ self.logit_scale = logit_scale
77
+ self.no_bias = no_bias
78
+ self.verbose = verbose
79
+ self.embedding_fraction = embedding_fraction
80
+ self.norm_type = norm_type
81
+ self.use_cache = use_cache
82
+ self.init_config = init_config
83
+ if 'name' in kwargs:
84
+ del kwargs['name']
85
+ if 'loss_fn' in kwargs:
86
+ del kwargs['loss_fn']
87
+ super().__init__(**kwargs)
88
+ self._validate_config()
89
+
90
+ def _set_config_defaults(self, config, config_defaults):
91
+ for (k, v) in config_defaults.items():
92
+ if k not in config:
93
+ config[k] = v
94
+ return config
95
+
96
+ def _validate_config(self):
97
+ self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
98
+ self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
99
+ if self.d_model % self.n_heads != 0:
100
+ raise ValueError('d_model must be divisible by n_heads')
101
+ if any((prob < 0 or prob > 1 for prob in [self.attn_config['attn_pdrop'], self.resid_pdrop, self.emb_pdrop])):
102
+ raise ValueError("self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are probabilities and must be between 0 and 1")
103
+ if self.attn_config['attn_impl'] not in ['torch', 'flash', 'triton']:
104
+ raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
105
+ if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
106
+ raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
107
+ if self.attn_config['alibi'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
108
+ raise NotImplementedError('alibi only implemented with torch and triton attention.')
109
+ if self.attn_config['attn_uses_sequence_id'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
110
+ raise NotImplementedError('attn_uses_sequence_id only implemented with torch and triton attention.')
111
+ if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
112
+ raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
113
+ if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
114
+ raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
115
+ if self.init_config.get('name', None) is None:
116
+ raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
117
+ if not self.learned_pos_emb and (not self.attn_config['alibi']):
118
+ raise ValueError(f'Positional information must be provided to the model using either learned_pos_emb or alibi.')
LLaVA/llava/model/language_model/mpt/custom_embedding.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torch import Tensor
5
+
6
+ class SharedEmbedding(nn.Embedding):
7
+
8
+ def forward(self, input: Tensor, unembed: bool=False) -> Tensor:
9
+ if unembed:
10
+ return F.linear(input, self.weight)
11
+ return super().forward(input)
LLaVA/llava/model/language_model/mpt/flash_attn_triton.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py
3
+ update imports to use 'triton_pre_mlir'
4
+
5
+ *Experimental* implementation of FlashAttention in Triton.
6
+ Tested with triton==2.0.0.dev20221202.
7
+ Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions
8
+ other than 64:
9
+ https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207
10
+ We'll update this implementation with the new Triton backend once this is fixed.
11
+
12
+ We use the FlashAttention implementation from Phil Tillet a starting point.
13
+ https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
14
+
15
+ Changes:
16
+ - Implement both causal and non-causal attention.
17
+ - Implement both self-attention and cross-attention.
18
+ - Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
19
+ - Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
20
+ - Support attention bias.
21
+ - Speed up the forward pass a bit, and only store the LSE instead of m and l.
22
+ - Make the backward for d=128 much faster by reducing register spilling.
23
+ - Optionally parallelize the backward pass across seqlen_k, to deal with the case of
24
+ small batch size * nheads.
25
+
26
+ Caution:
27
+ - This is an *experimental* implementation. The forward pass should be quite robust but
28
+ I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler).
29
+ - This implementation has only been tested on A100.
30
+ - If you plan to use headdim other than 64 and 128, you should test for race conditions
31
+ (due to the Triton compiler), as done in tests/test_flash_attn.py
32
+ "test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
33
+ for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
34
+ that there are none left for other head dimensions.
35
+
36
+ Differences between this Triton version and the CUDA version:
37
+ - Triton version doesn't support dropout.
38
+ - Triton forward is generally faster than CUDA forward, while Triton backward is
39
+ generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
40
+ than CUDA forward + backward.
41
+ - Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
42
+ - Triton version supports attention bias, while CUDA version doesn't.
43
+ """
44
+ import math
45
+ import torch
46
+ import triton_pre_mlir as triton
47
+ import triton_pre_mlir.language as tl
48
+
49
+ @triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
50
+ @triton.jit
51
+ def _fwd_kernel(Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_ob, stride_oh, stride_om, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
52
+ start_m = tl.program_id(0)
53
+ off_hb = tl.program_id(1)
54
+ off_b = off_hb // nheads
55
+ off_h = off_hb % nheads
56
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
57
+ offs_n = tl.arange(0, BLOCK_N)
58
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
59
+ q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :])
60
+ k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :])
61
+ v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :])
62
+ if BIAS_TYPE == 'vector':
63
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
64
+ elif BIAS_TYPE == 'matrix':
65
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :])
66
+ t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
67
+ lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
68
+ m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
69
+ acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
70
+ if EVEN_M & EVEN_N:
71
+ if EVEN_HEADDIM:
72
+ q = tl.load(q_ptrs)
73
+ else:
74
+ q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
75
+ elif EVEN_HEADDIM:
76
+ q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
77
+ else:
78
+ q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
79
+ end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
80
+ for start_n in range(0, end_n, BLOCK_N):
81
+ start_n = tl.multiple_of(start_n, BLOCK_N)
82
+ if EVEN_N & EVEN_M:
83
+ if EVEN_HEADDIM:
84
+ k = tl.load(k_ptrs + start_n * stride_kn)
85
+ else:
86
+ k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0)
87
+ elif EVEN_HEADDIM:
88
+ k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
89
+ else:
90
+ k = tl.load(k_ptrs + start_n * stride_kn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
91
+ qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
92
+ qk += tl.dot(q, k, trans_b=True)
93
+ if not EVEN_N:
94
+ qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float('-inf'))
95
+ if IS_CAUSAL:
96
+ qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float('-inf'))
97
+ if BIAS_TYPE != 'none':
98
+ if BIAS_TYPE == 'vector':
99
+ if EVEN_N:
100
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
101
+ else:
102
+ bias = tl.load(b_ptrs + start_n, mask=start_n + offs_n < seqlen_k, other=0.0).to(tl.float32)
103
+ bias = bias[None, :]
104
+ elif BIAS_TYPE == 'matrix':
105
+ if EVEN_M & EVEN_N:
106
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
107
+ else:
108
+ bias = tl.load(b_ptrs + start_n, mask=(offs_m[:, None] < seqlen_q) & ((start_n + offs_n)[None, :] < seqlen_k), other=0.0).to(tl.float32)
109
+ qk = qk * softmax_scale + bias
110
+ m_ij = tl.maximum(tl.max(qk, 1), lse_i)
111
+ p = tl.exp(qk - m_ij[:, None])
112
+ else:
113
+ m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
114
+ p = tl.exp(qk * softmax_scale - m_ij[:, None])
115
+ l_ij = tl.sum(p, 1)
116
+ acc_o_scale = tl.exp(m_i - m_ij)
117
+ tl.store(t_ptrs, acc_o_scale)
118
+ acc_o_scale = tl.load(t_ptrs)
119
+ acc_o = acc_o * acc_o_scale[:, None]
120
+ if EVEN_N & EVEN_M:
121
+ if EVEN_HEADDIM:
122
+ v = tl.load(v_ptrs + start_n * stride_vn)
123
+ else:
124
+ v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0)
125
+ elif EVEN_HEADDIM:
126
+ v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
127
+ else:
128
+ v = tl.load(v_ptrs + start_n * stride_vn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
129
+ p = p.to(v.dtype)
130
+ acc_o += tl.dot(p, v)
131
+ m_i = m_ij
132
+ l_i_new = tl.exp(lse_i - m_ij) + l_ij
133
+ lse_i = m_ij + tl.log(l_i_new)
134
+ o_scale = tl.exp(m_i - lse_i)
135
+ tl.store(t_ptrs, o_scale)
136
+ o_scale = tl.load(t_ptrs)
137
+ acc_o = acc_o * o_scale[:, None]
138
+ start_m = tl.program_id(0)
139
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
140
+ lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
141
+ tl.store(lse_ptrs, lse_i)
142
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
143
+ out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :])
144
+ if EVEN_M:
145
+ if EVEN_HEADDIM:
146
+ tl.store(out_ptrs, acc_o)
147
+ else:
148
+ tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
149
+ elif EVEN_HEADDIM:
150
+ tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
151
+ else:
152
+ tl.store(out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
153
+
154
+ @triton.jit
155
+ def _bwd_preprocess_do_o_dot(Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr):
156
+ start_m = tl.program_id(0)
157
+ off_hb = tl.program_id(1)
158
+ off_b = off_hb // nheads
159
+ off_h = off_hb % nheads
160
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
161
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
162
+ o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
163
+ do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
164
+ delta = tl.sum(o * do, axis=1)
165
+ tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
166
+
167
+ @triton.jit
168
+ def _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr):
169
+ if EVEN_N & EVEN_M:
170
+ if EVEN_HEADDIM:
171
+ tl.store(dv_ptrs, dv)
172
+ tl.store(dk_ptrs, dk)
173
+ else:
174
+ tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
175
+ tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
176
+ elif EVEN_HEADDIM:
177
+ tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
178
+ tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
179
+ else:
180
+ tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
181
+ tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
182
+
183
+ @triton.jit
184
+ def _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD: tl.constexpr, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
185
+ begin_m = 0 if not IS_CAUSAL else start_n * BLOCK_N // BLOCK_M * BLOCK_M
186
+ offs_qm = begin_m + tl.arange(0, BLOCK_M)
187
+ offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
188
+ offs_m = tl.arange(0, BLOCK_M)
189
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
190
+ q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
191
+ k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
192
+ v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
193
+ do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
194
+ dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
195
+ if BIAS_TYPE == 'vector':
196
+ b_ptrs = Bias + offs_n
197
+ elif BIAS_TYPE == 'matrix':
198
+ b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
199
+ dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
200
+ dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
201
+ if begin_m >= seqlen_q:
202
+ dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
203
+ dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
204
+ _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
205
+ return
206
+ if EVEN_N & EVEN_M:
207
+ if EVEN_HEADDIM:
208
+ k = tl.load(k_ptrs)
209
+ v = tl.load(v_ptrs)
210
+ else:
211
+ k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
212
+ v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
213
+ elif EVEN_HEADDIM:
214
+ k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
215
+ v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
216
+ else:
217
+ k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
218
+ v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
219
+ num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
220
+ for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
221
+ start_m = tl.multiple_of(start_m, BLOCK_M)
222
+ offs_m_curr = start_m + offs_m
223
+ if EVEN_M & EVEN_HEADDIM:
224
+ q = tl.load(q_ptrs)
225
+ elif EVEN_HEADDIM:
226
+ q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
227
+ else:
228
+ q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
229
+ qk = tl.dot(q, k, trans_b=True)
230
+ if not EVEN_N:
231
+ qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf'))
232
+ if IS_CAUSAL:
233
+ qk = tl.where(offs_m_curr[:, None] >= offs_n[None, :], qk, float('-inf'))
234
+ if BIAS_TYPE != 'none':
235
+ tl.debug_barrier()
236
+ if BIAS_TYPE == 'vector':
237
+ if EVEN_N:
238
+ bias = tl.load(b_ptrs).to(tl.float32)
239
+ else:
240
+ bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32)
241
+ bias = bias[None, :]
242
+ elif BIAS_TYPE == 'matrix':
243
+ if EVEN_M & EVEN_N:
244
+ bias = tl.load(b_ptrs).to(tl.float32)
245
+ else:
246
+ bias = tl.load(b_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), other=0.0).to(tl.float32)
247
+ qk = qk * softmax_scale + bias
248
+ if not EVEN_M & EVEN_HEADDIM:
249
+ tl.debug_barrier()
250
+ lse_i = tl.load(LSE + offs_m_curr)
251
+ if BIAS_TYPE == 'none':
252
+ p = tl.exp(qk * softmax_scale - lse_i[:, None])
253
+ else:
254
+ p = tl.exp(qk - lse_i[:, None])
255
+ if EVEN_M & EVEN_HEADDIM:
256
+ do = tl.load(do_ptrs)
257
+ else:
258
+ do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
259
+ dv += tl.dot(p.to(do.dtype), do, trans_a=True)
260
+ if not EVEN_M & EVEN_HEADDIM:
261
+ tl.debug_barrier()
262
+ dp = tl.dot(do, v, trans_b=True)
263
+ if not EVEN_HEADDIM:
264
+ tl.debug_barrier()
265
+ Di = tl.load(D + offs_m_curr)
266
+ ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
267
+ dk += tl.dot(ds, q, trans_a=True)
268
+ if not EVEN_M & EVEN_HEADDIM:
269
+ tl.debug_barrier()
270
+ if not ATOMIC_ADD:
271
+ if EVEN_M & EVEN_HEADDIM:
272
+ dq = tl.load(dq_ptrs, eviction_policy='evict_last')
273
+ dq += tl.dot(ds, k)
274
+ tl.store(dq_ptrs, dq, eviction_policy='evict_last')
275
+ elif EVEN_HEADDIM:
276
+ dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0, eviction_policy='evict_last')
277
+ dq += tl.dot(ds, k)
278
+ tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q, eviction_policy='evict_last')
279
+ else:
280
+ dq = tl.load(dq_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0, eviction_policy='evict_last')
281
+ dq += tl.dot(ds, k)
282
+ tl.store(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), eviction_policy='evict_last')
283
+ else:
284
+ dq = tl.dot(ds, k)
285
+ if EVEN_M & EVEN_HEADDIM:
286
+ tl.atomic_add(dq_ptrs, dq)
287
+ elif EVEN_HEADDIM:
288
+ tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
289
+ else:
290
+ tl.atomic_add(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
291
+ dq_ptrs += BLOCK_M * stride_dqm
292
+ q_ptrs += BLOCK_M * stride_qm
293
+ do_ptrs += BLOCK_M * stride_dom
294
+ if BIAS_TYPE == 'matrix':
295
+ b_ptrs += BLOCK_M * stride_bm
296
+ dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
297
+ dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
298
+ _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
299
+
300
+ def init_to_zero(name):
301
+ return lambda nargs: nargs[name].zero_()
302
+
303
+ @triton.autotune(configs=[triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ'))], key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'])
304
+ @triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
305
+ @triton.jit
306
+ def _bwd_kernel(Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_dob, stride_doh, stride_dom, stride_dqb, stride_dqh, stride_dqm, stride_dkb, stride_dkh, stride_dkn, stride_dvb, stride_dvh, stride_dvn, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, SEQUENCE_PARALLEL: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
307
+ off_hb = tl.program_id(1)
308
+ off_b = off_hb // nheads
309
+ off_h = off_hb % nheads
310
+ Q += off_b * stride_qb + off_h * stride_qh
311
+ K += off_b * stride_kb + off_h * stride_kh
312
+ V += off_b * stride_vb + off_h * stride_vh
313
+ DO += off_b * stride_dob + off_h * stride_doh
314
+ DQ += off_b * stride_dqb + off_h * stride_dqh
315
+ DK += off_b * stride_dkb + off_h * stride_dkh
316
+ DV += off_b * stride_dvb + off_h * stride_dvh
317
+ if BIAS_TYPE != 'none':
318
+ Bias += off_b * stride_bb + off_h * stride_bh
319
+ D += off_hb * seqlen_q_rounded
320
+ LSE += off_hb * seqlen_q_rounded
321
+ if not SEQUENCE_PARALLEL:
322
+ num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
323
+ for start_n in range(0, num_block_n):
324
+ _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=False, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
325
+ else:
326
+ start_n = tl.program_id(0)
327
+ _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=True, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
328
+
329
+ def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
330
+ (batch, seqlen_q, nheads, d) = q.shape
331
+ (_, seqlen_k, _, _) = k.shape
332
+ assert k.shape == (batch, seqlen_k, nheads, d)
333
+ assert v.shape == (batch, seqlen_k, nheads, d)
334
+ assert d <= 128, 'FlashAttention only support head dimensions up to 128'
335
+ assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
336
+ assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16'
337
+ assert q.is_cuda and k.is_cuda and v.is_cuda
338
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
339
+ has_bias = bias is not None
340
+ bias_type = 'none'
341
+ if has_bias:
342
+ assert bias.dtype in [q.dtype, torch.float]
343
+ assert bias.is_cuda
344
+ assert bias.dim() == 4
345
+ if bias.stride(-1) != 1:
346
+ bias = bias.contiguous()
347
+ if bias.shape[2:] == (1, seqlen_k):
348
+ bias_type = 'vector'
349
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
350
+ bias_type = 'matrix'
351
+ else:
352
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
353
+ bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
354
+ bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
355
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
356
+ lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
357
+ tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
358
+ o = torch.empty_like(q)
359
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
360
+ BLOCK = 128
361
+ num_warps = 4 if d <= 64 else 8
362
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
363
+ _fwd_kernel[grid](q, k, v, bias, o, lse, tmp, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, o.stride(0), o.stride(2), o.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM, BLOCK_M=BLOCK, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1)
364
+ return (o, lse, softmax_scale)
365
+
366
+ def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None):
367
+ if do.stride(-1) != 1:
368
+ do = do.contiguous()
369
+ (batch, seqlen_q, nheads, d) = q.shape
370
+ (_, seqlen_k, _, _) = k.shape
371
+ assert d <= 128
372
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
373
+ assert lse.shape == (batch, nheads, seqlen_q_rounded)
374
+ assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
375
+ assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
376
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
377
+ dq_accum = torch.empty_like(q, dtype=torch.float32)
378
+ delta = torch.empty_like(lse)
379
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
380
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
381
+ _bwd_preprocess_do_o_dot[grid](o, do, delta, o.stride(0), o.stride(2), o.stride(1), do.stride(0), do.stride(2), do.stride(1), nheads, seqlen_q, seqlen_q_rounded, d, BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM)
382
+ has_bias = bias is not None
383
+ bias_type = 'none'
384
+ if has_bias:
385
+ assert bias.dtype in [q.dtype, torch.float]
386
+ assert bias.is_cuda
387
+ assert bias.dim() == 4
388
+ assert bias.stride(-1) == 1
389
+ if bias.shape[2:] == (1, seqlen_k):
390
+ bias_type = 'vector'
391
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
392
+ bias_type = 'matrix'
393
+ else:
394
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
395
+ bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
396
+ bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
397
+ grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N']) if META['SEQUENCE_PARALLEL'] else 1, batch * nheads)
398
+ _bwd_kernel[grid](q, k, v, bias, do, dq_accum, dk, dv, lse, delta, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, do.stride(0), do.stride(2), do.stride(1), dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1), dk.stride(0), dk.stride(2), dk.stride(1), dv.stride(0), dv.stride(2), dv.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM)
399
+ dq.copy_(dq_accum)
400
+
401
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
402
+
403
+ @staticmethod
404
+ def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
405
+ """
406
+ qkv: (batch, seqlen, 3, nheads, headdim)
407
+ bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
408
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
409
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
410
+ """
411
+ if qkv.stride(-1) != 1:
412
+ qkv = qkv.contiguous()
413
+ (o, lse, ctx.softmax_scale) = _flash_attn_forward(qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal, softmax_scale=softmax_scale)
414
+ ctx.save_for_backward(qkv, o, lse, bias)
415
+ ctx.causal = causal
416
+ return o
417
+
418
+ @staticmethod
419
+ def backward(ctx, do):
420
+ (qkv, o, lse, bias) = ctx.saved_tensors
421
+ assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet'
422
+ with torch.inference_mode():
423
+ dqkv = torch.empty_like(qkv)
424
+ _flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse, dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
425
+ return (dqkv, None, None, None)
426
+ flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
427
+
428
+ class FlashAttnKVPackedFunc(torch.autograd.Function):
429
+
430
+ @staticmethod
431
+ def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
432
+ """
433
+ q: (batch, seqlen_q, nheads, headdim)
434
+ kv: (batch, seqlen_k, 2, nheads, headdim)
435
+ bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
436
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
437
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
438
+ """
439
+ (q, kv) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
440
+ (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale)
441
+ ctx.save_for_backward(q, kv, o, lse, bias)
442
+ ctx.causal = causal
443
+ return o
444
+
445
+ @staticmethod
446
+ def backward(ctx, do):
447
+ (q, kv, o, lse, bias) = ctx.saved_tensors
448
+ if len(ctx.needs_input_grad) >= 3:
449
+ assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet'
450
+ with torch.inference_mode():
451
+ dq = torch.empty_like(q)
452
+ dkv = torch.empty_like(kv)
453
+ _flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse, dq, dkv[:, :, 0], dkv[:, :, 1], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
454
+ return (dq, dkv, None, None, None)
455
+ flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
456
+
457
+ class FlashAttnFunc(torch.autograd.Function):
458
+
459
+ @staticmethod
460
+ def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
461
+ """
462
+ q: (batch_size, seqlen_q, nheads, headdim)
463
+ k, v: (batch_size, seqlen_k, nheads, headdim)
464
+ bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
465
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
466
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
467
+ """
468
+ (q, k, v) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
469
+ (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale)
470
+ ctx.save_for_backward(q, k, v, o, lse, bias)
471
+ ctx.causal = causal
472
+ return o
473
+
474
+ @staticmethod
475
+ def backward(ctx, do):
476
+ (q, k, v, o, lse, bias) = ctx.saved_tensors
477
+ assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet'
478
+ with torch.inference_mode():
479
+ dq = torch.empty_like(q)
480
+ dk = torch.empty_like(k)
481
+ dv = torch.empty_like(v)
482
+ _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
483
+ return (dq, dk, dv, None, None, None)
484
+ flash_attn_func = FlashAttnFunc.apply
LLaVA/llava/model/language_model/mpt/hf_prefixlm_converter.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Converts Huggingface Causal LM to Prefix LM.
2
+
3
+ Conversion does lightweight surgery on a HuggingFace
4
+ Causal LM to convert it to a Prefix LM.
5
+
6
+ Prefix LMs accepts a `bidirectional_mask` input in `forward`
7
+ and treat the input prompt as the prefix in `generate`.
8
+ """
9
+ import math
10
+ import warnings
11
+ from types import MethodType
12
+ from typing import Any, Dict, List, Optional, Tuple, Union
13
+ import torch
14
+ from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
15
+ from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
16
+ from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
17
+ from transformers.models.bloom.modeling_bloom import logging
18
+ from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
19
+ from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
20
+ from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
21
+ from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
22
+ from transformers.models.opt.modeling_opt import OPTForCausalLM
23
+ from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
24
+ from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
25
+ logger = logging.get_logger(__name__)
26
+ _SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
27
+ CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
28
+
29
+ def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_TYPES:
30
+ """Converts a GPT-style Causal LM to a Prefix LM.
31
+
32
+ Supported HuggingFace model classes:
33
+ - `GPT2LMHeadModel`
34
+ - `GPTNeoForCausalLM`
35
+ - `GPTNeoXForCausalLM`
36
+ - `GPTJForCausalLM`
37
+
38
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
39
+ """
40
+ if hasattr(model, '_prefix_lm_converted'):
41
+ return model
42
+ assert isinstance(model, _SUPPORTED_GPT_MODELS)
43
+ assert model.config.add_cross_attention == False, 'Only supports GPT-style decoder-only models'
44
+
45
+ def _get_attn_modules(model: CAUSAL_GPT_TYPES) -> List[torch.nn.Module]:
46
+ """Helper that gets a list of the model's attention modules.
47
+
48
+ Each module has a `bias` buffer used for causal masking. The Prefix LM
49
+ conversion adds logic to dynamically manipulate these biases to support
50
+ Prefix LM attention masking.
51
+ """
52
+ attn_modules = []
53
+ if isinstance(model, GPTNeoXForCausalLM):
54
+ blocks = model.gpt_neox.layers
55
+ else:
56
+ blocks = model.transformer.h
57
+ for block in blocks:
58
+ if isinstance(model, GPTNeoForCausalLM):
59
+ if block.attn.attention_type != 'global':
60
+ continue
61
+ attn_module = block.attn.attention
62
+ elif isinstance(model, GPTNeoXForCausalLM):
63
+ attn_module = block.attention
64
+ else:
65
+ attn_module = block.attn
66
+ attn_modules.append(attn_module)
67
+ return attn_modules
68
+ setattr(model, '_original_forward', getattr(model, 'forward'))
69
+ setattr(model, '_original_generate', getattr(model, 'generate'))
70
+
71
+ def forward(self: CAUSAL_GPT_TYPES, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, attention_mask: Optional[torch.FloatTensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
72
+ """Wraps original forward to enable PrefixLM attention."""
73
+
74
+ def call_og_forward():
75
+ if isinstance(self, GPTNeoXForCausalLM):
76
+ return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
77
+ else:
78
+ return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
79
+ if bidirectional_mask is None:
80
+ return call_og_forward()
81
+ assert isinstance(bidirectional_mask, torch.Tensor)
82
+ attn_modules = _get_attn_modules(model)
83
+ (b, s) = bidirectional_mask.shape
84
+ max_length = attn_modules[0].bias.shape[-1]
85
+ if s > max_length:
86
+ raise ValueError(f'bidirectional_mask sequence length (={s}) exceeds the ' + f'max length allowed by the model ({max_length}).')
87
+ assert s <= max_length
88
+ if s < max_length:
89
+ pad = torch.zeros((int(b), int(max_length - s)), dtype=bidirectional_mask.dtype, device=bidirectional_mask.device)
90
+ bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
91
+ bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
92
+ for attn_module in attn_modules:
93
+ attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)
94
+ output = call_og_forward()
95
+ for attn_module in attn_modules:
96
+ attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
97
+ return output
98
+
99
+ def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
100
+ """Wraps original generate to enable PrefixLM attention."""
101
+ attn_modules = _get_attn_modules(model)
102
+ for attn_module in attn_modules:
103
+ attn_module.bias.data[:] = 1
104
+ output = self._original_generate(*args, **kwargs)
105
+ for attn_module in attn_modules:
106
+ attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
107
+ return output
108
+ setattr(model, 'forward', MethodType(forward, model))
109
+ setattr(model, 'generate', MethodType(generate, model))
110
+ setattr(model, '_prefix_lm_converted', True)
111
+ return model
112
+
113
+ def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
114
+ """Converts a BLOOM Causal LM to a Prefix LM.
115
+
116
+ Supported HuggingFace model classes:
117
+ - `BloomForCausalLM`
118
+
119
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
120
+ """
121
+ if hasattr(model, '_prefix_lm_converted'):
122
+ return model
123
+ assert isinstance(model, BloomForCausalLM)
124
+ assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'
125
+
126
+ def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:
127
+ combined_attention_mask = None
128
+ device = attention_mask.device
129
+ (_, src_length) = input_shape
130
+ if src_length > 1:
131
+ combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)
132
+ if bidirectional_mask is not None:
133
+ assert attention_mask.shape == bidirectional_mask.shape
134
+ expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)
135
+ combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)
136
+ expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
137
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
138
+ return combined_attention_mask
139
+
140
+ def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
141
+ num_heads = self.config.n_head
142
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
143
+ base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)
144
+ powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
145
+ slopes = torch.pow(base, powers)
146
+ if closest_power_of_2 != num_heads:
147
+ extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)
148
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
149
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
150
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
151
+ qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
152
+ ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
153
+ diffs = qa - ka + key_length - query_length
154
+ diffs = -diffs.abs()
155
+ alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)
156
+ alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)
157
+ return alibi.to(dtype)
158
+ KeyValueT = Tuple[torch.Tensor, torch.Tensor]
159
+
160
+ def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
161
+ if deprecated_arguments.pop('position_ids', False) is not False:
162
+ warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)
163
+ if len(deprecated_arguments) > 0:
164
+ raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
165
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
166
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
167
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
168
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
169
+ if input_ids is not None and inputs_embeds is not None:
170
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
171
+ elif input_ids is not None:
172
+ (batch_size, seq_length) = input_ids.shape
173
+ elif inputs_embeds is not None:
174
+ (batch_size, seq_length, _) = inputs_embeds.shape
175
+ else:
176
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
177
+ if past_key_values is None:
178
+ past_key_values = tuple([None] * len(self.h))
179
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
180
+ if inputs_embeds is None:
181
+ inputs_embeds = self.word_embeddings(input_ids)
182
+ hidden_states = self.word_embeddings_layernorm(inputs_embeds)
183
+ presents = () if use_cache else None
184
+ all_self_attentions = () if output_attentions else None
185
+ all_hidden_states = () if output_hidden_states else None
186
+ seq_length_with_past = seq_length
187
+ past_key_values_length = 0
188
+ if past_key_values[0] is not None:
189
+ tmp = past_key_values[0][0]
190
+ past_key_values_length = tmp.shape[2]
191
+ seq_length_with_past = seq_length_with_past + past_key_values_length
192
+ if attention_mask is None:
193
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
194
+ else:
195
+ attention_mask = attention_mask.to(hidden_states.device)
196
+ alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)
197
+ causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)
198
+ for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):
199
+ if output_hidden_states:
200
+ hst = (hidden_states,)
201
+ all_hidden_states = all_hidden_states + hst
202
+ if self.gradient_checkpointing and self.training:
203
+ if use_cache:
204
+ logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
205
+ use_cache = False
206
+
207
+ def create_custom_forward(module):
208
+
209
+ def custom_forward(*inputs):
210
+ return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
211
+ return custom_forward
212
+ outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])
213
+ else:
214
+ outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)
215
+ hidden_states = outputs[0]
216
+ if use_cache is True:
217
+ presents = presents + (outputs[1],)
218
+ if output_attentions:
219
+ oa = (outputs[2 if use_cache else 1],)
220
+ all_self_attentions = all_self_attentions + oa
221
+ hidden_states = self.ln_f(hidden_states)
222
+ if output_hidden_states:
223
+ hst = (hidden_states,)
224
+ all_hidden_states = all_hidden_states + hst
225
+ if not return_dict:
226
+ return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))
227
+ return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)
228
+ setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))
229
+ setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))
230
+ setattr(model.transformer, 'forward', MethodType(forward, model.transformer))
231
+ KeyValueT = Tuple[torch.Tensor, torch.Tensor]
232
+
233
+ def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
234
+ """Replacement forward method for BloomCausalLM."""
235
+ if deprecated_arguments.pop('position_ids', False) is not False:
236
+ warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)
237
+ if len(deprecated_arguments) > 0:
238
+ raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
239
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
240
+ transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
241
+ hidden_states = transformer_outputs[0]
242
+ lm_logits = self.lm_head(hidden_states)
243
+ loss = None
244
+ if labels is not None:
245
+ shift_logits = lm_logits[..., :-1, :].contiguous()
246
+ shift_labels = labels[..., 1:].contiguous()
247
+ (batch_size, seq_length, vocab_size) = shift_logits.shape
248
+ loss_fct = CrossEntropyLoss()
249
+ loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))
250
+ if not return_dict:
251
+ output = (lm_logits,) + transformer_outputs[1:]
252
+ return (loss,) + output if loss is not None else output
253
+ return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)
254
+
255
+ def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict:
256
+ if past:
257
+ input_ids = input_ids[:, -1].unsqueeze(-1)
258
+ bidirectional_mask = None
259
+ if past[0][0].shape[0] == input_ids.shape[0]:
260
+ past = self._convert_to_bloom_cache(past)
261
+ else:
262
+ bidirectional_mask = torch.ones_like(input_ids)
263
+ return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}
264
+ setattr(model, 'forward', MethodType(forward, model))
265
+ setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))
266
+ setattr(model, '_prefix_lm_converted', True)
267
+ return model
268
+
269
+ def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
270
+ """Converts an OPT Causal LM to a Prefix LM.
271
+
272
+ Supported HuggingFace model classes:
273
+ - `OPTForCausalLM`
274
+
275
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
276
+ """
277
+ if hasattr(model, '_prefix_lm_converted'):
278
+ return model
279
+ assert isinstance(model, OPTForCausalLM)
280
+ assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'
281
+ setattr(model, '_original_forward', getattr(model, 'forward'))
282
+ setattr(model, '_original_generate', getattr(model, 'generate'))
283
+ model.model.decoder.bidirectional_mask = None
284
+
285
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
286
+ combined_attention_mask = None
287
+ if input_shape[-1] > 1:
288
+ if self.bidirectional_mask == 'g':
289
+ (bsz, src_length) = input_shape
290
+ combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
291
+ else:
292
+ combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)
293
+ if self.bidirectional_mask is not None:
294
+ assert attention_mask.shape == self.bidirectional_mask.shape
295
+ expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
296
+ combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)
297
+ if attention_mask is not None:
298
+ expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
299
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
300
+ return combined_attention_mask
301
+ setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))
302
+
303
+ def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
304
+
305
+ def call_og_forward():
306
+ return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
307
+ if bidirectional_mask is None:
308
+ return call_og_forward()
309
+ self.model.decoder.bidirectional_mask = bidirectional_mask
310
+ try:
311
+ outputs = call_og_forward()
312
+ except:
313
+ self.model.decoder.bidirectional_mask = None
314
+ raise
315
+ self.model.decoder.bidirectional_mask = None
316
+ return outputs
317
+
318
+ def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):
319
+ """Wraps original generate to enable PrefixLM-style attention."""
320
+ self.model.decoder.bidirectional_mask = 'g'
321
+ try:
322
+ output = self._original_generate(*args, **kwargs)
323
+ except:
324
+ self.model.decoder.bidirectional_mask = None
325
+ raise
326
+ self.model.decoder.bidirectional_mask = None
327
+ return output
328
+ setattr(model, 'forward', MethodType(forward, model))
329
+ setattr(model, 'generate', MethodType(generate, model))
330
+ setattr(model, '_prefix_lm_converted', True)
331
+ return model
332
+ _SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
333
+ CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]
334
+
335
+ def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
336
+ """Converts a HuggingFace Causal LM to a Prefix LM.
337
+
338
+ Supported HuggingFace model classes:
339
+ - `GPT2LMHeadModel`
340
+ - `GPTNeoForCausalLM`
341
+ - `GPTNeoXForCausalLM`
342
+ - `GPTJForCausalLM`
343
+ - `BloomForCausalLM`
344
+ - `OPTForCausalLM`
345
+
346
+ Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
347
+ `generate` method and/or select underlying methods depending on the model class.
348
+
349
+ These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask".
350
+
351
+ Notes on training:
352
+ To actually train the converted model as a Prefix LM, training batches will need to indicate
353
+ the prefix/target structure by including `bidirectional_mask` as part of the batch inputs.
354
+
355
+ **This is not a standard input and requires custom layers either within or after your dataloader.**
356
+
357
+ In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels`
358
+ such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`.
359
+ That is, the prefix portion of the sequence should not generate any loss. Loss should only be
360
+ generated by the target portion of the sequence.
361
+
362
+ Notes on `GPTNeoForCausalLM`:
363
+ To simplify the implementation, "global" and "local" attention layers are handled differently.
364
+ For "global" layers, we handle conversion as described above. For "local" layers, which use a
365
+ causal attention mask within a restricted local window, we do not alter the masking.
366
+
367
+ Notes on `forward` method conversion:
368
+ After conversion, the `forward` method will handle a new input, `bidirectional_mask`,
369
+ which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions
370
+ belonging to the prefix (prefix tokens can attend to one another bidirectionally), and
371
+ 0 indicates token positions belonging to the target.
372
+
373
+ The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing
374
+ causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset
375
+ the causal masks before returning the result.
376
+
377
+ Notes on `generate` method conversion:
378
+ After conversion, the `generate` method will have the same signature but will internally
379
+ convert all causal masks to be purely bidirectional, call the original `generate` method, and
380
+ (where appropriate) reset the causal masks before returning the result.
381
+
382
+ This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token
383
+ "prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates
384
+ each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one
385
+ another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and
386
+ previously-generated tokens (also as expected in a Prefix LM).
387
+
388
+ To preserve the API, the original methods are renamed to `_original_forward` and
389
+ `_original_generate`, and replaced with new `forward` and `generate` methods that wrap
390
+ them, respectively. Although implementation details vary by model class.
391
+ """
392
+ if isinstance(model, _SUPPORTED_GPT_MODELS):
393
+ return _convert_gpt_causal_lm_to_prefix_lm(model)
394
+ elif isinstance(model, BloomForCausalLM):
395
+ return _convert_bloom_causal_lm_to_prefix_lm(model)
396
+ elif isinstance(model, OPTForCausalLM):
397
+ return _convert_opt_causal_lm_to_prefix_lm(model)
398
+ else:
399
+ raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
400
+
401
+ def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):
402
+ """Attempts to add bidirectional_mask to batch if missing.
403
+
404
+ Raises:
405
+ KeyError if bidirectional_mask is missing and can't be inferred
406
+ """
407
+ if 'bidirectional_mask' not in batch:
408
+ if batch.get('mode', None) == 'icl_task':
409
+ batch['bidirectional_mask'] = batch['attention_mask'].clone()
410
+ for (i, continuation_indices) in enumerate(batch['continuation_indices']):
411
+ batch['bidirectional_mask'][i, continuation_indices] = 0
412
+ elif 'labels' in batch and 'attention_mask' in batch:
413
+ batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask'])
414
+ else:
415
+ raise KeyError('No bidirectional_mask in batch and not sure how to construct one.')
LLaVA/llava/model/language_model/mpt/meta_init_context.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+ @contextmanager
6
+ def init_empty_weights(include_buffers: bool=False):
7
+ """Meta initialization context manager.
8
+
9
+ A context manager under which models are initialized with all parameters
10
+ on the meta device, therefore creating an empty model. Useful when just
11
+ initializing the model would blow the available RAM.
12
+
13
+ Args:
14
+ include_buffers (`bool`, *optional*, defaults to `False`): Whether or
15
+ not to also put all buffers on the meta device while initializing.
16
+
17
+ Example:
18
+ ```python
19
+ import torch.nn as nn
20
+
21
+ # Initialize a model with 100 billions parameters in no time and without using any RAM.
22
+ with init_empty_weights():
23
+ tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
24
+ ```
25
+
26
+ <Tip warning={true}>
27
+
28
+ Any model created under this context manager has no weights. As such you can't do something like
29
+ `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
30
+
31
+ </Tip>
32
+ """
33
+ with init_on_device(torch.device('meta'), include_buffers=include_buffers) as f:
34
+ yield f
35
+
36
+ @contextmanager
37
+ def init_on_device(device: torch.device, include_buffers: bool=False):
38
+ """Device initialization context manager.
39
+
40
+ A context manager under which models are initialized with all parameters
41
+ on the specified device.
42
+
43
+ Args:
44
+ device (`torch.device`): Device to initialize all parameters on.
45
+ include_buffers (`bool`, *optional*, defaults to `False`): Whether or
46
+ not to also put all buffers on the meta device while initializing.
47
+
48
+ Example:
49
+ ```python
50
+ import torch.nn as nn
51
+
52
+ with init_on_device(device=torch.device("cuda")):
53
+ tst = nn.Liner(100, 100) # on `cuda` device
54
+ ```
55
+ """
56
+ old_register_parameter = nn.Module.register_parameter
57
+ if include_buffers:
58
+ old_register_buffer = nn.Module.register_buffer
59
+
60
+ def register_empty_parameter(module, name, param):
61
+ old_register_parameter(module, name, param)
62
+ if param is not None:
63
+ param_cls = type(module._parameters[name])
64
+ kwargs = module._parameters[name].__dict__
65
+ module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
66
+
67
+ def register_empty_buffer(module, name, buffer):
68
+ old_register_buffer(module, name, buffer)
69
+ if buffer is not None:
70
+ module._buffers[name] = module._buffers[name].to(device)
71
+ if include_buffers:
72
+ tensor_constructors_to_patch = {torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ['empty', 'zeros', 'ones', 'full']}
73
+ else:
74
+ tensor_constructors_to_patch = {}
75
+
76
+ def patch_tensor_constructor(fn):
77
+
78
+ def wrapper(*args, **kwargs):
79
+ kwargs['device'] = device
80
+ return fn(*args, **kwargs)
81
+ return wrapper
82
+ try:
83
+ nn.Module.register_parameter = register_empty_parameter
84
+ if include_buffers:
85
+ nn.Module.register_buffer = register_empty_buffer
86
+ for torch_function_name in tensor_constructors_to_patch.keys():
87
+ setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
88
+ yield
89
+ finally:
90
+ nn.Module.register_parameter = old_register_parameter
91
+ if include_buffers:
92
+ nn.Module.register_buffer = old_register_buffer
93
+ for (torch_function_name, old_torch_function) in tensor_constructors_to_patch.items():
94
+ setattr(torch, torch_function_name, old_torch_function)
LLaVA/llava/model/language_model/mpt/modeling_mpt.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A simple, flexible implementation of a GPT model.
2
+
3
+ Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
4
+ """
5
+ import math
6
+ import warnings
7
+ from typing import List, Optional, Tuple, Union
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
12
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
13
+ from .attention import attn_bias_shape, build_attn_bias
14
+ from .blocks import MPTBlock
15
+ from .custom_embedding import SharedEmbedding
16
+ from .norm import NORM_CLASS_REGISTRY
17
+ from .configuration_mpt import MPTConfig
18
+ from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
19
+ from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm
20
+ from .meta_init_context import init_empty_weights
21
+ from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_
22
+ try:
23
+ from .flash_attn_triton import flash_attn_func
24
+ except:
25
+ pass
26
+ Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
27
+
28
+ class MPTPreTrainedModel(PreTrainedModel):
29
+ config_class = MPTConfig
30
+ base_model_prefix = 'model'
31
+ _no_split_modules = ['MPTBlock']
32
+
33
+ class MPTModel(MPTPreTrainedModel):
34
+
35
+ def __init__(self, config: MPTConfig):
36
+ config._validate_config()
37
+ super().__init__(config)
38
+ self.attn_impl = config.attn_config['attn_impl']
39
+ self.prefix_lm = config.attn_config['prefix_lm']
40
+ self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
41
+ self.alibi = config.attn_config['alibi']
42
+ self.alibi_bias_max = config.attn_config['alibi_bias_max']
43
+ if config.init_device == 'mixed':
44
+ if dist.get_local_rank() == 0:
45
+ config.init_device = 'cpu'
46
+ else:
47
+ config.init_device = 'meta'
48
+ if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
49
+ norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())
50
+ raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')
51
+ norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
52
+ self.embedding_fraction = config.embedding_fraction
53
+ self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device)
54
+ if not self.alibi:
55
+ self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device)
56
+ self.emb_drop = nn.Dropout(config.emb_pdrop)
57
+ self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
58
+ self.norm_f = norm_class(config.d_model, device=config.init_device)
59
+ if config.init_device != 'meta':
60
+ print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.')
61
+ self.apply(self.param_init_fn)
62
+ self.is_causal = not self.prefix_lm
63
+ self._attn_bias_initialized = False
64
+ self.attn_bias = None
65
+ self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id)
66
+ if config.no_bias:
67
+ for module in self.modules():
68
+ if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
69
+ if config.verbose:
70
+ warnings.warn(f'Removing bias ({module.bias}) from {module}.')
71
+ module.register_parameter('bias', None)
72
+ if config.verbose and config.verbose > 2:
73
+ print(self)
74
+ if 'verbose' not in self.config.init_config:
75
+ self.config.init_config['verbose'] = self.config.verbose
76
+ if self.config.init_config['verbose'] > 1:
77
+ init_fn_name = self.config.init_config['name']
78
+ warnings.warn(f'Using {init_fn_name} initialization.')
79
+ self.gradient_checkpointing = False
80
+
81
+ def get_input_embeddings(self):
82
+ return self.wte
83
+
84
+ def set_input_embeddings(self, value):
85
+ self.wte = value
86
+
87
+ @torch.no_grad()
88
+ def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None):
89
+ if not self._attn_bias_initialized:
90
+ if self.attn_bias_shape:
91
+ self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
92
+ self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max)
93
+ self._attn_bias_initialized = True
94
+ if self.attn_impl == 'flash':
95
+ return (self.attn_bias, attention_mask)
96
+ if self.attn_bias is not None:
97
+ self.attn_bias = self.attn_bias.to(dtype=dtype, device=device)
98
+ attn_bias = self.attn_bias
99
+ if self.prefix_lm:
100
+ assert isinstance(attn_bias, torch.Tensor)
101
+ assert isinstance(prefix_mask, torch.Tensor)
102
+ attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
103
+ if self.attn_uses_sequence_id and sequence_id is not None:
104
+ assert isinstance(attn_bias, torch.Tensor)
105
+ attn_bias = self._apply_sequence_id(attn_bias, sequence_id)
106
+ if attention_mask is not None:
107
+ s_k = attention_mask.shape[-1]
108
+ if attn_bias is None:
109
+ attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype)
110
+ else:
111
+ _s_k = max(0, attn_bias.size(-1) - s_k)
112
+ attn_bias = attn_bias[:, :, :, _s_k:]
113
+ if prefix_mask is not None and attention_mask.shape != prefix_mask.shape:
114
+ raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
115
+ min_val = torch.finfo(attn_bias.dtype).min
116
+ attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
117
+ return (attn_bias, None)
118
+
119
+ def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor):
120
+ (s_k, s_q) = attn_bias.shape[-2:]
121
+ if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:
122
+ raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.')
123
+ seq_len = prefix_mask.shape[-1]
124
+ if seq_len > self.config.max_seq_len:
125
+ raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
126
+ attn_bias = attn_bias[..., :seq_len, :seq_len]
127
+ causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len)
128
+ prefix = prefix_mask.view(-1, 1, 1, seq_len)
129
+ cannot_attend = ~torch.logical_or(causal, prefix.bool())
130
+ min_val = torch.finfo(attn_bias.dtype).min
131
+ attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
132
+ return attn_bias
133
+
134
+ def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor):
135
+ seq_len = sequence_id.shape[-1]
136
+ if seq_len > self.config.max_seq_len:
137
+ raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
138
+ attn_bias = attn_bias[..., :seq_len, :seq_len]
139
+ cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
140
+ min_val = torch.finfo(attn_bias.dtype).min
141
+ attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
142
+ return attn_bias
143
+
144
+ def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None):
145
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
146
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
147
+ if attention_mask is not None:
148
+ attention_mask = attention_mask.bool()
149
+ if prefix_mask is not None:
150
+ prefix_mask = prefix_mask.bool()
151
+ if not return_dict:
152
+ raise NotImplementedError('return_dict False is not implemented yet for MPT')
153
+ if output_attentions:
154
+ if self.attn_impl != 'torch':
155
+ raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.')
156
+ if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training:
157
+ raise NotImplementedError('MPT does not support training with left padding.')
158
+ if self.prefix_lm and prefix_mask is None:
159
+ raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
160
+ if self.training:
161
+ if self.attn_uses_sequence_id and sequence_id is None:
162
+ raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
163
+ elif self.attn_uses_sequence_id is False and sequence_id is not None:
164
+ warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
165
+ if input_ids is not None:
166
+ S = input_ids.size(1)
167
+ assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
168
+ tok_emb = self.wte(input_ids)
169
+ else:
170
+ assert inputs_embeds is not None
171
+ assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.'
172
+ S = inputs_embeds.size(1)
173
+ tok_emb = inputs_embeds
174
+ if self.alibi:
175
+ x = tok_emb
176
+ else:
177
+ past_position = 0
178
+ if past_key_values is not None:
179
+ if len(past_key_values) != self.config.n_layers:
180
+ raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).')
181
+ past_position = past_key_values[0][0].size(1)
182
+ if self.attn_impl == 'torch':
183
+ past_position = past_key_values[0][0].size(3)
184
+ if S + past_position > self.config.max_seq_len:
185
+ raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')
186
+ pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0)
187
+ if attention_mask is not None:
188
+ pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
189
+ pos_emb = self.wpe(pos)
190
+ x = tok_emb + pos_emb
191
+ if self.embedding_fraction == 1:
192
+ x = self.emb_drop(x)
193
+ else:
194
+ x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction)
195
+ assert isinstance(self.emb_drop, nn.Module)
196
+ x = self.emb_drop(x_shrunk)
197
+ (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
198
+ if use_cache and past_key_values is None:
199
+ past_key_values = [() for _ in range(self.config.n_layers)]
200
+ all_hidden_states = () if output_hidden_states else None
201
+ all_self_attns = () if output_attentions else None
202
+ for (b_idx, block) in enumerate(self.blocks):
203
+ if output_hidden_states:
204
+ assert all_hidden_states is not None
205
+ all_hidden_states = all_hidden_states + (x,)
206
+ past_key_value = past_key_values[b_idx] if past_key_values is not None else None
207
+ if self.gradient_checkpointing and self.training:
208
+ (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal)
209
+ else:
210
+ (x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal)
211
+ if past_key_values is not None:
212
+ past_key_values[b_idx] = past_key_value
213
+ if output_attentions:
214
+ assert all_self_attns is not None
215
+ all_self_attns = all_self_attns + (attn_weights,)
216
+ x = self.norm_f(x)
217
+ if output_hidden_states:
218
+ assert all_hidden_states is not None
219
+ all_hidden_states = all_hidden_states + (x,)
220
+ return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns)
221
+
222
+ def param_init_fn(self, module):
223
+ init_fn_name = self.config.init_config['name']
224
+ MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
225
+
226
+ def fsdp_wrap_fn(self, module):
227
+ return isinstance(module, MPTBlock)
228
+
229
+ def activation_checkpointing_fn(self, module):
230
+ return isinstance(module, MPTBlock)
231
+
232
+ class MPTForCausalLM(MPTPreTrainedModel):
233
+
234
+ def __init__(self, config: MPTConfig):
235
+ super().__init__(config)
236
+ if not config.tie_word_embeddings:
237
+ raise ValueError('MPTForCausalLM only supports tied word embeddings')
238
+ print(f'Instantiating an MPTForCausalLM model from {__file__}')
239
+ self.transformer = MPTModel(config)
240
+ for child in self.transformer.children():
241
+ if isinstance(child, torch.nn.ModuleList):
242
+ continue
243
+ if isinstance(child, torch.nn.Module):
244
+ child._fsdp_wrap = True
245
+ self.logit_scale = None
246
+ if config.logit_scale is not None:
247
+ logit_scale = config.logit_scale
248
+ if isinstance(logit_scale, str):
249
+ if logit_scale == 'inv_sqrt_d_model':
250
+ logit_scale = 1 / math.sqrt(config.d_model)
251
+ else:
252
+ raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
253
+ self.logit_scale = logit_scale
254
+
255
+ def get_input_embeddings(self):
256
+ return self.transformer.wte
257
+
258
+ def set_input_embeddings(self, value):
259
+ self.transformer.wte = value
260
+
261
+ def get_output_embeddings(self):
262
+ return self.transformer.wte
263
+
264
+ def set_output_embeddings(self, new_embeddings):
265
+ self.transformer.wte = new_embeddings
266
+
267
+ def set_decoder(self, decoder):
268
+ self.transformer = decoder
269
+
270
+ def get_decoder(self):
271
+ return self.transformer
272
+
273
+ def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None):
274
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
275
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
276
+ if inputs_embeds is not None:
277
+ raise NotImplementedError('inputs_embeds has to be None (for hf/peft support).')
278
+ outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
279
+ logits = self.transformer.wte(outputs.last_hidden_state.to(self.transformer.wte.weight.device), True)
280
+ if self.logit_scale is not None:
281
+ if self.logit_scale == 0:
282
+ warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
283
+ logits *= self.logit_scale
284
+ loss = None
285
+ if labels is not None:
286
+ labels = torch.roll(labels, shifts=-1)
287
+ labels[:, -1] = -100
288
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))
289
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
290
+
291
+ def param_init_fn(self, module):
292
+ init_fn_name = self.config.init_config['name']
293
+ MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
294
+
295
+ def fsdp_wrap_fn(self, module):
296
+ return isinstance(module, MPTBlock)
297
+
298
+ def activation_checkpointing_fn(self, module):
299
+ return isinstance(module, MPTBlock)
300
+
301
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
302
+ if inputs_embeds is not None:
303
+ raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
304
+ attention_mask = kwargs['attention_mask'].bool()
305
+ if attention_mask[:, -1].sum() != attention_mask.shape[0]:
306
+ raise NotImplementedError('MPT does not support generation with right padding.')
307
+ if self.transformer.attn_uses_sequence_id and self.training:
308
+ sequence_id = torch.zeros_like(input_ids[:1])
309
+ else:
310
+ sequence_id = None
311
+ if past_key_values is not None:
312
+ input_ids = input_ids[:, -1].unsqueeze(-1)
313
+ if self.transformer.prefix_lm:
314
+ prefix_mask = torch.ones_like(attention_mask)
315
+ if kwargs.get('use_cache') == False:
316
+ raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
317
+ else:
318
+ prefix_mask = None
319
+ return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)}
320
+
321
+ @staticmethod
322
+ def _reorder_cache(past_key_values, beam_idx):
323
+ """Used by HuggingFace generate when using beam search with kv-caching.
324
+
325
+ See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133
326
+ for an example in transformers.
327
+ """
328
+ reordered_past = []
329
+ for layer_past in past_key_values:
330
+ reordered_past += [tuple((past_state.index_select(0, beam_idx) for past_state in layer_past))]
331
+ return reordered_past
LLaVA/llava/model/language_model/mpt/norm.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ def _cast_if_autocast_enabled(tensor):
4
+ if torch.is_autocast_enabled():
5
+ if tensor.device.type == 'cuda':
6
+ dtype = torch.get_autocast_gpu_dtype()
7
+ elif tensor.device.type == 'cpu':
8
+ dtype = torch.get_autocast_cpu_dtype()
9
+ else:
10
+ raise NotImplementedError()
11
+ return tensor.to(dtype=dtype)
12
+ return tensor
13
+
14
+ class LPLayerNorm(torch.nn.LayerNorm):
15
+
16
+ def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True, device=None, dtype=None):
17
+ super().__init__(normalized_shape=normalized_shape, eps=eps, elementwise_affine=elementwise_affine, device=device, dtype=dtype)
18
+
19
+ def forward(self, x):
20
+ module_device = x.device
21
+ downcast_x = _cast_if_autocast_enabled(x)
22
+ downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
23
+ downcast_bias = _cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
24
+ with torch.autocast(enabled=False, device_type=module_device.type):
25
+ return torch.nn.functional.layer_norm(downcast_x, self.normalized_shape, downcast_weight, downcast_bias, self.eps)
26
+
27
+ def rms_norm(x, weight=None, eps=1e-05):
28
+ output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
29
+ if weight is not None:
30
+ return output * weight
31
+ return output
32
+
33
+ class RMSNorm(torch.nn.Module):
34
+
35
+ def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
36
+ super().__init__()
37
+ self.eps = eps
38
+ if weight:
39
+ self.weight = torch.nn.Parameter(torch.ones(normalized_shape, dtype=dtype, device=device))
40
+ else:
41
+ self.register_parameter('weight', None)
42
+
43
+ def forward(self, x):
44
+ return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype)
45
+
46
+ class LPRMSNorm(RMSNorm):
47
+
48
+ def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
49
+ super().__init__(normalized_shape=normalized_shape, eps=eps, weight=weight, dtype=dtype, device=device)
50
+
51
+ def forward(self, x):
52
+ downcast_x = _cast_if_autocast_enabled(x)
53
+ downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
54
+ with torch.autocast(enabled=False, device_type=x.device.type):
55
+ return rms_norm(downcast_x, downcast_weight, self.eps).to(dtype=x.dtype)
56
+ NORM_CLASS_REGISTRY = {'layernorm': torch.nn.LayerNorm, 'low_precision_layernorm': LPLayerNorm, 'rmsnorm': RMSNorm, 'low_precision_rmsnorm': LPRMSNorm}
LLaVA/llava/model/language_model/mpt/param_init_fns.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import warnings
3
+ from collections.abc import Sequence
4
+ from functools import partial
5
+ from typing import Optional, Tuple, Union
6
+ import torch
7
+ from torch import nn
8
+ from .norm import NORM_CLASS_REGISTRY
9
+
10
+ def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs):
11
+ del kwargs
12
+ if verbose > 1:
13
+ warnings.warn(f"Initializing network using module's reset_parameters attribute")
14
+ if hasattr(module, 'reset_parameters'):
15
+ module.reset_parameters()
16
+
17
+ def fused_init_helper_(module: nn.Module, init_fn_):
18
+ _fused = getattr(module, '_fused', None)
19
+ if _fused is None:
20
+ raise RuntimeError(f'Internal logic error')
21
+ (dim, splits) = _fused
22
+ splits = (0, *splits, module.weight.size(dim))
23
+ for (s, e) in zip(splits[:-1], splits[1:]):
24
+ slice_indices = [slice(None)] * module.weight.ndim
25
+ slice_indices[dim] = slice(s, e)
26
+ init_fn_(module.weight[slice_indices])
27
+
28
+ def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
29
+ del kwargs
30
+ if verbose > 1:
31
+ warnings.warn(f'If model has bias parameters they are initialized to 0.')
32
+ init_div_is_residual = init_div_is_residual
33
+ if init_div_is_residual is False:
34
+ div_is_residual = 1.0
35
+ elif init_div_is_residual is True:
36
+ div_is_residual = math.sqrt(2 * n_layers)
37
+ elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int):
38
+ div_is_residual = init_div_is_residual
39
+ elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric():
40
+ div_is_residual = float(init_div_is_residual)
41
+ else:
42
+ div_is_residual = 1.0
43
+ raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}')
44
+ if init_div_is_residual is not False:
45
+ if verbose > 1:
46
+ warnings.warn(f'Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. ' + f'Set `init_div_is_residual: false` in init config to disable this.')
47
+ if isinstance(module, nn.Linear):
48
+ if hasattr(module, '_fused'):
49
+ fused_init_helper_(module, init_fn_)
50
+ else:
51
+ init_fn_(module.weight)
52
+ if module.bias is not None:
53
+ torch.nn.init.zeros_(module.bias)
54
+ if init_div_is_residual is not False and getattr(module, '_is_residual', False):
55
+ with torch.no_grad():
56
+ module.weight.div_(div_is_residual)
57
+ elif isinstance(module, nn.Embedding):
58
+ if emb_init_std is not None:
59
+ std = emb_init_std
60
+ if std == 0:
61
+ warnings.warn(f'Embedding layer initialized to 0.')
62
+ emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
63
+ if verbose > 1:
64
+ warnings.warn(f'Embedding layer initialized using normal distribution with mean=0 and std={std!r}.')
65
+ elif emb_init_uniform_lim is not None:
66
+ lim = emb_init_uniform_lim
67
+ if isinstance(lim, Sequence):
68
+ if len(lim) > 2:
69
+ raise ValueError(f'Uniform init requires a min and a max limit. User input: {lim}.')
70
+ if lim[0] == lim[1]:
71
+ warnings.warn(f'Embedding layer initialized to {lim[0]}.')
72
+ else:
73
+ if lim == 0:
74
+ warnings.warn(f'Embedding layer initialized to 0.')
75
+ lim = [-lim, lim]
76
+ (a, b) = lim
77
+ emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
78
+ if verbose > 1:
79
+ warnings.warn(f'Embedding layer initialized using uniform distribution in range {lim}.')
80
+ else:
81
+ emb_init_fn_ = init_fn_
82
+ emb_init_fn_(module.weight)
83
+ elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
84
+ if verbose > 1:
85
+ warnings.warn(f'Norm weights are set to 1. If norm layer has a bias it is initialized to 0.')
86
+ if hasattr(module, 'weight') and module.weight is not None:
87
+ torch.nn.init.ones_(module.weight)
88
+ if hasattr(module, 'bias') and module.bias is not None:
89
+ torch.nn.init.zeros_(module.bias)
90
+ elif isinstance(module, nn.MultiheadAttention):
91
+ if module._qkv_same_embed_dim:
92
+ assert module.in_proj_weight is not None
93
+ assert module.q_proj_weight is None and module.k_proj_weight is None and (module.v_proj_weight is None)
94
+ assert d_model is not None
95
+ _d = d_model
96
+ splits = (0, _d, 2 * _d, 3 * _d)
97
+ for (s, e) in zip(splits[:-1], splits[1:]):
98
+ init_fn_(module.in_proj_weight[s:e])
99
+ else:
100
+ assert module.q_proj_weight is not None and module.k_proj_weight is not None and (module.v_proj_weight is not None)
101
+ assert module.in_proj_weight is None
102
+ init_fn_(module.q_proj_weight)
103
+ init_fn_(module.k_proj_weight)
104
+ init_fn_(module.v_proj_weight)
105
+ if module.in_proj_bias is not None:
106
+ torch.nn.init.zeros_(module.in_proj_bias)
107
+ if module.bias_k is not None:
108
+ torch.nn.init.zeros_(module.bias_k)
109
+ if module.bias_v is not None:
110
+ torch.nn.init.zeros_(module.bias_v)
111
+ init_fn_(module.out_proj.weight)
112
+ if init_div_is_residual is not False and getattr(module.out_proj, '_is_residual', False):
113
+ with torch.no_grad():
114
+ module.out_proj.weight.div_(div_is_residual)
115
+ if module.out_proj.bias is not None:
116
+ torch.nn.init.zeros_(module.out_proj.bias)
117
+ else:
118
+ for _ in module.parameters(recurse=False):
119
+ raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.')
120
+
121
+ def _normal_init_(std, mean=0.0):
122
+ return partial(torch.nn.init.normal_, mean=mean, std=std)
123
+
124
+ def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
125
+ del kwargs
126
+ init_fn_ = _normal_init_(std=std)
127
+ if verbose > 1:
128
+ warnings.warn(f'Using torch.nn.init.normal_ init fn mean=0.0, std={std}')
129
+ generic_param_init_fn_(module=module, init_fn_=init_fn_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
130
+
131
+ def baseline_param_init_fn_(module: nn.Module, init_std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
132
+ del kwargs
133
+ if init_std is None:
134
+ raise ValueError("You must set model.init_config['init_std'] to a float value to use the default initialization scheme.")
135
+ _normal_param_init_fn_(module=module, std=init_std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
136
+
137
+ def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
138
+ del kwargs
139
+ std = math.sqrt(2 / (5 * d_model))
140
+ _normal_param_init_fn_(module=module, std=std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
141
+
142
+ def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
143
+ """From section 2.3.1 of GPT-NeoX-20B:
144
+
145
+ An Open-Source AutoregressiveLanguage Model — Black et. al. (2022)
146
+ see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151
147
+ and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
148
+ """
149
+ del kwargs
150
+ residual_div = n_layers / math.sqrt(10)
151
+ if verbose > 1:
152
+ warnings.warn(f'setting init_div_is_residual to {residual_div}')
153
+ small_param_init_fn_(module=module, d_model=d_model, n_layers=n_layers, init_div_is_residual=residual_div, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
154
+
155
+ def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
156
+ del kwargs
157
+ if verbose > 1:
158
+ warnings.warn(f'Using nn.init.kaiming_uniform_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
159
+ kaiming_uniform_ = partial(nn.init.kaiming_uniform_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
160
+ generic_param_init_fn_(module=module, init_fn_=kaiming_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
161
+
162
+ def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
163
+ del kwargs
164
+ if verbose > 1:
165
+ warnings.warn(f'Using nn.init.kaiming_normal_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
166
+ kaiming_normal_ = partial(torch.nn.init.kaiming_normal_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
167
+ generic_param_init_fn_(module=module, init_fn_=kaiming_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
168
+
169
+ def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
170
+ del kwargs
171
+ xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain)
172
+ if verbose > 1:
173
+ warnings.warn(f'Using torch.nn.init.xavier_uniform_ init fn with parameters: ' + f'gain={init_gain}')
174
+ generic_param_init_fn_(module=module, init_fn_=xavier_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
175
+
176
+ def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
177
+ xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain)
178
+ if verbose > 1:
179
+ warnings.warn(f'Using torch.nn.init.xavier_normal_ init fn with parameters: ' + f'gain={init_gain}')
180
+ generic_param_init_fn_(module=module, init_fn_=xavier_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
181
+ MODEL_INIT_REGISTRY = {'default_': torch_default_param_init_fn_, 'baseline_': baseline_param_init_fn_, 'kaiming_uniform_': kaiming_uniform_param_init_fn_, 'kaiming_normal_': kaiming_normal_param_init_fn_, 'neox_init_': neox_param_init_fn_, 'small_init_': small_param_init_fn_, 'xavier_uniform_': xavier_uniform_param_init_fn_, 'xavier_normal_': xavier_normal_param_init_fn_}
LLaVA/llava/model/llava_arch.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 abc import ABC, abstractmethod
17
+
18
+ import torch
19
+
20
+ from LLaVA.llava.model.multimodal_encoder.builder import build_vision_tower
21
+ from LLaVA.llava.model.multimodal_projector.builder import build_vision_projector
22
+
23
+ from ..constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
24
+
25
+
26
+ class LlavaMetaModel:
27
+
28
+ def __init__(self, config):
29
+ super(LlavaMetaModel, self).__init__(config)
30
+
31
+ if hasattr(config, "mm_vision_tower"):
32
+ self.vision_tower = build_vision_tower(config, delay_load=True)
33
+ self.mm_projector = build_vision_projector(config)
34
+
35
+ def get_vision_tower(self):
36
+ vision_tower = getattr(self, 'vision_tower', None)
37
+ if type(vision_tower) is list:
38
+ vision_tower = vision_tower[0]
39
+ return vision_tower
40
+
41
+ def initialize_vision_modules(self, model_args, fsdp=None):
42
+ vision_tower = model_args.vision_tower
43
+ mm_vision_select_layer = model_args.mm_vision_select_layer
44
+ mm_vision_select_feature = model_args.mm_vision_select_feature
45
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
46
+
47
+ self.config.mm_vision_tower = vision_tower
48
+
49
+ if self.get_vision_tower() is None:
50
+ vision_tower = build_vision_tower(model_args)
51
+
52
+ if fsdp is not None and len(fsdp) > 0:
53
+ self.vision_tower = [vision_tower]
54
+ else:
55
+ self.vision_tower = vision_tower
56
+ else:
57
+ if fsdp is not None and len(fsdp) > 0:
58
+ vision_tower = self.vision_tower[0]
59
+ else:
60
+ vision_tower = self.vision_tower
61
+ vision_tower.load_model()
62
+
63
+ self.config.use_mm_proj = True
64
+ self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
65
+ self.config.mm_hidden_size = vision_tower.hidden_size
66
+ self.config.mm_vision_select_layer = mm_vision_select_layer
67
+ self.config.mm_vision_select_feature = mm_vision_select_feature
68
+
69
+ if getattr(self, 'mm_projector', None) is None:
70
+ self.mm_projector = build_vision_projector(self.config)
71
+
72
+ if pretrain_mm_mlp_adapter is not None:
73
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
74
+ def get_w(weights, keyword):
75
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
76
+
77
+ self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
78
+
79
+
80
+ class LlavaMetaForCausalLM(ABC):
81
+
82
+ @abstractmethod
83
+ def get_model(self):
84
+ pass
85
+
86
+ def get_vision_tower(self):
87
+ return self.get_model().get_vision_tower()
88
+
89
+ def encode_images(self, images):
90
+ image_features = self.get_model().get_vision_tower()(images)
91
+ image_features = self.get_model().mm_projector(image_features)
92
+ return image_features
93
+
94
+ def prepare_inputs_labels_for_multimodal(
95
+ self, input_ids, attention_mask, past_key_values, labels, images
96
+ ):
97
+ vision_tower = self.get_vision_tower()
98
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
99
+ if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
100
+ attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
101
+ return input_ids, attention_mask, past_key_values, None, labels
102
+
103
+ if type(images) is list or images.ndim == 5:
104
+ concat_images = torch.cat([image for image in images], dim=0)
105
+ image_features = self.encode_images(concat_images)
106
+ split_sizes = [image.shape[0] for image in images]
107
+ image_features = torch.split(image_features, split_sizes, dim=0)
108
+ image_features = [x.flatten(0, 1) for x in image_features]
109
+ else:
110
+ image_features = self.encode_images(images)
111
+
112
+ new_input_embeds = []
113
+ new_labels = [] if labels is not None else None
114
+ cur_image_idx = 0
115
+ for batch_idx, cur_input_ids in enumerate(input_ids):
116
+ if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0:
117
+ # multimodal LLM, but the current sample is not multimodal
118
+ # FIXME: this is a hacky fix, for deepspeed zero3 to work
119
+ half_len = cur_input_ids.shape[0] // 2
120
+ cur_image_features = image_features[cur_image_idx]
121
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len])
122
+ cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:])
123
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0)
124
+ new_input_embeds.append(cur_input_embeds)
125
+ if labels is not None:
126
+ new_labels.append(labels[batch_idx])
127
+ cur_image_idx += 1
128
+ continue
129
+ image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
130
+ cur_new_input_embeds = []
131
+ if labels is not None:
132
+ cur_labels = labels[batch_idx]
133
+ cur_new_labels = []
134
+ assert cur_labels.shape == cur_input_ids.shape
135
+ while image_token_indices.numel() > 0:
136
+ cur_image_features = image_features[cur_image_idx]
137
+ image_token_start = image_token_indices[0]
138
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
139
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start-1]).detach())
140
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start-1:image_token_start]))
141
+ cur_new_input_embeds.append(cur_image_features)
142
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start+1:image_token_start+2]))
143
+ if labels is not None:
144
+ cur_new_labels.append(cur_labels[:image_token_start])
145
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
146
+ cur_new_labels.append(cur_labels[image_token_start:image_token_start+1])
147
+ cur_labels = cur_labels[image_token_start+2:]
148
+ else:
149
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start]))
150
+ cur_new_input_embeds.append(cur_image_features)
151
+ if labels is not None:
152
+ cur_new_labels.append(cur_labels[:image_token_start])
153
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
154
+ cur_labels = cur_labels[image_token_start+1:]
155
+ cur_image_idx += 1
156
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
157
+ cur_input_ids = cur_input_ids[image_token_start+2:]
158
+ else:
159
+ cur_input_ids = cur_input_ids[image_token_start+1:]
160
+ image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
161
+ if cur_input_ids.numel() > 0:
162
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
163
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids).detach())
164
+ else:
165
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
166
+ if labels is not None:
167
+ cur_new_labels.append(cur_labels)
168
+ cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds]
169
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
170
+ new_input_embeds.append(cur_new_input_embeds)
171
+ if labels is not None:
172
+ cur_new_labels = torch.cat(cur_new_labels, dim=0)
173
+ new_labels.append(cur_new_labels)
174
+
175
+ if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds):
176
+ max_len = max(x.shape[0] for x in new_input_embeds)
177
+
178
+ new_input_embeds_align = []
179
+ for cur_new_embed in new_input_embeds:
180
+ cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0)
181
+ new_input_embeds_align.append(cur_new_embed)
182
+ new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
183
+
184
+ if labels is not None:
185
+ new_labels_align = []
186
+ _new_labels = new_labels
187
+ for cur_new_label in new_labels:
188
+ cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0)
189
+ new_labels_align.append(cur_new_label)
190
+ new_labels = torch.stack(new_labels_align, dim=0)
191
+
192
+ if attention_mask is not None:
193
+ new_attention_mask = []
194
+ for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels):
195
+ new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device)
196
+ new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device)
197
+ cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0)
198
+ new_attention_mask.append(cur_new_attention_mask)
199
+ attention_mask = torch.stack(new_attention_mask, dim=0)
200
+ assert attention_mask.shape == new_labels.shape
201
+ else:
202
+ new_input_embeds = torch.stack(new_input_embeds, dim=0)
203
+ if labels is not None:
204
+ new_labels = torch.stack(new_labels, dim=0)
205
+
206
+ if attention_mask is not None:
207
+ new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device)
208
+ attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1)
209
+ assert attention_mask.shape == new_input_embeds.shape[:2]
210
+
211
+ return None, attention_mask, past_key_values, new_input_embeds, new_labels
212
+
213
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
214
+ if model_args.mm_use_im_patch_token:
215
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
216
+ self.resize_token_embeddings(len(tokenizer))
217
+
218
+ if model_args.mm_use_im_start_end:
219
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
220
+ self.resize_token_embeddings(len(tokenizer))
221
+
222
+ if num_new_tokens > 0:
223
+ input_embeddings = self.get_input_embeddings().weight.data
224
+ output_embeddings = self.get_output_embeddings().weight.data
225
+
226
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
227
+ dim=0, keepdim=True)
228
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
229
+ dim=0, keepdim=True)
230
+
231
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
232
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
233
+
234
+ if model_args.tune_mm_mlp_adapter:
235
+ for p in self.get_input_embeddings().parameters():
236
+ p.requires_grad = True
237
+ for p in self.get_output_embeddings().parameters():
238
+ p.requires_grad = False
239
+
240
+ if model_args.pretrain_mm_mlp_adapter:
241
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
242
+ embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
243
+ assert num_new_tokens == 2
244
+ if input_embeddings.shape == embed_tokens_weight.shape:
245
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
246
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
247
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
248
+ else:
249
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
250
+ elif model_args.mm_use_im_patch_token:
251
+ if model_args.tune_mm_mlp_adapter:
252
+ for p in self.get_input_embeddings().parameters():
253
+ p.requires_grad = False
254
+ for p in self.get_output_embeddings().parameters():
255
+ p.requires_grad = False
LLaVA/llava/model/llava_search_arch.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ import torch
3
+
4
+ from LLaVA.llava.model.multimodal_encoder.builder import build_vision_tower
5
+ from LLaVA.llava.model.multimodal_projector.builder import build_vision_projector
6
+
7
+ from LLaVA.llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, OBJECT_TOKEN_INDEX
8
+
9
+
10
+ class LlavaSearchMetaModel:
11
+
12
+ def __init__(self, config):
13
+ super(LlavaSearchMetaModel, self).__init__(config)
14
+
15
+ if hasattr(config, "mm_vision_tower"):
16
+ self.vision_tower = build_vision_tower(config, delay_load=True)
17
+ self.mm_projector = build_vision_projector(config)
18
+ self.mm_projector_object = build_vision_projector(config, object_projector=True)
19
+
20
+ def get_vision_tower(self):
21
+ vision_tower = getattr(self, 'vision_tower', None)
22
+ if type(vision_tower) is list:
23
+ vision_tower = vision_tower[0]
24
+ return vision_tower
25
+
26
+ def initialize_vision_modules(self, model_args, fsdp=None):
27
+ vision_tower = model_args.vision_tower
28
+ mm_vision_select_layer = model_args.mm_vision_select_layer
29
+ mm_vision_select_feature = model_args.mm_vision_select_feature
30
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
31
+ pretrain_mm_perceiver_adapter = model_args.pretrain_mm_perceiver_adapter
32
+
33
+ self.config.mm_vision_tower = vision_tower
34
+
35
+ if self.get_vision_tower() is None:
36
+ vision_tower = build_vision_tower(model_args)
37
+
38
+ if fsdp is not None and len(fsdp) > 0:
39
+ self.vision_tower = [vision_tower]
40
+ else:
41
+ self.vision_tower = vision_tower
42
+ else:
43
+ if fsdp is not None and len(fsdp) > 0:
44
+ vision_tower = self.vision_tower[0]
45
+ else:
46
+ vision_tower = self.vision_tower
47
+ vision_tower.load_model()
48
+
49
+ self.config.use_mm_proj = True
50
+ self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
51
+ self.config.object_mm_projector_type = getattr(model_args, 'object_mm_projector_type', 'perceiver')
52
+ self.config.mm_hidden_size = vision_tower.hidden_size
53
+ self.config.mm_vision_select_layer = mm_vision_select_layer
54
+ self.config.mm_vision_select_feature = mm_vision_select_feature
55
+
56
+ if getattr(self, 'mm_projector', None) is None:
57
+ self.mm_projector = build_vision_projector(self.config)
58
+ self.mm_projector_object = build_vision_projector(self.config, object_projector=True)
59
+
60
+
61
+ if pretrain_mm_mlp_adapter is not None:
62
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
63
+ def get_w(weights, keyword):
64
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
65
+ self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
66
+
67
+ if pretrain_mm_perceiver_adapter is not None:
68
+ mm_projector_weights = torch.load(pretrain_mm_perceiver_adapter, map_location='cpu')
69
+ def get_w(weights, keyword):
70
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
71
+ self.mm_projector_object.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
72
+
73
+
74
+ class LlavaSearchMetaForCausalLM(ABC):
75
+
76
+ @abstractmethod
77
+ def get_model(self):
78
+ pass
79
+
80
+ def get_vision_tower(self):
81
+ return self.get_model().get_vision_tower()
82
+
83
+ def encode_images(self, images):
84
+ image_features = self.get_model().get_vision_tower()(images)
85
+ image_features_long = self.get_model().mm_projector(image_features)
86
+ image_features_short = self.get_model().mm_projector_object(image_features)
87
+ return image_features_long, image_features_short
88
+
89
+ def project_features(self, object_features):
90
+ object_features = self.get_model().get_vision_tower()(object_features)
91
+ image_features_long = self.get_model().mm_projector(object_features)
92
+ object_features_short = self.get_model().mm_projector_object(object_features)
93
+ return image_features_long, object_features_short
94
+
95
+ def prepare_inputs_labels_for_multimodal(
96
+ self, input_ids, attention_mask, past_key_values, labels, images, object_features, images_long=None, objects_long=None
97
+ ):
98
+ vision_tower = self.get_vision_tower()
99
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
100
+ if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
101
+ attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
102
+ return input_ids, attention_mask, past_key_values, None, labels
103
+ if type(images) is list or images.ndim == 5:
104
+ concat_images = torch.cat([image for image in images], dim=0)
105
+ image_features = self.encode_images(concat_images)
106
+ split_sizes = [image.shape[0] for image in images]
107
+ image_features = torch.split(image_features, split_sizes, dim=0)
108
+ image_features = [x.flatten(0, 1) for x in image_features]
109
+ else:
110
+ image_features_long, image_features_short = self.encode_images(images)
111
+
112
+ if object_features is not None and len(object_features) > 0:
113
+ projected_object_features_long, projected_object_features_short = self.project_features(object_features)
114
+
115
+ new_input_embeds = []
116
+ new_labels = [] if labels is not None else None
117
+ new_attention_mask = [] if attention_mask is not None else None
118
+ cur_image_idx = 0
119
+ cur_object_idx = 0
120
+ for batch_idx, cur_input_ids in enumerate(input_ids):
121
+ if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0:
122
+ # multimodal LLM, but the current sample is not multimodal
123
+ half_len = cur_input_ids.shape[0] // 2
124
+ cur_object_features = projected_object_features_short[cur_object_idx]
125
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len])
126
+ cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:])
127
+ cat_list = [cur_input_embeds_1, image_features_short[cur_image_idx][0:0], image_features_long[cur_image_idx][0:0]]
128
+ for _ in range(3):
129
+ cat_list.extend([projected_object_features_short[cur_object_idx][0:0], projected_object_features_long[cur_object_idx][0:0]])
130
+ cur_object_idx += 1
131
+ cat_list.append(cur_input_embeds_2)
132
+ cur_input_embeds = torch.cat(cat_list, dim=0)
133
+ new_input_embeds.append(cur_input_embeds)
134
+ if labels is not None:
135
+ new_labels.append(labels[batch_idx])
136
+ cur_image_idx += 1
137
+ new_attention_mask.append(attention_mask[batch_idx])
138
+ continue
139
+ image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
140
+ cur_new_input_embeds = []
141
+ if labels is not None:
142
+ cur_labels = labels[batch_idx]
143
+ cur_new_labels = []
144
+ assert cur_labels.shape == cur_input_ids.shape
145
+ if attention_mask is not None:
146
+ cur_attention_mask = attention_mask[batch_idx]
147
+ cur_new_attention_mask = []
148
+ assert cur_attention_mask.shape == cur_input_ids.shape
149
+ while image_token_indices.numel() > 0:
150
+ if images_long is None or images_long[cur_image_idx]:
151
+ cur_image_features = torch.cat([image_features_short[cur_image_idx][0:0], image_features_long[cur_image_idx]])
152
+ else:
153
+ cur_image_features = torch.cat([image_features_short[cur_image_idx], image_features_long[cur_image_idx][0:0]])
154
+ image_token_start = image_token_indices[0]
155
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
156
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start-1]).detach())
157
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start-1:image_token_start]))
158
+ cur_new_input_embeds.append(cur_image_features)
159
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start+1:image_token_start+2]))
160
+ if labels is not None:
161
+ cur_new_labels.append(cur_labels[:image_token_start])
162
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
163
+ cur_new_labels.append(cur_labels[image_token_start:image_token_start+1])
164
+ cur_labels = cur_labels[image_token_start+2:]
165
+ if attention_mask is not None:
166
+ cur_new_attention_mask.append(cur_attention_mask[:image_token_start])
167
+ if cur_attention_mask[image_token_start]:
168
+ cur_new_attention_mask.append(torch.full((cur_image_features.shape[0],), True, device=attention_mask.device, dtype=attention_mask.dtype))
169
+ else:
170
+ cur_new_attention_mask.append(torch.full((cur_image_features.shape[0],), False, device=attention_mask.device, dtype=attention_mask.dtype))
171
+ cur_new_attention_mask.append(cur_attention_mask[image_token_start:image_token_start+1])
172
+ cur_attention_mask = cur_attention_mask[image_token_start+2:]
173
+ else:
174
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start]))
175
+ cur_new_input_embeds.append(cur_image_features)
176
+ if labels is not None:
177
+ cur_new_labels.append(cur_labels[:image_token_start])
178
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
179
+ cur_labels = cur_labels[image_token_start+1:]
180
+ if attention_mask is not None:
181
+ cur_new_attention_mask.append(cur_attention_mask[:image_token_start])
182
+ if cur_attention_mask[image_token_start]:
183
+ cur_new_attention_mask.append(torch.full((cur_image_features.shape[0],), True, device=attention_mask.device, dtype=attention_mask.dtype))
184
+ else:
185
+ cur_new_attention_mask.append(torch.full((cur_image_features.shape[0],), False, device=attention_mask.device, dtype=attention_mask.dtype))
186
+ cur_attention_mask = cur_attention_mask[image_token_start+1:]
187
+ cur_image_idx += 1
188
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
189
+ cur_input_ids = cur_input_ids[image_token_start+2:]
190
+ else:
191
+ cur_input_ids = cur_input_ids[image_token_start+1:]
192
+ image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
193
+ object_token_indices = torch.where(cur_input_ids == OBJECT_TOKEN_INDEX)[0]
194
+ cur_object_num = object_token_indices.numel()
195
+ while object_token_indices.numel() > 0:
196
+ if objects_long is None or not objects_long[cur_object_idx]:
197
+ cur_object_features = torch.cat([projected_object_features_short[cur_object_idx], projected_object_features_long[cur_object_idx][0:0]])
198
+ else:
199
+ cur_object_features = torch.cat([projected_object_features_short[cur_object_idx][0:0],projected_object_features_long[cur_object_idx]])
200
+ object_token_start = object_token_indices[0]
201
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:object_token_start]))
202
+ cur_new_input_embeds.append(cur_object_features)
203
+ if labels is not None:
204
+ cur_new_labels.append(cur_labels[:object_token_start])
205
+ cur_new_labels.append(torch.full((cur_object_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
206
+ cur_labels = cur_labels[object_token_start+1:]
207
+ if attention_mask is not None:
208
+ cur_new_attention_mask.append(cur_attention_mask[:object_token_start])
209
+ if cur_attention_mask[object_token_start]:
210
+ cur_new_attention_mask.append(torch.full((cur_object_features.shape[0],), True, device=attention_mask.device, dtype=attention_mask.dtype))
211
+ else:
212
+ cur_new_attention_mask.append(torch.full((cur_object_features.shape[0],), False, device=attention_mask.device, dtype=attention_mask.dtype))
213
+ cur_attention_mask = cur_attention_mask[object_token_start+1:]
214
+ cur_object_idx += 1
215
+ cur_input_ids = cur_input_ids[object_token_start+1:]
216
+ object_token_indices = torch.where(cur_input_ids == OBJECT_TOKEN_INDEX)[0]
217
+
218
+ if cur_input_ids.numel() > 0:
219
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
220
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids).detach())
221
+ else:
222
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
223
+ if labels is not None:
224
+ cur_new_labels.append(cur_labels)
225
+ if attention_mask is not None:
226
+ cur_new_attention_mask.append(cur_attention_mask)
227
+ cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds]
228
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
229
+ new_input_embeds.append(cur_new_input_embeds)
230
+ if labels is not None:
231
+ cur_new_labels = torch.cat(cur_new_labels, dim=0)
232
+ new_labels.append(cur_new_labels)
233
+ if attention_mask is not None:
234
+ cur_new_attention_mask = torch.cat(cur_new_attention_mask, dim=0)
235
+ new_attention_mask.append(cur_new_attention_mask)
236
+
237
+ need_padding = False
238
+ for i in range(len(new_input_embeds)):
239
+ for j in range(i+1, len(new_input_embeds)):
240
+ if new_input_embeds[i].shape != new_input_embeds[j].shape:
241
+ need_padding = True
242
+ break
243
+ if need_padding:
244
+ break
245
+ if need_padding:
246
+ max_len = max(x.shape[0] for x in new_input_embeds)
247
+
248
+ new_input_embeds_align = []
249
+ for cur_new_embed in new_input_embeds:
250
+ cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0)
251
+ new_input_embeds_align.append(cur_new_embed)
252
+ new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
253
+
254
+ if labels is not None:
255
+ new_labels_align = []
256
+ for cur_new_label in new_labels:
257
+ cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0)
258
+ new_labels_align.append(cur_new_label)
259
+ new_labels = torch.stack(new_labels_align, dim=0)
260
+
261
+ if attention_mask is not None:
262
+ new_attention_mask_align = []
263
+ for cur_new_attention_mask in new_attention_mask:
264
+ new_attn_mask_pad_right = torch.full((max_len - cur_new_attention_mask.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device)
265
+ cur_new_attention_mask = torch.cat((cur_new_attention_mask, new_attn_mask_pad_right), dim=0)
266
+ new_attention_mask.append(cur_new_attention_mask)
267
+ attention_mask = torch.stack(new_attention_mask, dim=0)
268
+ assert attention_mask.shape == new_labels.shape
269
+
270
+ else:
271
+ new_input_embeds = torch.stack(new_input_embeds, dim=0)
272
+ if labels is not None:
273
+ new_labels = torch.stack(new_labels, dim=0)
274
+ if new_attention_mask is not None and len(new_attention_mask):
275
+ new_attention_mask = torch.stack(new_attention_mask, dim=0)
276
+ attention_mask = new_attention_mask
277
+ assert attention_mask.shape == new_input_embeds.shape[:2]
278
+
279
+ return None, attention_mask, past_key_values, new_input_embeds, new_labels
280
+
281
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
282
+ if model_args.mm_use_im_patch_token:
283
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
284
+ self.resize_token_embeddings(len(tokenizer))
285
+
286
+ if model_args.mm_use_im_start_end:
287
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
288
+ self.resize_token_embeddings(len(tokenizer))
289
+
290
+ if num_new_tokens > 0:
291
+ input_embeddings = self.get_input_embeddings().weight.data
292
+ output_embeddings = self.get_output_embeddings().weight.data
293
+
294
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
295
+ dim=0, keepdim=True)
296
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
297
+ dim=0, keepdim=True)
298
+
299
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
300
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
301
+
302
+ if model_args.tune_mm_mlp_adapter:
303
+ for p in self.get_input_embeddings().parameters():
304
+ p.requires_grad = True
305
+ for p in self.get_output_embeddings().parameters():
306
+ p.requires_grad = False
307
+
308
+ if model_args.pretrain_mm_mlp_adapter:
309
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
310
+ embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
311
+ assert num_new_tokens == 2
312
+ if input_embeddings.shape == embed_tokens_weight.shape:
313
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
314
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
315
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
316
+ else:
317
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
318
+ elif model_args.mm_use_im_patch_token:
319
+ if model_args.tune_mm_mlp_adapter:
320
+ for p in self.get_input_embeddings().parameters():
321
+ p.requires_grad = False
322
+ for p in self.get_output_embeddings().parameters():
323
+ p.requires_grad = False
LLaVA/llava/model/make_delta.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m llava.model.make_delta --base ~/model_weights/llama-7b --target ~/model_weights/llava-7b --delta ~/model_weights/llava-7b-delta --hub-repo-id liuhaotian/llava-7b-delta
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from tqdm import tqdm
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from LLaVA.llava.model.utils import auto_upgrade
11
+
12
+
13
+ def make_delta(base_model_path, target_model_path, delta_path, hub_repo_id):
14
+ print("Loading base model")
15
+ base = AutoModelForCausalLM.from_pretrained(
16
+ base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+
18
+ print("Loading target model")
19
+ auto_upgrade(target_model_path)
20
+ target = AutoModelForCausalLM.from_pretrained(target_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
21
+
22
+ print("Calculating delta")
23
+ for name, param in tqdm(target.state_dict().items(), desc="Calculating delta"):
24
+ if name not in base.state_dict():
25
+ assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
26
+ continue
27
+ if param.data.shape == base.state_dict()[name].shape:
28
+ param.data -= base.state_dict()[name]
29
+ else:
30
+ assert name in ['model.embed_tokens.weight', 'lm_head.weight'], f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
31
+ bparam = base.state_dict()[name]
32
+ param.data[:bparam.shape[0], :bparam.shape[1]] -= bparam
33
+
34
+ print("Saving delta")
35
+ if hub_repo_id:
36
+ kwargs = {"push_to_hub": True, "repo_id": hub_repo_id}
37
+ else:
38
+ kwargs = {}
39
+ target.save_pretrained(delta_path, **kwargs)
40
+ target_tokenizer = AutoTokenizer.from_pretrained(target_model_path)
41
+ target_tokenizer.save_pretrained(delta_path, **kwargs)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ parser = argparse.ArgumentParser()
46
+ parser.add_argument("--base-model-path", type=str, required=True)
47
+ parser.add_argument("--target-model-path", type=str, required=True)
48
+ parser.add_argument("--delta-path", type=str, required=True)
49
+ parser.add_argument("--hub-repo-id", type=str, default=None)
50
+ args = parser.parse_args()
51
+
52
+ make_delta(args.base_model_path, args.target_model_path, args.delta_path, args.hub_repo_id)
LLaVA/llava/model/multimodal_encoder/builder.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .clip_encoder import CLIPVisionTower
3
+
4
+
5
+ def build_vision_tower(vision_tower_cfg, **kwargs):
6
+ vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))
7
+ is_absolute_path_exists = os.path.exists(vision_tower)
8
+ if is_absolute_path_exists or vision_tower.startswith("openai") or vision_tower.startswith("laion"):
9
+ return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
10
+
11
+ raise ValueError(f'Unknown vision tower: {vision_tower}')
LLaVA/llava/model/multimodal_encoder/clip_encoder.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
5
+
6
+
7
+ class CLIPVisionTower(nn.Module):
8
+ def __init__(self, vision_tower, args, delay_load=False):
9
+ super().__init__()
10
+
11
+ self.is_loaded = False
12
+
13
+ self.vision_tower_name = vision_tower
14
+ self.select_layer = args.mm_vision_select_layer
15
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
16
+
17
+ if not delay_load:
18
+ self.load_model()
19
+ else:
20
+ self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
21
+
22
+ def load_model(self):
23
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
24
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
25
+ self.vision_tower.requires_grad_(False)
26
+
27
+ self.is_loaded = True
28
+
29
+ def feature_select(self, image_forward_outs):
30
+ image_features = image_forward_outs.hidden_states[self.select_layer]
31
+ if self.select_feature == 'patch':
32
+ image_features = image_features[:, 1:]
33
+ elif self.select_feature == 'cls_patch':
34
+ image_features = image_features
35
+ else:
36
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
37
+ return image_features
38
+
39
+ @torch.no_grad()
40
+ def forward(self, images):
41
+ if type(images) is list:
42
+ image_features = []
43
+ for image in images:
44
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
45
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
46
+ image_features.append(image_feature)
47
+ else:
48
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
49
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
50
+
51
+ return image_features
52
+
53
+ @property
54
+ def dummy_feature(self):
55
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
56
+
57
+ @property
58
+ def dtype(self):
59
+ return self.vision_tower.dtype
60
+
61
+ @property
62
+ def device(self):
63
+ return self.vision_tower.device
64
+
65
+ @property
66
+ def config(self):
67
+ if self.is_loaded:
68
+ return self.vision_tower.config
69
+ else:
70
+ return self.cfg_only
71
+
72
+ @property
73
+ def hidden_size(self):
74
+ return self.config.hidden_size
75
+
76
+ @property
77
+ def num_patches(self):
78
+ return (self.config.image_size // self.config.patch_size) ** 2
LLaVA/llava/model/multimodal_projector/builder.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import re
3
+ from .perceiver import PerceiverResampler
4
+
5
+
6
+ class IdentityMap(nn.Module):
7
+ def __init__(self):
8
+ super().__init__()
9
+
10
+ def forward(self, x, *args, **kwargs):
11
+ return x
12
+
13
+ @property
14
+ def config(self):
15
+ return {"mm_projector_type": 'identity'}
16
+
17
+
18
+ class SimpleResBlock(nn.Module):
19
+ def __init__(self, channels):
20
+ super().__init__()
21
+ self.pre_norm = nn.LayerNorm(channels)
22
+
23
+ self.proj = nn.Sequential(
24
+ nn.Linear(channels, channels),
25
+ nn.GELU(),
26
+ nn.Linear(channels, channels)
27
+ )
28
+ def forward(self, x):
29
+ x = self.pre_norm(x)
30
+ return x + self.proj(x)
31
+
32
+
33
+ def build_vision_projector(config, object_projector=False, delay_load=False, **kwargs):
34
+ if not object_projector:
35
+ projector_type = getattr(config, 'mm_projector_type', 'linear')
36
+ else:
37
+ projector_type = getattr(config, 'object_mm_projector_type', 'perceiver')
38
+
39
+ if projector_type == 'linear':
40
+ return nn.Linear(config.mm_hidden_size, config.hidden_size)
41
+
42
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
43
+ if mlp_gelu_match:
44
+ mlp_depth = int(mlp_gelu_match.group(1))
45
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
46
+ for _ in range(1, mlp_depth):
47
+ modules.append(nn.GELU())
48
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
49
+ return nn.Sequential(*modules)
50
+
51
+ if projector_type == 'identity':
52
+ return IdentityMap()
53
+
54
+ if projector_type == "perceiver":
55
+ return nn.Sequential(
56
+ nn.LayerNorm(config.mm_hidden_size),
57
+ PerceiverResampler(
58
+ dim = config.mm_hidden_size,
59
+ dim_head = 96,
60
+ depth = 6,
61
+ heads = 16,
62
+ num_latents = 32,
63
+ num_media_embeds = 1
64
+ ),
65
+ nn.Linear(
66
+ config.mm_hidden_size, config.hidden_size
67
+ )
68
+ )
69
+
70
+ raise ValueError(f'Unknown projector type: {projector_type}')
LLaVA/llava/model/multimodal_projector/perceiver.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copied from
3
+ https://github.com/lucidrains/flamingo-pytorch/blob/main/flamingo_pytorch/flamingo_pytorch.py
4
+ """
5
+
6
+ import torch
7
+ from torch import nn, einsum
8
+ import torch.nn.functional as F
9
+
10
+ from einops import rearrange, repeat
11
+ from einops_exts import rearrange_many, repeat_many
12
+
13
+ def exists(val):
14
+ return val is not None
15
+
16
+ def FeedForward(dim, mult = 4):
17
+ inner_dim = int(dim * mult)
18
+ return nn.Sequential(
19
+ nn.LayerNorm(dim),
20
+ nn.Linear(dim, inner_dim, bias = False),
21
+ nn.GELU(),
22
+ nn.Linear(inner_dim, dim, bias = False)
23
+ )
24
+
25
+ class PerceiverAttention(nn.Module):
26
+ def __init__(
27
+ self,
28
+ *,
29
+ dim,
30
+ dim_head = 64,
31
+ heads = 8
32
+ ):
33
+ super().__init__()
34
+ self.scale = dim_head ** -0.5
35
+ self.heads = heads
36
+ inner_dim = dim_head * heads
37
+
38
+ self.norm_media = nn.LayerNorm(dim)
39
+ self.norm_latents = nn.LayerNorm(dim)
40
+
41
+ self.to_q = nn.Linear(dim, inner_dim, bias = False)
42
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias = False)
43
+ self.to_out = nn.Linear(inner_dim, dim, bias = False)
44
+
45
+ def forward(self, x, latents):
46
+ """
47
+ einstein notation
48
+ b - batch
49
+ t - time
50
+ n - sequence
51
+ d - dimension
52
+ """
53
+ x = self.norm_media(x)
54
+ latents = self.norm_latents(latents)
55
+
56
+ b, m, h = *x.shape[:2], self.heads
57
+
58
+ q = self.to_q(latents)
59
+
60
+ # the paper differs from Perceiver in which they also concat the key / values derived from the latents to be attended to
61
+ kv_input = torch.cat((x, latents), dim = -2)
62
+ k, v = self.to_kv(kv_input).chunk(2, dim = -1)
63
+
64
+ q, k, v = rearrange_many((q, k, v), 'b t n (h d) -> b h t n d', h = h)
65
+
66
+ q = q * self.scale
67
+
68
+ # attention
69
+
70
+ sim = einsum('... i d, ... j d -> ... i j', q, k)
71
+
72
+ sim = sim - sim.amax(dim = -1, keepdim = True).detach()
73
+ attn = sim.softmax(dim = -1)
74
+
75
+ out = einsum('... i j, ... j d -> ... i d', attn, v)
76
+ out = rearrange(out, 'b h t n d -> b t n (h d)', h = h)
77
+ return self.to_out(out)
78
+
79
+ class PerceiverResampler(nn.Module):
80
+ def __init__(
81
+ self,
82
+ *,
83
+ dim,
84
+ depth,
85
+ dim_head = 64,
86
+ heads = 8,
87
+ num_latents = 64,
88
+ num_media_embeds = 4,
89
+ ff_mult = 4
90
+ ):
91
+ super().__init__()
92
+ self.latents = nn.Parameter(torch.randn(num_latents, dim))
93
+ self.media_pos_emb = nn.Parameter(torch.randn(num_media_embeds, 1, dim))
94
+
95
+ self.layers = nn.ModuleList([])
96
+ for _ in range(depth):
97
+ self.layers.append(nn.ModuleList([
98
+ PerceiverAttention(dim = dim, dim_head = dim_head, heads = heads),
99
+ FeedForward(dim = dim, mult = ff_mult)
100
+ ]))
101
+
102
+ self.norm = nn.LayerNorm(dim)
103
+
104
+ def forward(self, x):
105
+ if x.ndim == 3:
106
+ x = rearrange(x, 'b n d -> b 1 n d')
107
+
108
+ times = x.shape[1]
109
+ x = x + self.media_pos_emb[:times]
110
+
111
+ latents = repeat(self.latents, 'n d -> b m n d', b = x.shape[0], m = x.shape[1])
112
+
113
+ for attn, ff in self.layers:
114
+ latents = attn(x, latents) + latents
115
+ latents = ff(latents) + latents
116
+
117
+ res = self.norm(latents)
118
+
119
+ if res.ndim == 4:
120
+ res = res.squeeze(1)
121
+
122
+ return res
LLaVA/llava/model/utils.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoConfig
2
+
3
+
4
+ def auto_upgrade(config):
5
+ cfg = AutoConfig.from_pretrained(config)
6
+ if 'llava' in config and 'llava' not in cfg.model_type:
7
+ assert cfg.model_type == 'llama'
8
+ print("You are using newer LLaVA code base, while the checkpoint of v0 is from older code base.")
9
+ print("You must upgrade the checkpoint to the new code base (this can be done automatically).")
10
+ confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]")
11
+ if confirm.lower() in ["y", "yes"]:
12
+ print("Upgrading checkpoint...")
13
+ assert len(cfg.architectures) == 1
14
+ setattr(cfg.__class__, "model_type", "llava")
15
+ cfg.architectures[0] = 'LlavaLlamaForCausalLM'
16
+ cfg.save_pretrained(config)
17
+ print("Checkpoint upgraded.")
18
+ else:
19
+ print("Checkpoint upgrade aborted.")
20
+ exit(1)
LLaVA/llava/train/__init__.py ADDED
File without changes
LLaVA/llava/train/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (161 Bytes). View file
 
LLaVA/llava/train/__pycache__/llama_flash_attn_monkey_patch.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
LLaVA/llava/train/__pycache__/llava_trainer.cpython-310.pyc ADDED
Binary file (8.36 kB). View file
 
LLaVA/llava/train/__pycache__/train.cpython-310.pyc ADDED
Binary file (26.8 kB). View file
 
LLaVA/llava/train/__pycache__/train_search.cpython-310.pyc ADDED
Binary file (31.4 kB). View file
 
LLaVA/llava/train/llama_flash_attn_monkey_patch.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple
2
+ import warnings
3
+
4
+ import torch
5
+
6
+ import transformers
7
+ from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv
8
+
9
+ try:
10
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func
11
+ except ImportError:
12
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
13
+ from flash_attn.bert_padding import unpad_input, pad_input
14
+
15
+
16
+ def forward(
17
+ self,
18
+ hidden_states: torch.Tensor,
19
+ attention_mask: Optional[torch.Tensor] = None,
20
+ position_ids: Optional[torch.Tensor] = None,
21
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
22
+ output_attentions: bool = False,
23
+ use_cache: bool = False,
24
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
25
+ if output_attentions:
26
+ warnings.warn(
27
+ "Output attentions is not supported for patched `LlamaAttention`, returning `None` instead."
28
+ )
29
+
30
+ bsz, q_len, _ = hidden_states.size()
31
+
32
+ query_states = (
33
+ self.q_proj(hidden_states)
34
+ .view(bsz, q_len, self.num_heads, self.head_dim)
35
+ .transpose(1, 2)
36
+ )
37
+ key_states = (
38
+ self.k_proj(hidden_states)
39
+ .view(bsz, q_len, self.num_key_value_heads, self.head_dim)
40
+ .transpose(1, 2)
41
+ )
42
+ value_states = (
43
+ self.v_proj(hidden_states)
44
+ .view(bsz, q_len, self.num_key_value_heads, self.head_dim)
45
+ .transpose(1, 2)
46
+ ) # shape: (b, num_heads, s, head_dim)
47
+
48
+ kv_seq_len = key_states.shape[-2]
49
+ if past_key_value is not None:
50
+ kv_seq_len += past_key_value[0].shape[-2]
51
+
52
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
53
+ query_states, key_states = apply_rotary_pos_emb(
54
+ query_states, key_states, cos, sin, position_ids
55
+ )
56
+
57
+ if past_key_value is not None:
58
+ # reuse k, v
59
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
60
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
61
+
62
+ past_key_value = (key_states, value_states) if use_cache else None
63
+
64
+ # repeat k/v heads if n_kv_heads < n_heads
65
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
66
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
67
+
68
+ # Transform the data into the format required by flash attention
69
+ qkv = torch.stack([query_states, key_states, value_states], dim=2)
70
+ qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim]
71
+ key_padding_mask = attention_mask
72
+
73
+ if key_padding_mask is None:
74
+ qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim)
75
+ cu_q_lens = torch.arange(
76
+ 0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device
77
+ )
78
+ max_s = q_len
79
+ output = flash_attn_unpadded_qkvpacked_func(
80
+ qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
81
+ )
82
+ output = output.view(bsz, q_len, -1)
83
+ else:
84
+ qkv = qkv.reshape(bsz, q_len, -1)
85
+ qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask)
86
+ qkv = qkv.view(-1, 3, self.num_heads, self.head_dim)
87
+ output_unpad = flash_attn_unpadded_qkvpacked_func(
88
+ qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
89
+ )
90
+ output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim)
91
+ output = pad_input(output_unpad, indices, bsz, q_len)
92
+
93
+ return self.o_proj(output), None, past_key_value
94
+
95
+
96
+ # Disable the transformation of the attention mask in LlamaModel as the flash attention
97
+ # requires the attention mask to be the same as the key_padding_mask
98
+ def _prepare_decoder_attention_mask(
99
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
100
+ ):
101
+ # [bsz, seq_len]
102
+ return attention_mask
103
+
104
+
105
+ def replace_llama_attn_with_flash_attn():
106
+ cuda_major, cuda_minor = torch.cuda.get_device_capability()
107
+ if cuda_major < 8:
108
+ warnings.warn(
109
+ "Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward."
110
+ "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593"
111
+ )
112
+ transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = (
113
+ _prepare_decoder_attention_mask
114
+ )
115
+ transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
LLaVA/llava/train/llava_trainer.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+
4
+ from torch.utils.data import Sampler
5
+
6
+ from transformers import Trainer
7
+ from transformers.trainer import (
8
+ has_length,
9
+ )
10
+ from typing import List, Optional
11
+
12
+
13
+ def maybe_zero_3(param, ignore_status=False, name=None):
14
+ from deepspeed import zero
15
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
16
+ if hasattr(param, "ds_id"):
17
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
18
+ if not ignore_status:
19
+ print(name, 'no ignore status')
20
+ with zero.GatheredParameters([param]):
21
+ param = param.data.detach().cpu().clone()
22
+ else:
23
+ param = param.detach().cpu().clone()
24
+ return param
25
+
26
+
27
+ def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
28
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
29
+ to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()}
30
+ return to_return
31
+
32
+
33
+ def split_to_even_chunks(indices, lengths, num_chunks):
34
+ """
35
+ Split a list of indices into `chunks` chunks of roughly equal lengths.
36
+ """
37
+
38
+ if len(indices) % num_chunks != 0:
39
+ return [indices[i::num_chunks] for i in range(num_chunks)]
40
+
41
+ num_indices_per_chunk = len(indices) // num_chunks
42
+
43
+ chunks = [[] for _ in range(num_chunks)]
44
+ chunks_lengths = [0 for _ in range(num_chunks)]
45
+ for index in indices:
46
+ shortest_chunk = chunks_lengths.index(min(chunks_lengths))
47
+ chunks[shortest_chunk].append(index)
48
+ chunks_lengths[shortest_chunk] += lengths[index]
49
+ if len(chunks[shortest_chunk]) == num_indices_per_chunk:
50
+ chunks_lengths[shortest_chunk] = float("inf")
51
+
52
+ return chunks
53
+
54
+
55
+ def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None):
56
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
57
+ assert all(l != 0 for l in lengths), "Should not have zero length."
58
+ mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
59
+ lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
60
+
61
+ assert len(mm_indices) > 0, "Should have at least one multimodal sample."
62
+ assert len(lang_indices) > 0, "Should have at least one language sample."
63
+
64
+ mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)]
65
+ lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)]
66
+ megabatch_size = world_size * batch_size
67
+ mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
68
+ lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
69
+
70
+ last_mm = mm_megabatches[-1]
71
+ last_lang = lang_megabatches[-1]
72
+ additional_batch = last_mm + last_lang
73
+ megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
74
+ megabatch_indices = torch.randperm(len(megabatches), generator=generator)
75
+ megabatches = [megabatches[i] for i in megabatch_indices]
76
+
77
+ if len(additional_batch) >= megabatch_size:
78
+ megabatches = [additional_batch[:megabatch_size]] + megabatches
79
+ additional_batch = additional_batch[megabatch_size:]
80
+
81
+ if len(additional_batch) > 0:
82
+ megabatches.append(additional_batch)
83
+
84
+ return [i for megabatch in megabatches for i in megabatch]
85
+
86
+
87
+ def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True):
88
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
89
+ indices = torch.randperm(len(lengths), generator=generator)
90
+ megabatch_size = world_size * batch_size
91
+ megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
92
+ megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
93
+ megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
94
+
95
+ return [i for megabatch in megabatches for batch in megabatch for i in batch]
96
+
97
+
98
+ class LengthGroupedSampler(Sampler):
99
+ r"""
100
+ Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
101
+ keeping a bit of randomness.
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ batch_size: int,
107
+ world_size: int,
108
+ lengths: Optional[List[int]] = None,
109
+ generator=None,
110
+ group_by_modality: bool = False,
111
+ ):
112
+ if lengths is None:
113
+ raise ValueError("Lengths must be provided.")
114
+
115
+ self.batch_size = batch_size
116
+ self.world_size = world_size
117
+ self.lengths = lengths
118
+ self.generator = generator
119
+ self.group_by_modality = group_by_modality
120
+
121
+ def __len__(self):
122
+ return len(self.lengths)
123
+
124
+ def __iter__(self):
125
+ if self.group_by_modality:
126
+ indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
127
+ else:
128
+ indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
129
+ return iter(indices)
130
+
131
+
132
+ class LLaVATrainer(Trainer):
133
+
134
+ def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
135
+ if self.train_dataset is None or not has_length(self.train_dataset):
136
+ return None
137
+
138
+ if self.args.group_by_modality_length:
139
+ lengths = self.train_dataset.modality_lengths
140
+ return LengthGroupedSampler(
141
+ # self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
142
+ self.args.train_batch_size,
143
+ world_size=self.args.world_size,
144
+ lengths=lengths,
145
+ group_by_modality=True,
146
+ )
147
+ else:
148
+ return super()._get_train_sampler()
149
+
150
+ def _save_checkpoint(self, model, trial, metrics=None):
151
+ if getattr(self.args, 'tune_mm_mlp_adapter', False):
152
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
153
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
154
+
155
+ run_dir = self._get_output_dir(trial=trial)
156
+ output_dir = os.path.join(run_dir, checkpoint_folder)
157
+
158
+ # Only save Adapter
159
+ keys_to_match = ['mm_projector', 'vision_resampler']
160
+ if getattr(self.args, "use_im_start_end", False):
161
+ keys_to_match.extend(['embed_tokens', 'embed_in'])
162
+
163
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
164
+
165
+ if self.args.local_rank == 0 or self.args.local_rank == -1:
166
+ self.model.config.save_pretrained(output_dir)
167
+ torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
168
+ else:
169
+ super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics)
170
+
171
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
172
+ if getattr(self.args, 'tune_mm_mlp_adapter', False):
173
+ pass
174
+ else:
175
+ super(LLaVATrainer, self)._save(output_dir, state_dict)
LLaVA/llava/train/train.py ADDED
@@ -0,0 +1,951 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
2
+ # Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
3
+ # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ import copy
19
+ from dataclasses import dataclass, field
20
+ import json
21
+ import logging
22
+ import pathlib
23
+ from typing import Dict, Optional, Sequence, List
24
+
25
+ import torch
26
+
27
+ import transformers
28
+
29
+ from LLaVA.llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_OBJECT_TOKEN,OBJECT_TOKEN_INDEX
30
+ from torch.utils.data import Dataset
31
+ from LLaVA.llava.train.llava_trainer import LLaVATrainer
32
+
33
+ import LLaVA.llava.conversation as conversation_lib
34
+ from LLaVA.llava.model import *
35
+ from LLaVA.llava.mm_utils import tokenizer_image_token, tokenizer_image_object_token
36
+
37
+ from PIL import Image
38
+
39
+
40
+ local_rank = None
41
+
42
+
43
+ def rank0_print(*args):
44
+ if local_rank == 0:
45
+ print(*args)
46
+
47
+
48
+ @dataclass
49
+ class ModelArguments:
50
+ model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
51
+ version: Optional[str] = field(default="v0")
52
+ freeze_backbone: bool = field(default=False)
53
+ tune_mm_mlp_adapter: bool = field(default=False)
54
+ vision_tower: Optional[str] = field(default=None)
55
+ mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer
56
+ pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
57
+ mm_projector_type: Optional[str] = field(default='linear')
58
+ mm_use_im_start_end: bool = field(default=False)
59
+ mm_use_im_patch_token: bool = field(default=True)
60
+ mm_vision_select_feature: Optional[str] = field(default="patch")
61
+
62
+
63
+ @dataclass
64
+ class DataArguments:
65
+ data_path: str = field(default=None,
66
+ metadata={"help": "Path to the training data."})
67
+ lazy_preprocess: bool = False
68
+ is_multimodal: bool = False
69
+ image_folder: Optional[str] = field(default=None)
70
+ image_aspect_ratio: str = 'square'
71
+ image_grid_pinpoints: Optional[str] = field(default=None)
72
+
73
+
74
+ @dataclass
75
+ class TrainingArguments(transformers.TrainingArguments):
76
+ cache_dir: Optional[str] = field(default=None)
77
+ optim: str = field(default="adamw_torch")
78
+ remove_unused_columns: bool = field(default=False)
79
+ freeze_mm_mlp_adapter: bool = field(default=False)
80
+ mpt_attn_impl: Optional[str] = field(default="triton")
81
+ model_max_length: int = field(
82
+ default=512,
83
+ metadata={
84
+ "help":
85
+ "Maximum sequence length. Sequences will be right padded (and possibly truncated)."
86
+ },
87
+ )
88
+ double_quant: bool = field(
89
+ default=True,
90
+ metadata={"help": "Compress the quantization statistics through double quantization."}
91
+ )
92
+ quant_type: str = field(
93
+ default="nf4",
94
+ metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}
95
+ )
96
+ bits: int = field(
97
+ default=16,
98
+ metadata={"help": "How many bits to use."}
99
+ )
100
+ lora_enable: bool = False
101
+ lora_r: int = 64
102
+ lora_alpha: int = 16
103
+ lora_dropout: float = 0.05
104
+ lora_weight_path: str = ""
105
+ lora_bias: str = "none"
106
+ group_by_modality_length: bool = field(default=False)
107
+
108
+
109
+ def maybe_zero_3(param, ignore_status=False, name=None):
110
+ from deepspeed import zero
111
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
112
+ if hasattr(param, "ds_id"):
113
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
114
+ if not ignore_status:
115
+ logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
116
+ with zero.GatheredParameters([param]):
117
+ param = param.data.detach().cpu().clone()
118
+ else:
119
+ param = param.detach().cpu().clone()
120
+ return param
121
+
122
+
123
+ # Borrowed from peft.utils.get_peft_model_state_dict
124
+ def get_peft_state_maybe_zero_3(named_params, bias):
125
+ if bias == "none":
126
+ to_return = {k: t for k, t in named_params if "lora_" in k}
127
+ elif bias == "all":
128
+ to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
129
+ elif bias == "lora_only":
130
+ to_return = {}
131
+ maybe_lora_bias = {}
132
+ lora_bias_names = set()
133
+ for k, t in named_params:
134
+ if "lora_" in k:
135
+ to_return[k] = t
136
+ bias_name = k.split("lora_")[0] + "bias"
137
+ lora_bias_names.add(bias_name)
138
+ elif "bias" in k:
139
+ maybe_lora_bias[k] = t
140
+ for k, t in maybe_lora_bias:
141
+ if bias_name in lora_bias_names:
142
+ to_return[bias_name] = t
143
+ else:
144
+ raise NotImplementedError
145
+ to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
146
+ return to_return
147
+
148
+
149
+ def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
150
+ to_return = {k: t for k, t in named_params if "lora_" not in k}
151
+ if require_grad_only:
152
+ to_return = {k: t for k, t in to_return.items() if t.requires_grad}
153
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
154
+ return to_return
155
+
156
+
157
+ def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
158
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
159
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
160
+ return to_return
161
+
162
+
163
+ def find_all_linear_names(model):
164
+ cls = torch.nn.Linear
165
+ lora_module_names = set()
166
+ multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler']
167
+ for name, module in model.named_modules():
168
+ if any(mm_keyword in name for mm_keyword in multimodal_keywords):
169
+ continue
170
+ if isinstance(module, cls):
171
+ names = name.split('.')
172
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1])
173
+
174
+ if 'lm_head' in lora_module_names: # needed for 16-bit
175
+ lora_module_names.remove('lm_head')
176
+ return list(lora_module_names)
177
+
178
+
179
+ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer,
180
+ output_dir: str):
181
+ """Collects the state dict and dump to disk."""
182
+
183
+ if getattr(trainer.args, "tune_mm_mlp_adapter", False):
184
+ # Only save Adapter
185
+ keys_to_match = ['mm_projector']
186
+ if getattr(trainer.args, "use_im_start_end", False):
187
+ keys_to_match.extend(['embed_tokens', 'embed_in'])
188
+
189
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
190
+ trainer.model.config.save_pretrained(output_dir)
191
+
192
+ current_folder = output_dir.split('/')[-1]
193
+ parent_folder = os.path.dirname(output_dir)
194
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
195
+ if current_folder.startswith('checkpoint-'):
196
+ mm_projector_folder = os.path.join(parent_folder, "mm_projector")
197
+ os.makedirs(mm_projector_folder, exist_ok=True)
198
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
199
+ else:
200
+ torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
201
+ return
202
+
203
+ if trainer.deepspeed:
204
+ torch.cuda.synchronize()
205
+ trainer.save_model(output_dir)
206
+ return
207
+
208
+ state_dict = trainer.model.state_dict()
209
+ if trainer.args.should_save:
210
+ cpu_state_dict = {
211
+ key: value.cpu()
212
+ for key, value in state_dict.items()
213
+ }
214
+ del state_dict
215
+ trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
216
+
217
+
218
+ def smart_tokenizer_and_embedding_resize(
219
+ special_tokens_dict: Dict,
220
+ tokenizer: transformers.PreTrainedTokenizer,
221
+ model: transformers.PreTrainedModel,
222
+ ):
223
+ """Resize tokenizer and embedding.
224
+
225
+ Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
226
+ """
227
+ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
228
+ model.resize_token_embeddings(len(tokenizer))
229
+
230
+ if num_new_tokens > 0:
231
+ input_embeddings = model.get_input_embeddings().weight.data
232
+ output_embeddings = model.get_output_embeddings().weight.data
233
+
234
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
235
+ dim=0, keepdim=True)
236
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
237
+ dim=0, keepdim=True)
238
+
239
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
240
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
241
+
242
+
243
+ def _tokenize_fn(strings: Sequence[str],
244
+ tokenizer: transformers.PreTrainedTokenizer) -> Dict:
245
+ """Tokenize a list of strings."""
246
+ tokenized_list = [
247
+ tokenizer(
248
+ text,
249
+ return_tensors="pt",
250
+ padding="longest",
251
+ max_length=tokenizer.model_max_length,
252
+ truncation=True,
253
+ ) for text in strings
254
+ ]
255
+ input_ids = labels = [
256
+ tokenized.input_ids[0] for tokenized in tokenized_list
257
+ ]
258
+ input_ids_lens = labels_lens = [
259
+ tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item()
260
+ for tokenized in tokenized_list
261
+ ]
262
+ return dict(
263
+ input_ids=input_ids,
264
+ labels=labels,
265
+ input_ids_lens=input_ids_lens,
266
+ labels_lens=labels_lens,
267
+ )
268
+
269
+
270
+ def _mask_targets(target, tokenized_lens, speakers):
271
+ # cur_idx = 0
272
+ cur_idx = tokenized_lens[0]
273
+ tokenized_lens = tokenized_lens[1:]
274
+ target[:cur_idx] = IGNORE_INDEX
275
+ for tokenized_len, speaker in zip(tokenized_lens, speakers):
276
+ if speaker == "human":
277
+ target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX
278
+ cur_idx += tokenized_len
279
+
280
+
281
+ def _add_speaker_and_signal(header, source, get_conversation=True):
282
+ """Add speaker and start/end signal on each round."""
283
+ BEGIN_SIGNAL = "### "
284
+ END_SIGNAL = "\n"
285
+ conversation = header
286
+ for sentence in source:
287
+ from_str = sentence["from"]
288
+ if from_str.lower() == "human":
289
+ from_str = conversation_lib.default_conversation.roles[0]
290
+ elif from_str.lower() == "gpt":
291
+ from_str = conversation_lib.default_conversation.roles[1]
292
+ else:
293
+ from_str = 'unknown'
294
+ sentence["value"] = (BEGIN_SIGNAL + from_str + ": " +
295
+ sentence["value"] + END_SIGNAL)
296
+ if get_conversation:
297
+ conversation += sentence["value"]
298
+ conversation += BEGIN_SIGNAL
299
+ return conversation
300
+
301
+
302
+ def preprocess_multimodal(
303
+ sources: Sequence[str],
304
+ data_args: DataArguments
305
+ ) -> Dict:
306
+ is_multimodal = data_args.is_multimodal
307
+ if not is_multimodal:
308
+ return sources
309
+
310
+ for source in sources:
311
+ for sentence in source:
312
+ if DEFAULT_IMAGE_TOKEN in sentence['value']:
313
+ sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip()
314
+ sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value']
315
+ sentence['value'] = sentence['value'].strip()
316
+ if "mmtag" in conversation_lib.default_conversation.version:
317
+ sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '<Image>' + DEFAULT_IMAGE_TOKEN + '</Image>')
318
+ replace_token = DEFAULT_IMAGE_TOKEN
319
+ if data_args.mm_use_im_start_end:
320
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
321
+ sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
322
+
323
+ return sources
324
+
325
+ def preprocess_llama_2(
326
+ sources,
327
+ tokenizer: transformers.PreTrainedTokenizer,
328
+ has_image: bool = False
329
+ ) -> Dict:
330
+ conv = conversation_lib.default_conversation.copy()
331
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
332
+
333
+ # Apply prompt templates
334
+ conversations = []
335
+ for i, source in enumerate(sources):
336
+ if roles[source[0]["from"]] != conv.roles[0]:
337
+ # Skip the first one if it is not from human
338
+ source = source[1:]
339
+
340
+ conv.messages = []
341
+ for j, sentence in enumerate(source):
342
+ role = roles[sentence["from"]]
343
+ assert role == conv.roles[j % 2], f"{i}"
344
+ conv.append_message(role, sentence["value"])
345
+ conversations.append(conv.get_prompt())
346
+
347
+ # Tokenize conversations
348
+
349
+ if has_image:
350
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
351
+ else:
352
+ input_ids = tokenizer(
353
+ conversations,
354
+ return_tensors="pt",
355
+ padding="longest",
356
+ max_length=tokenizer.model_max_length,
357
+ truncation=True,
358
+ ).input_ids
359
+
360
+ targets = input_ids.clone()
361
+
362
+ assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
363
+
364
+ # Mask targets
365
+ sep = "[/INST] "
366
+ for conversation, target in zip(conversations, targets):
367
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
368
+
369
+ rounds = conversation.split(conv.sep2)
370
+ cur_len = 1
371
+ target[:cur_len] = IGNORE_INDEX
372
+ for i, rou in enumerate(rounds):
373
+ if rou == "":
374
+ break
375
+
376
+ parts = rou.split(sep)
377
+ if len(parts) != 2:
378
+ break
379
+ parts[0] += sep
380
+
381
+ if has_image:
382
+ round_len = len(tokenizer_image_token(rou, tokenizer))
383
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
384
+ else:
385
+ round_len = len(tokenizer(rou).input_ids)
386
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
387
+
388
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
389
+
390
+ cur_len += round_len
391
+ target[cur_len:] = IGNORE_INDEX
392
+
393
+ if cur_len < tokenizer.model_max_length:
394
+ if cur_len != total_len:
395
+ target[:] = IGNORE_INDEX
396
+ print(
397
+ f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
398
+ f" (ignored)"
399
+ )
400
+
401
+ return dict(
402
+ input_ids=input_ids,
403
+ labels=targets,
404
+ )
405
+
406
+
407
+ def preprocess_v1(
408
+ sources,
409
+ tokenizer: transformers.PreTrainedTokenizer,
410
+ has_image: bool = False
411
+ ) -> Dict:
412
+ conv = conversation_lib.default_conversation.copy()
413
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
414
+
415
+ # Apply prompt templates
416
+ conversations = []
417
+ for i, source in enumerate(sources):
418
+ if roles[source[0]["from"]] != conv.roles[0]:
419
+ # Skip the first one if it is not from human
420
+ source = source[1:]
421
+
422
+ conv.messages = []
423
+ for j, sentence in enumerate(source):
424
+ role = roles[sentence["from"]]
425
+ assert role == conv.roles[j % 2], f"{i}"
426
+ conv.append_message(role, sentence["value"])
427
+ conversations.append(conv.get_prompt())
428
+
429
+ # Tokenize conversations
430
+
431
+ if has_image:
432
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
433
+ else:
434
+ input_ids = tokenizer(
435
+ conversations,
436
+ return_tensors="pt",
437
+ padding="longest",
438
+ max_length=tokenizer.model_max_length,
439
+ truncation=True,
440
+ ).input_ids
441
+
442
+ targets = input_ids.clone()
443
+
444
+ assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
445
+
446
+ # Mask targets
447
+ sep = conv.sep + conv.roles[1] + ": "
448
+ for conversation, target in zip(conversations, targets):
449
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
450
+
451
+ rounds = conversation.split(conv.sep2)
452
+ cur_len = 1
453
+ target[:cur_len] = IGNORE_INDEX
454
+ for i, rou in enumerate(rounds):
455
+ if rou == "":
456
+ break
457
+
458
+ parts = rou.split(sep)
459
+ if len(parts) != 2:
460
+ break
461
+ parts[0] += sep
462
+
463
+ if has_image:
464
+ round_len = len(tokenizer_image_token(rou, tokenizer))
465
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
466
+ else:
467
+ round_len = len(tokenizer(rou).input_ids)
468
+ instruction_len = len(tokenizer(parts[0]).input_ids) - 2
469
+
470
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
471
+
472
+ cur_len += round_len
473
+ target[cur_len:] = IGNORE_INDEX
474
+
475
+ if cur_len < tokenizer.model_max_length:
476
+ if cur_len != total_len:
477
+ target[:] = IGNORE_INDEX
478
+ print(
479
+ f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
480
+ f" (ignored)"
481
+ )
482
+
483
+ return dict(
484
+ input_ids=input_ids,
485
+ labels=targets,
486
+ )
487
+
488
+
489
+ def preprocess_mpt(
490
+ sources,
491
+ tokenizer: transformers.PreTrainedTokenizer,
492
+ ) -> Dict:
493
+ conv = conversation_lib.default_conversation.copy()
494
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
495
+
496
+ # Apply prompt templates
497
+ conversations = []
498
+ for i, source in enumerate(sources):
499
+ if roles[source[0]["from"]] != conv.roles[0]:
500
+ # Skip the first one if it is not from human
501
+ source = source[1:]
502
+
503
+ conv.messages = []
504
+ for j, sentence in enumerate(source):
505
+ role = roles[sentence["from"]]
506
+ assert role == conv.roles[j % 2], f"{i}"
507
+ conv.append_message(role, sentence["value"])
508
+ conversations.append(conv.get_prompt())
509
+
510
+ # Tokenize conversations
511
+ input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
512
+ targets = input_ids.clone()
513
+ assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
514
+
515
+ # Mask targets
516
+ sep = conv.sep + conv.roles[1]
517
+ for conversation, target in zip(conversations, targets):
518
+ total_len = int(target.ne(tokenizer.pad_token_id).sum())
519
+
520
+ rounds = conversation.split(conv.sep)
521
+ re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
522
+ for conv_idx in range(3, len(rounds), 2):
523
+ re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt
524
+ cur_len = 0
525
+ target[:cur_len] = IGNORE_INDEX
526
+ for i, rou in enumerate(re_rounds):
527
+ if rou == "":
528
+ break
529
+
530
+ parts = rou.split(sep)
531
+ if len(parts) != 2:
532
+ break
533
+ parts[0] += sep
534
+ round_len = len(tokenizer_image_token(rou, tokenizer)) + len(tokenizer_image_token(conv.sep, tokenizer))
535
+ instruction_len = len(tokenizer_image_token(parts[0], tokenizer))
536
+ target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
537
+
538
+ cur_len += round_len
539
+ target[cur_len:] = IGNORE_INDEX
540
+
541
+ if cur_len < tokenizer.model_max_length:
542
+ if cur_len != total_len:
543
+ target[:] = IGNORE_INDEX
544
+ print(
545
+ f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
546
+ f" (ignored)"
547
+ )
548
+
549
+ return dict(
550
+ input_ids=input_ids,
551
+ labels=targets,
552
+ )
553
+
554
+
555
+ def preprocess_plain(
556
+ sources: Sequence[str],
557
+ tokenizer: transformers.PreTrainedTokenizer,
558
+ ) -> Dict:
559
+ # add end signal and concatenate together
560
+ conversations = []
561
+ for source in sources:
562
+ assert len(source) == 2
563
+ assert DEFAULT_IMAGE_TOKEN in source[0]['value']
564
+ source[0]['value'] = DEFAULT_IMAGE_TOKEN
565
+ conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep
566
+ conversations.append(conversation)
567
+ # tokenize conversations
568
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
569
+ targets = copy.deepcopy(input_ids)
570
+ for target, source in zip(targets, sources):
571
+ tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer))
572
+ target[:tokenized_len] = IGNORE_INDEX
573
+
574
+ return dict(input_ids=input_ids, labels=targets)
575
+
576
+
577
+ def preprocess(
578
+ sources: Sequence[str],
579
+ tokenizer: transformers.PreTrainedTokenizer,
580
+ has_image: bool = False
581
+ ) -> Dict:
582
+ """
583
+ Given a list of sources, each is a conversation list. This transform:
584
+ 1. Add signal '### ' at the beginning each sentence, with end signal '\n';
585
+ 2. Concatenate conversations together;
586
+ 3. Tokenize the concatenated conversation;
587
+ 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
588
+ """
589
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN:
590
+ return preprocess_plain(sources, tokenizer)
591
+ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2:
592
+ return preprocess_llama_2(sources, tokenizer, has_image=has_image)
593
+ if conversation_lib.default_conversation.version.startswith("v1"):
594
+ return preprocess_v1(sources, tokenizer, has_image=has_image)
595
+ if conversation_lib.default_conversation.version == "mpt":
596
+ return preprocess_mpt(sources, tokenizer)
597
+ # add end signal and concatenate together
598
+ conversations = []
599
+ for source in sources:
600
+ header = f"{conversation_lib.default_conversation.system}\n\n"
601
+ conversation = _add_speaker_and_signal(header, source)
602
+ conversations.append(conversation)
603
+ # tokenize conversations
604
+ def get_tokenize_len(prompts):
605
+ return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
606
+
607
+ if has_image:
608
+ input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
609
+ else:
610
+ conversations_tokenized = _tokenize_fn(conversations, tokenizer)
611
+ input_ids = conversations_tokenized["input_ids"]
612
+
613
+ targets = copy.deepcopy(input_ids)
614
+ for target, source in zip(targets, sources):
615
+ if has_image:
616
+ tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
617
+ else:
618
+ tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"]
619
+ speakers = [sentence["from"] for sentence in source]
620
+ _mask_targets(target, tokenized_lens, speakers)
621
+
622
+ return dict(input_ids=input_ids, labels=targets)
623
+
624
+
625
+ class LazySupervisedDataset(Dataset):
626
+ """Dataset for supervised fine-tuning."""
627
+
628
+ def __init__(self, data_path: str,
629
+ tokenizer: transformers.PreTrainedTokenizer,
630
+ data_args: DataArguments):
631
+ super(LazySupervisedDataset, self).__init__()
632
+ list_data_dict = json.load(open(data_path, "r"))
633
+
634
+ rank0_print("Formatting inputs...Skip in lazy mode")
635
+ self.tokenizer = tokenizer
636
+ self.list_data_dict = list_data_dict
637
+ self.data_args = data_args
638
+
639
+ def __len__(self):
640
+ return len(self.list_data_dict)
641
+
642
+ @property
643
+ def lengths(self):
644
+ length_list = []
645
+ for sample in self.list_data_dict:
646
+ img_tokens = 128 if 'image' in sample else 0
647
+ length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens)
648
+ return length_list
649
+
650
+ @property
651
+ def modality_lengths(self):
652
+ length_list = []
653
+ for sample in self.list_data_dict:
654
+ cur_len = sum(len(conv['value'].split()) for conv in sample['conversations'])
655
+ cur_len = cur_len if 'image' in sample else -cur_len
656
+ length_list.append(cur_len)
657
+ return length_list
658
+
659
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
660
+ sources = self.list_data_dict[i]
661
+ if isinstance(i, int):
662
+ sources = [sources]
663
+ assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
664
+ if 'image' in sources[0]:
665
+ image_file = self.list_data_dict[i]['image']
666
+ image_folder = self.data_args.image_folder
667
+ processor = self.data_args.image_processor
668
+ image = Image.open(os.path.join(image_folder, image_file)).convert('RGB')
669
+ if self.data_args.image_aspect_ratio == 'pad':
670
+ def expand2square(pil_img, background_color):
671
+ width, height = pil_img.size
672
+ if width == height:
673
+ return pil_img
674
+ elif width > height:
675
+ result = Image.new(pil_img.mode, (width, width), background_color)
676
+ result.paste(pil_img, (0, (width - height) // 2))
677
+ return result
678
+ else:
679
+ result = Image.new(pil_img.mode, (height, height), background_color)
680
+ result.paste(pil_img, ((height - width) // 2, 0))
681
+ return result
682
+ image = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
683
+ image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
684
+ else:
685
+ image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
686
+ sources = preprocess_multimodal(
687
+ copy.deepcopy([e["conversations"] for e in sources]),
688
+ self.data_args)
689
+ else:
690
+ sources = copy.deepcopy([e["conversations"] for e in sources])
691
+ data_dict = preprocess(
692
+ sources,
693
+ self.tokenizer,
694
+ has_image=('image' in self.list_data_dict[i]))
695
+ if isinstance(i, int):
696
+ data_dict = dict(input_ids=data_dict["input_ids"][0],
697
+ labels=data_dict["labels"][0])
698
+
699
+ # image exist in the data
700
+ if 'image' in self.list_data_dict[i]:
701
+ data_dict['image'] = image
702
+ elif self.data_args.is_multimodal:
703
+ # image does not exist in the data, but the model is multimodal
704
+ crop_size = self.data_args.image_processor.crop_size
705
+ data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width'])
706
+ return data_dict
707
+
708
+
709
+ @dataclass
710
+ class DataCollatorForSupervisedDataset(object):
711
+ """Collate examples for supervised fine-tuning."""
712
+
713
+ tokenizer: transformers.PreTrainedTokenizer
714
+
715
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
716
+ input_ids, labels = tuple([instance[key] for instance in instances]
717
+ for key in ("input_ids", "labels"))
718
+ input_ids = torch.nn.utils.rnn.pad_sequence(
719
+ input_ids,
720
+ batch_first=True,
721
+ padding_value=self.tokenizer.pad_token_id)
722
+ labels = torch.nn.utils.rnn.pad_sequence(labels,
723
+ batch_first=True,
724
+ padding_value=IGNORE_INDEX)
725
+ input_ids = input_ids[:, :self.tokenizer.model_max_length]
726
+ labels = labels[:, :self.tokenizer.model_max_length]
727
+ batch = dict(
728
+ input_ids=input_ids,
729
+ labels=labels,
730
+ attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
731
+ )
732
+
733
+ if 'image' in instances[0]:
734
+ images = [instance['image'] for instance in instances]
735
+ if all(x is not None and x.shape == images[0].shape for x in images):
736
+ batch['images'] = torch.stack(images)
737
+ else:
738
+ batch['images'] = images
739
+
740
+ return batch
741
+
742
+
743
+ def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
744
+ data_args) -> Dict:
745
+ """Make dataset and collator for supervised fine-tuning."""
746
+ train_dataset = LazySupervisedDataset(tokenizer=tokenizer,
747
+ data_path=data_args.data_path,
748
+ data_args=data_args)
749
+ data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
750
+ return dict(train_dataset=train_dataset,
751
+ eval_dataset=None,
752
+ data_collator=data_collator)
753
+
754
+
755
+ def train():
756
+ global local_rank
757
+
758
+ parser = transformers.HfArgumentParser(
759
+ (ModelArguments, DataArguments, TrainingArguments))
760
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
761
+ local_rank = training_args.local_rank
762
+ compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
763
+
764
+ bnb_model_from_pretrained_args = {}
765
+ if training_args.bits in [4, 8]:
766
+ from transformers import BitsAndBytesConfig
767
+ bnb_model_from_pretrained_args.update(dict(
768
+ device_map={"": training_args.device},
769
+ load_in_4bit=training_args.bits == 4,
770
+ load_in_8bit=training_args.bits == 8,
771
+ quantization_config=BitsAndBytesConfig(
772
+ load_in_4bit=training_args.bits == 4,
773
+ load_in_8bit=training_args.bits == 8,
774
+ llm_int8_threshold=6.0,
775
+ llm_int8_has_fp16_weight=False,
776
+ bnb_4bit_compute_dtype=compute_dtype,
777
+ bnb_4bit_use_double_quant=training_args.double_quant,
778
+ bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'}
779
+ )
780
+ ))
781
+
782
+ if model_args.vision_tower is not None:
783
+ if 'mpt' in model_args.model_name_or_path:
784
+ config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True)
785
+ config.attn_config['attn_impl'] = training_args.mpt_attn_impl
786
+ model = LlavaMPTForCausalLM.from_pretrained(
787
+ model_args.model_name_or_path,
788
+ config=config,
789
+ cache_dir=training_args.cache_dir,
790
+ **bnb_model_from_pretrained_args
791
+ )
792
+ else:
793
+ model = LlavaLlamaForCausalLM.from_pretrained(
794
+ model_args.model_name_or_path,
795
+ cache_dir=training_args.cache_dir,
796
+ **bnb_model_from_pretrained_args
797
+ )
798
+ else:
799
+ model = transformers.LlamaForCausalLM.from_pretrained(
800
+ model_args.model_name_or_path,
801
+ cache_dir=training_args.cache_dir,
802
+ **bnb_model_from_pretrained_args
803
+ )
804
+ model.config.use_cache = False
805
+
806
+ if model_args.freeze_backbone:
807
+ model.model.requires_grad_(False)
808
+
809
+ if training_args.bits in [4, 8]:
810
+ from peft import prepare_model_for_kbit_training
811
+ model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
812
+ model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
813
+
814
+ if training_args.gradient_checkpointing:
815
+ if hasattr(model, "enable_input_require_grads"):
816
+ model.enable_input_require_grads()
817
+ else:
818
+ def make_inputs_require_grad(module, input, output):
819
+ output.requires_grad_(True)
820
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
821
+
822
+ if training_args.lora_enable:
823
+ from peft import LoraConfig, get_peft_model
824
+ lora_config = LoraConfig(
825
+ r=training_args.lora_r,
826
+ lora_alpha=training_args.lora_alpha,
827
+ target_modules=find_all_linear_names(model),
828
+ lora_dropout=training_args.lora_dropout,
829
+ bias=training_args.lora_bias,
830
+ task_type="CAUSAL_LM",
831
+ )
832
+ if training_args.bits == 16:
833
+ if training_args.bf16:
834
+ model.to(torch.bfloat16)
835
+ if training_args.fp16:
836
+ model.to(torch.float16)
837
+ rank0_print("Adding LoRA adapters...")
838
+ model = get_peft_model(model, lora_config)
839
+
840
+ if 'mpt' in model_args.model_name_or_path:
841
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
842
+ model_args.model_name_or_path,
843
+ cache_dir=training_args.cache_dir,
844
+ model_max_length=training_args.model_max_length,
845
+ padding_side="right"
846
+ )
847
+ else:
848
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
849
+ model_args.model_name_or_path,
850
+ cache_dir=training_args.cache_dir,
851
+ model_max_length=training_args.model_max_length,
852
+ padding_side="right",
853
+ use_fast=False,
854
+ )
855
+
856
+ if model_args.version == "v0":
857
+ if tokenizer.pad_token is None:
858
+ smart_tokenizer_and_embedding_resize(
859
+ special_tokens_dict=dict(pad_token="[PAD]"),
860
+ tokenizer=tokenizer,
861
+ model=model,
862
+ )
863
+ elif model_args.version == "v0.5":
864
+ tokenizer.pad_token = tokenizer.unk_token
865
+ else:
866
+ tokenizer.pad_token = tokenizer.unk_token
867
+ if model_args.version in conversation_lib.conv_templates:
868
+ conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
869
+ else:
870
+ conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
871
+
872
+ if model_args.vision_tower is not None:
873
+ model.get_model().initialize_vision_modules(
874
+ model_args=model_args,
875
+ fsdp=training_args.fsdp
876
+ )
877
+
878
+ vision_tower = model.get_vision_tower()
879
+ vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
880
+
881
+ data_args.image_processor = vision_tower.image_processor
882
+ data_args.is_multimodal = True
883
+
884
+ model.config.image_aspect_ratio = data_args.image_aspect_ratio
885
+ model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
886
+
887
+ model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
888
+ if model_args.tune_mm_mlp_adapter:
889
+ model.requires_grad_(False)
890
+ for p in model.get_model().mm_projector.parameters():
891
+ p.requires_grad = True
892
+
893
+ model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
894
+ if training_args.freeze_mm_mlp_adapter:
895
+ for p in model.get_model().mm_projector.parameters():
896
+ p.requires_grad = False
897
+
898
+ if training_args.bits in [4, 8]:
899
+ model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
900
+
901
+ model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end
902
+ training_args.use_im_start_end = model_args.mm_use_im_start_end
903
+ model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
904
+ model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
905
+
906
+ if training_args.bits in [4, 8]:
907
+ from peft.tuners.lora import LoraLayer
908
+ for name, module in model.named_modules():
909
+ if isinstance(module, LoraLayer):
910
+ if training_args.bf16:
911
+ module = module.to(torch.bfloat16)
912
+ if 'norm' in name:
913
+ module = module.to(torch.float32)
914
+ if 'lm_head' in name or 'embed_tokens' in name:
915
+ if hasattr(module, 'weight'):
916
+ if training_args.bf16 and module.weight.dtype == torch.float32:
917
+ module = module.to(torch.bfloat16)
918
+
919
+ data_module = make_supervised_data_module(tokenizer=tokenizer,
920
+ data_args=data_args)
921
+ trainer = LLaVATrainer(model=model,
922
+ tokenizer=tokenizer,
923
+ args=training_args,
924
+ **data_module)
925
+
926
+ if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
927
+ trainer.train(resume_from_checkpoint=True)
928
+ else:
929
+ trainer.train()
930
+ trainer.save_state()
931
+
932
+ model.config.use_cache = True
933
+
934
+ if training_args.lora_enable:
935
+ state_dict = get_peft_state_maybe_zero_3(
936
+ model.named_parameters(), training_args.lora_bias
937
+ )
938
+ non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(
939
+ model.named_parameters()
940
+ )
941
+ if training_args.local_rank == 0 or training_args.local_rank == -1:
942
+ model.config.save_pretrained(training_args.output_dir)
943
+ model.save_pretrained(training_args.output_dir, state_dict=state_dict)
944
+ torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin'))
945
+ else:
946
+ safe_save_model_for_hf_trainer(trainer=trainer,
947
+ output_dir=training_args.output_dir)
948
+
949
+
950
+ if __name__ == "__main__":
951
+ train()